imgui.cpp 617 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822
  1. // dear imgui, v1.87 WIP
  2. // (main code and documentation)
  3. // Help:
  4. // - Read FAQ at http://dearimgui.org/faq
  5. // - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
  6. // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
  7. // Read imgui.cpp for details, links and comments.
  8. // Resources:
  9. // - FAQ http://dearimgui.org/faq
  10. // - Homepage & latest https://github.com/ocornut/imgui
  11. // - Releases & changelog https://github.com/ocornut/imgui/releases
  12. // - Gallery https://github.com/ocornut/imgui/issues/4451 (please post your screenshots/video there!)
  13. // - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there)
  14. // - Glossary https://github.com/ocornut/imgui/wiki/Glossary
  15. // - Issues & support https://github.com/ocornut/imgui/issues
  16. // Getting Started?
  17. // - For first-time users having issues compiling/linking/running or issues loading fonts:
  18. // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
  19. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  20. // See LICENSE.txt for copyright and licensing details (standard MIT License).
  21. // This library is free but needs your support to sustain development and maintenance.
  22. // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
  23. // Individuals: you can support continued development via donations. See docs/README or web page.
  24. // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
  25. // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
  26. // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
  27. // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
  28. // to a better solution or official support for them.
  29. /*
  30. Index of this file:
  31. DOCUMENTATION
  32. - MISSION STATEMENT
  33. - END-USER GUIDE
  34. - PROGRAMMER GUIDE
  35. - READ FIRST
  36. - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  37. - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  38. - HOW A SIMPLE APPLICATION MAY LOOK LIKE
  39. - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  40. - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  41. - API BREAKING CHANGES (read me when you update!)
  42. - FREQUENTLY ASKED QUESTIONS (FAQ)
  43. - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
  44. CODE
  45. (search for "[SECTION]" in the code to find them)
  46. // [SECTION] INCLUDES
  47. // [SECTION] FORWARD DECLARATIONS
  48. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  49. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  50. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  51. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  52. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  53. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  54. // [SECTION] MISC HELPERS/UTILITIES (Color functions)
  55. // [SECTION] ImGuiStorage
  56. // [SECTION] ImGuiTextFilter
  57. // [SECTION] ImGuiTextBuffer
  58. // [SECTION] ImGuiListClipper
  59. // [SECTION] STYLING
  60. // [SECTION] RENDER HELPERS
  61. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  62. // [SECTION] INPUTS
  63. // [SECTION] ERROR CHECKING
  64. // [SECTION] LAYOUT
  65. // [SECTION] SCROLLING
  66. // [SECTION] TOOLTIPS
  67. // [SECTION] POPUPS
  68. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  69. // [SECTION] DRAG AND DROP
  70. // [SECTION] LOGGING/CAPTURING
  71. // [SECTION] SETTINGS
  72. // [SECTION] VIEWPORTS
  73. // [SECTION] PLATFORM DEPENDENT HELPERS
  74. // [SECTION] METRICS/DEBUGGER WINDOW
  75. // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
  76. */
  77. //-----------------------------------------------------------------------------
  78. // DOCUMENTATION
  79. //-----------------------------------------------------------------------------
  80. /*
  81. MISSION STATEMENT
  82. =================
  83. - Easy to use to create code-driven and data-driven tools.
  84. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
  85. - Easy to hack and improve.
  86. - Minimize setup and maintenance.
  87. - Minimize state storage on user side.
  88. - Portable, minimize dependencies, run on target (consoles, phones, etc.).
  89. - Efficient runtime and memory consumption.
  90. Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
  91. - Doesn't look fancy, doesn't animate.
  92. - Limited layout features, intricate layouts are typically crafted in code.
  93. END-USER GUIDE
  94. ==============
  95. - Double-click on title bar to collapse window.
  96. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
  97. - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
  98. - Click and drag on any empty space to move window.
  99. - TAB/SHIFT+TAB to cycle through keyboard editable fields.
  100. - CTRL+Click on a slider or drag box to input value as text.
  101. - Use mouse wheel to scroll.
  102. - Text editor:
  103. - Hold SHIFT or use mouse to select text.
  104. - CTRL+Left/Right to word jump.
  105. - CTRL+Shift+Left/Right to select words.
  106. - CTRL+A our Double-Click to select all.
  107. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
  108. - CTRL+Z,CTRL+Y to undo/redo.
  109. - ESCAPE to revert text to its original value.
  110. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  111. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  112. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
  113. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://dearimgui.org/controls_sheets
  114. PROGRAMMER GUIDE
  115. ================
  116. READ FIRST
  117. ----------
  118. - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
  119. - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
  120. destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
  121. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
  122. - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
  123. - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
  124. You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
  125. - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
  126. For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
  127. where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
  128. - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
  129. - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
  130. - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
  131. If you get an assert, read the messages and comments around the assert.
  132. - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
  133. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
  134. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
  135. However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
  136. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
  137. HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  138. ----------------------------------------------
  139. - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
  140. - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
  141. - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
  142. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  143. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
  144. from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
  145. likely be a comment about it. Please report any issue to the GitHub page!
  146. - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
  147. - Try to keep your copy of Dear ImGui reasonably up to date.
  148. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  149. ---------------------------------------------------------------
  150. - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
  151. - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
  152. - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
  153. It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
  154. - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
  155. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
  156. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
  157. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
  158. phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
  159. - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
  160. - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
  161. HOW A SIMPLE APPLICATION MAY LOOK LIKE
  162. --------------------------------------
  163. EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
  164. The sub-folders in examples/ contain examples applications following this structure.
  165. // Application init: create a dear imgui context, setup some options, load fonts
  166. ImGui::CreateContext();
  167. ImGuiIO& io = ImGui::GetIO();
  168. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  169. // TODO: Fill optional fields of the io structure later.
  170. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  171. // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
  172. ImGui_ImplWin32_Init(hwnd);
  173. ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
  174. // Application main loop
  175. while (true)
  176. {
  177. // Feed inputs to dear imgui, start new frame
  178. ImGui_ImplDX11_NewFrame();
  179. ImGui_ImplWin32_NewFrame();
  180. ImGui::NewFrame();
  181. // Any application code here
  182. ImGui::Text("Hello, world!");
  183. // Render dear imgui into screen
  184. ImGui::Render();
  185. ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
  186. g_pSwapChain->Present(1, 0);
  187. }
  188. // Shutdown
  189. ImGui_ImplDX11_Shutdown();
  190. ImGui_ImplWin32_Shutdown();
  191. ImGui::DestroyContext();
  192. EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
  193. // Application init: create a dear imgui context, setup some options, load fonts
  194. ImGui::CreateContext();
  195. ImGuiIO& io = ImGui::GetIO();
  196. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  197. // TODO: Fill optional fields of the io structure later.
  198. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  199. // Build and load the texture atlas into a texture
  200. // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
  201. int width, height;
  202. unsigned char* pixels = NULL;
  203. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  204. // At this point you've got the texture data and you need to upload that to your graphic system:
  205. // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
  206. // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
  207. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
  208. io.Fonts->SetTexID((void*)texture);
  209. // Application main loop
  210. while (true)
  211. {
  212. // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
  213. // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
  214. io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
  215. io.DisplaySize.x = 1920.0f; // set the current display width
  216. io.DisplaySize.y = 1280.0f; // set the current display height here
  217. io.MousePos = my_mouse_pos; // set the mouse position
  218. io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
  219. io.MouseDown[1] = my_mouse_buttons[1];
  220. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  221. // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
  222. ImGui::NewFrame();
  223. // Most of your application code here
  224. ImGui::Text("Hello, world!");
  225. MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  226. MyGameRender(); // may use any Dear ImGui functions as well!
  227. // Render dear imgui, swap buffers
  228. // (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)
  229. ImGui::EndFrame();
  230. ImGui::Render();
  231. ImDrawData* draw_data = ImGui::GetDrawData();
  232. MyImGuiRenderFunction(draw_data);
  233. SwapBuffers();
  234. }
  235. // Shutdown
  236. ImGui::DestroyContext();
  237. To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
  238. you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
  239. Please read the FAQ and example applications for details about this!
  240. HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  241. ---------------------------------------------
  242. The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
  243. void void MyImGuiRenderFunction(ImDrawData* draw_data)
  244. {
  245. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  246. // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  247. // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  248. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  249. ImVec2 clip_off = draw_data->DisplayPos;
  250. for (int n = 0; n < draw_data->CmdListsCount; n++)
  251. {
  252. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  253. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
  254. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
  255. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  256. {
  257. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  258. if (pcmd->UserCallback)
  259. {
  260. pcmd->UserCallback(cmd_list, pcmd);
  261. }
  262. else
  263. {
  264. // Project scissor/clipping rectangles into framebuffer space
  265. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  266. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  267. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  268. continue;
  269. // We are using scissoring to clip some objects. All low-level graphics API should support it.
  270. // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
  271. // (some elements visible outside their bounds) but you can fix that once everything else works!
  272. // - Clipping coordinates are provided in imgui coordinates space:
  273. // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
  274. // - 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.
  275. // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
  276. // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
  277. // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
  278. MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
  279. // The texture for the draw call is specified by pcmd->GetTexID().
  280. // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
  281. MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
  282. // Render 'pcmd->ElemCount/3' indexed triangles.
  283. // 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.
  284. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
  285. }
  286. }
  287. }
  288. }
  289. USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  290. ------------------------------------------
  291. - The gamepad/keyboard navigation is fairly functional and keeps being improved.
  292. - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
  293. - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
  294. - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
  295. - Keyboard:
  296. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
  297. NewFrame() will automatically fill io.NavInputs[] based on your io.AddKeyEvent() calls.
  298. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
  299. will be set. For more advanced uses, you may want to read from:
  300. - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
  301. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
  302. - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
  303. Please reach out if you think the game vs navigation input sharing could be improved.
  304. - Gamepad:
  305. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
  306. - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
  307. Note that io.NavInputs[] is cleared by EndFrame().
  308. - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
  309. 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
  310. - We use a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
  311. Your 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.).
  312. - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
  313. - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
  314. to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
  315. - Mouse:
  316. - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
  317. - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
  318. - 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.
  319. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
  320. 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.
  321. 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.
  322. (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)
  323. (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
  324. to set a boolean to ignore your other external mouse positions until the external source is moved again.)
  325. API BREAKING CHANGES
  326. ====================
  327. Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
  328. Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
  329. 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.
  330. You can read releases logs https://github.com/ocornut/imgui/releases for more details.
  331. - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. 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.
  332. - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
  333. - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
  334. - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent()
  335. - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
  336. - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
  337. - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
  338. - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
  339. - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
  340. - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
  341. - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
  342. - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
  343. - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
  344. - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
  345. - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
  346. - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
  347. - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
  348. - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
  349. - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
  350. - if you are using official backends from the source tree: you have nothing to do.
  351. - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
  352. - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
  353. - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
  354. - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
  355. - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
  356. flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
  357. breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
  358. - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
  359. - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
  360. - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
  361. - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
  362. this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
  363. the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
  364. legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
  365. - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
  366. - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
  367. - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
  368. - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
  369. - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
  370. - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
  371. - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
  372. - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
  373. - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
  374. - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
  375. - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
  376. - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
  377. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
  378. - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
  379. - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
  380. - ImGuiInputTextCallback -> use ImGuiTextEditCallback
  381. - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
  382. - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
  383. - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
  384. - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
  385. - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
  386. - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
  387. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
  388. - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
  389. - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
  390. - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
  391. - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
  392. - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
  393. - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
  394. - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
  395. - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
  396. - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
  397. - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
  398. - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
  399. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
  400. - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
  401. - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
  402. - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
  403. replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
  404. worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
  405. - if you omitted the 'power' parameter (likely!), you are not affected.
  406. - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
  407. - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
  408. see https://github.com/ocornut/imgui/issues/3361 for all details.
  409. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
  410. for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
  411. - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
  412. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
  413. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
  414. - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
  415. - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
  416. - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
  417. - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
  418. - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
  419. - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
  420. - ShowTestWindow() -> use ShowDemoWindow()
  421. - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
  422. - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
  423. - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
  424. - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
  425. - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
  426. - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
  427. - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
  428. - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
  429. - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
  430. - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
  431. - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
  432. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
  433. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
  434. - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
  435. - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
  436. - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
  437. - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
  438. - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
  439. - ImFont::Glyph -> use ImFontGlyph
  440. - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
  441. if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
  442. The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
  443. If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
  444. - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
  445. - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
  446. - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
  447. - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
  448. overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
  449. This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
  450. Please reach out if you are affected.
  451. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
  452. - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
  453. - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
  454. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
  455. - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
  456. - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
  457. - 2019/02/14 (1.68) - 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 an arbitrarily small value!
  458. - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
  459. - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
  460. - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
  461. - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
  462. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
  463. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
  464. - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
  465. - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
  466. If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
  467. - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
  468. - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
  469. NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
  470. Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
  471. - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
  472. - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
  473. - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
  474. - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
  475. - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
  476. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
  477. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
  478. - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
  479. old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
  480. when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
  481. in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
  482. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
  483. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
  484. - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
  485. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
  486. To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
  487. If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
  488. - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
  489. consistent with other functions. Kept redirection functions (will obsolete).
  490. - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
  491. - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
  492. - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
  493. - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
  494. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
  495. - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
  496. - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
  497. - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
  498. - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
  499. - removed Shutdown() function, as DestroyContext() serve this purpose.
  500. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
  501. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
  502. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
  503. - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
  504. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
  505. - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
  506. - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
  507. - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
  508. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
  509. - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
  510. - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
  511. - 2017/12/14 (1.53) - 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.
  512. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
  513. - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
  514. - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
  515. - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
  516. - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
  517. - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
  518. - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
  519. Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
  520. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
  521. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
  522. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
  523. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
  524. - 2017/10/24 (1.52) - renamed 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.
  525. - 2017/10/20 (1.52) - 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.
  526. - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
  527. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
  528. IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
  529. IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
  530. IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
  531. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
  532. - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
  533. - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
  534. - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
  535. - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
  536. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
  537. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  538. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  539. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  540. - 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.
  541. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
  542. - 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.
  543. - 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).
  544. - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
  545. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  546. - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
  547. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
  548. - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
  549. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  550. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  551. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  552. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
  553. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  554. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
  555. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
  556. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  557. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <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.
  558. 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:
  559. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
  560. If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
  561. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  562. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  563. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
  564. - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::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.
  565. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
  566. - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
  567. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  568. - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
  569. - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
  570. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  571. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  572. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  573. GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
  574. GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
  575. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  576. - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
  577. - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
  578. - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
  579. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  580. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
  581. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  582. - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
  583. - the signature of the io.RenderDrawListsFn handler has changed!
  584. old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  585. new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  586. parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
  587. ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
  588. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
  589. - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
  590. - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
  591. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  592. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  593. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  594. - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
  595. - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
  596. - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
  597. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  598. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  599. - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
  600. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
  601. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  602. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  603. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  604. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  605. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  606. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  607. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  608. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  609. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  610. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  611. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  612. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  613. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  614. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  615. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  616. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  617. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  618. - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  619. - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
  620. - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
  621. you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
  622. - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
  623. - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  624. - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  625. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  626. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  627. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  628. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  629. - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
  630. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  631. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  632. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  633. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  634. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  635. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  636. FREQUENTLY ASKED QUESTIONS (FAQ)
  637. ================================
  638. Read all answers online:
  639. https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
  640. Read all answers locally (with a text editor or ideally a Markdown viewer):
  641. docs/FAQ.md
  642. Some answers are copied down here to facilitate searching in code.
  643. Q&A: Basics
  644. ===========
  645. Q: Where is the documentation?
  646. A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
  647. - Run the examples/ and explore them.
  648. - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
  649. - The demo covers most features of Dear ImGui, so you can read the code and see its output.
  650. - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
  651. - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
  652. examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
  653. - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
  654. - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
  655. - Your programming IDE is your friend, find the type or function declaration to find comments
  656. associated with it.
  657. Q: What is this library called?
  658. Q: Which version should I get?
  659. >> This library is called "Dear ImGui", please don't call it "ImGui" :)
  660. >> See https://www.dearimgui.org/faq for details.
  661. Q&A: Integration
  662. ================
  663. Q: How to get started?
  664. A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
  665. Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
  666. A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
  667. >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
  668. Q. How can I enable keyboard controls?
  669. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
  670. Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
  671. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
  672. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
  673. >> See https://www.dearimgui.org/faq
  674. Q&A: Usage
  675. ----------
  676. Q: About the ID Stack system..
  677. - Why is my widget not reacting when I click on it?
  678. - How can I have widgets with an empty label?
  679. - How can I have multiple widgets with the same label?
  680. - How can I have multiple windows with the same label?
  681. Q: How can I display an image? What is ImTextureID, how does it works?
  682. Q: How can I use my own math types instead of ImVec2/ImVec4?
  683. Q: How can I interact with standard C++ types (such as std::string and std::vector)?
  684. Q: How can I display custom shapes? (using low-level ImDrawList API)
  685. >> See https://www.dearimgui.org/faq
  686. Q&A: Fonts, Text
  687. ================
  688. Q: How should I handle DPI in my application?
  689. Q: How can I load a different font than the default?
  690. Q: How can I easily use icons in my application?
  691. Q: How can I load multiple fonts?
  692. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  693. >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
  694. Q&A: Concerns
  695. =============
  696. Q: Who uses Dear ImGui?
  697. Q: Can you create elaborate/serious tools with Dear ImGui?
  698. Q: Can you reskin the look of Dear ImGui?
  699. Q: Why using C++ (as opposed to C)?
  700. >> See https://www.dearimgui.org/faq
  701. Q&A: Community
  702. ==============
  703. Q: How can I help?
  704. A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
  705. We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
  706. This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
  707. - Individuals: you can support continued development via PayPal donations. See README.
  708. - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
  709. and see how you want to help and can help!
  710. - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
  711. You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
  712. But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
  713. - 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 (on GitHub or privately).
  714. */
  715. //-------------------------------------------------------------------------
  716. // [SECTION] INCLUDES
  717. //-------------------------------------------------------------------------
  718. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  719. #define _CRT_SECURE_NO_WARNINGS
  720. #endif
  721. #include "imgui.h"
  722. #ifndef IMGUI_DISABLE
  723. #ifndef IMGUI_DEFINE_MATH_OPERATORS
  724. #define IMGUI_DEFINE_MATH_OPERATORS
  725. #endif
  726. #include "imgui_internal.h"
  727. // System includes
  728. #include <ctype.h> // toupper
  729. #include <stdio.h> // vsnprintf, sscanf, printf
  730. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  731. #include <stddef.h> // intptr_t
  732. #else
  733. #include <stdint.h> // intptr_t
  734. #endif
  735. // [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
  736. #if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  737. #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
  738. #endif
  739. // [Windows] OS specific includes (optional)
  740. #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)
  741. #define IMGUI_DISABLE_WIN32_FUNCTIONS
  742. #endif
  743. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
  744. #ifndef WIN32_LEAN_AND_MEAN
  745. #define WIN32_LEAN_AND_MEAN
  746. #endif
  747. #ifndef NOMINMAX
  748. #define NOMINMAX
  749. #endif
  750. #ifndef __MINGW32__
  751. #include <Windows.h> // _wfopen, OpenClipboard
  752. #else
  753. #include <windows.h>
  754. #endif
  755. #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
  756. #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
  757. #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
  758. #endif
  759. #endif
  760. // [Apple] OS specific includes
  761. #if defined(__APPLE__)
  762. #include <TargetConditionals.h>
  763. #endif
  764. // Visual Studio warnings
  765. #ifdef _MSC_VER
  766. #pragma warning (disable: 4127) // condition expression is constant
  767. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  768. #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
  769. #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
  770. #endif
  771. #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).
  772. #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
  773. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  774. #endif
  775. // Clang/GCC warnings with -Weverything
  776. #if defined(__clang__)
  777. #if __has_warning("-Wunknown-warning-option")
  778. #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
  779. #endif
  780. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
  781. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
  782. #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.
  783. #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.
  784. #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.
  785. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
  786. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  787. #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.
  788. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
  789. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
  790. #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.
  791. #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
  792. #elif defined(__GNUC__)
  793. // We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
  794. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  795. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  796. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  797. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  798. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  799. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  800. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  801. #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
  802. #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
  803. #endif
  804. // Debug options
  805. #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
  806. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
  807. #define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
  808. // 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.
  809. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
  810. static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
  811. // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
  812. static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
  813. static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
  814. static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
  815. //-------------------------------------------------------------------------
  816. // [SECTION] FORWARD DECLARATIONS
  817. //-------------------------------------------------------------------------
  818. static void SetCurrentWindow(ImGuiWindow* window);
  819. static void FindHoveredWindow();
  820. static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
  821. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
  822. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
  823. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
  824. // Settings
  825. static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
  826. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
  827. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
  828. static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
  829. static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
  830. // Platform Dependents default implementation for IO functions
  831. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  832. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  833. static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
  834. namespace ImGui
  835. {
  836. // Navigation
  837. static void NavUpdate();
  838. static void NavUpdateWindowing();
  839. static void NavUpdateWindowingOverlay();
  840. static void NavUpdateCancelRequest();
  841. static void NavUpdateCreateMoveRequest();
  842. static void NavUpdateCreateTabbingRequest();
  843. static float NavUpdatePageUpPageDown();
  844. static inline void NavUpdateAnyRequestFlag();
  845. static void NavUpdateCreateWrappingRequest();
  846. static void NavEndFrame();
  847. static bool NavScoreItem(ImGuiNavItemData* result);
  848. static void NavApplyItemToResult(ImGuiNavItemData* result);
  849. static void NavProcessItem();
  850. static void NavProcessItemForTabbingRequest(ImGuiID id);
  851. static ImVec2 NavCalcPreferredRefPos();
  852. static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
  853. static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
  854. static void NavRestoreLayer(ImGuiNavLayer layer);
  855. static void NavRestoreHighlightAfterMove();
  856. static int FindWindowFocusIndex(ImGuiWindow* window);
  857. // Error Checking and Debug Tools
  858. static void ErrorCheckNewFrameSanityChecks();
  859. static void ErrorCheckEndFrameSanityChecks();
  860. static void UpdateDebugToolItemPicker();
  861. static void UpdateDebugToolStackQueries();
  862. // Misc
  863. static void UpdateSettings();
  864. static void UpdateKeyboardInputs();
  865. static void UpdateMouseInputs();
  866. static void UpdateMouseWheel();
  867. static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
  868. static void RenderWindowOuterBorders(ImGuiWindow* window);
  869. static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
  870. static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
  871. static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
  872. static void RenderDimmedBackgrounds();
  873. static ImGuiWindow* FindBlockingModal(ImGuiWindow* window);
  874. // Viewports
  875. static void UpdateViewportsNewFrame();
  876. }
  877. //-----------------------------------------------------------------------------
  878. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  879. //-----------------------------------------------------------------------------
  880. // DLL users:
  881. // - Heaps and globals are not shared across DLL boundaries!
  882. // - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
  883. // - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
  884. // - 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.
  885. // - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
  886. // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
  887. // - ImGui::CreateContext() will automatically set this pointer if it is NULL.
  888. // Change to a different context by calling ImGui::SetCurrentContext().
  889. // - Important: Dear ImGui functions are not thread-safe because of this pointer.
  890. // If you want thread-safety to allow N threads to access N different contexts:
  891. // - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
  892. // struct ImGuiContext;
  893. // extern thread_local ImGuiContext* MyImGuiTLS;
  894. // #define GImGui MyImGuiTLS
  895. // And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
  896. // - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  897. // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
  898. // - DLL users: read comments above.
  899. #ifndef GImGui
  900. ImGuiContext* GImGui = NULL;
  901. #endif
  902. // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
  903. // - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
  904. // - DLL users: read comments above.
  905. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
  906. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
  907. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
  908. #else
  909. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
  910. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
  911. #endif
  912. static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
  913. static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
  914. static void* GImAllocatorUserData = NULL;
  915. //-----------------------------------------------------------------------------
  916. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  917. //-----------------------------------------------------------------------------
  918. ImGuiStyle::ImGuiStyle()
  919. {
  920. Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
  921. DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
  922. WindowPadding = ImVec2(8,8); // Padding within a window
  923. 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.
  924. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  925. WindowMinSize = ImVec2(32,32); // Minimum window size
  926. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  927. WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
  928. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  929. ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  930. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
  931. PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  932. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  933. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  934. FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
  935. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  936. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  937. CellPadding = ImVec2(4,2); // Padding within a table cell
  938. TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
  939. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  940. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
  941. ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  942. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  943. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  944. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  945. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
  946. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
  947. TabBorderSize = 0.0f; // Thickness of border around tabs.
  948. TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appears 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.
  949. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
  950. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  951. 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.
  952. 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.
  953. DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
  954. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
  955. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
  956. AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering.
  957. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
  958. 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.
  959. 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.
  960. // Default theme
  961. ImGui::StyleColorsDark(this);
  962. }
  963. // 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.
  964. // 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.
  965. void ImGuiStyle::ScaleAllSizes(float scale_factor)
  966. {
  967. WindowPadding = ImFloor(WindowPadding * scale_factor);
  968. WindowRounding = ImFloor(WindowRounding * scale_factor);
  969. WindowMinSize = ImFloor(WindowMinSize * scale_factor);
  970. ChildRounding = ImFloor(ChildRounding * scale_factor);
  971. PopupRounding = ImFloor(PopupRounding * scale_factor);
  972. FramePadding = ImFloor(FramePadding * scale_factor);
  973. FrameRounding = ImFloor(FrameRounding * scale_factor);
  974. ItemSpacing = ImFloor(ItemSpacing * scale_factor);
  975. ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
  976. CellPadding = ImFloor(CellPadding * scale_factor);
  977. TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
  978. IndentSpacing = ImFloor(IndentSpacing * scale_factor);
  979. ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
  980. ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
  981. ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
  982. GrabMinSize = ImFloor(GrabMinSize * scale_factor);
  983. GrabRounding = ImFloor(GrabRounding * scale_factor);
  984. LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
  985. TabRounding = ImFloor(TabRounding * scale_factor);
  986. TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
  987. DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
  988. DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
  989. MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
  990. }
  991. ImGuiIO::ImGuiIO()
  992. {
  993. // Most fields are initialized with zero
  994. memset(this, 0, sizeof(*this));
  995. IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
  996. // Settings
  997. ConfigFlags = ImGuiConfigFlags_None;
  998. BackendFlags = ImGuiBackendFlags_None;
  999. DisplaySize = ImVec2(-1.0f, -1.0f);
  1000. DeltaTime = 1.0f / 60.0f;
  1001. IniSavingRate = 5.0f;
  1002. 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).
  1003. LogFilename = "imgui_log.txt";
  1004. MouseDoubleClickTime = 0.30f;
  1005. MouseDoubleClickMaxDist = 6.0f;
  1006. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1007. for (int i = 0; i < ImGuiKey_COUNT; i++)
  1008. KeyMap[i] = -1;
  1009. #endif
  1010. KeyRepeatDelay = 0.275f;
  1011. KeyRepeatRate = 0.050f;
  1012. UserData = NULL;
  1013. Fonts = NULL;
  1014. FontGlobalScale = 1.0f;
  1015. FontDefault = NULL;
  1016. FontAllowUserScaling = false;
  1017. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  1018. // Miscellaneous options
  1019. MouseDrawCursor = false;
  1020. #ifdef __APPLE__
  1021. ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
  1022. #else
  1023. ConfigMacOSXBehaviors = false;
  1024. #endif
  1025. ConfigInputTextCursorBlink = true;
  1026. ConfigWindowsResizeFromEdges = true;
  1027. ConfigWindowsMoveFromTitleBarOnly = false;
  1028. ConfigMemoryCompactTimer = 60.0f;
  1029. // Platform Functions
  1030. BackendPlatformName = BackendRendererName = NULL;
  1031. BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
  1032. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  1033. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  1034. ClipboardUserData = NULL;
  1035. SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
  1036. // Input (NB: we already have memset zero the entire structure!)
  1037. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  1038. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  1039. MouseDragThreshold = 6.0f;
  1040. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  1041. for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
  1042. for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
  1043. BackendUsingLegacyKeyArrays = (ImS8)-1;
  1044. }
  1045. // Pass in translated ASCII characters for text input.
  1046. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  1047. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  1048. void ImGuiIO::AddInputCharacter(unsigned int c)
  1049. {
  1050. if (c != 0)
  1051. InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
  1052. }
  1053. // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
  1054. // we should save the high surrogate.
  1055. void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
  1056. {
  1057. if (c == 0 && InputQueueSurrogate == 0)
  1058. return;
  1059. if ((c & 0xFC00) == 0xD800) // High surrogate, must save
  1060. {
  1061. if (InputQueueSurrogate != 0)
  1062. InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
  1063. InputQueueSurrogate = c;
  1064. return;
  1065. }
  1066. ImWchar cp = c;
  1067. if (InputQueueSurrogate != 0)
  1068. {
  1069. if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
  1070. {
  1071. InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
  1072. }
  1073. else
  1074. {
  1075. #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
  1076. cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
  1077. #else
  1078. cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
  1079. #endif
  1080. }
  1081. InputQueueSurrogate = 0;
  1082. }
  1083. InputQueueCharacters.push_back(cp);
  1084. }
  1085. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  1086. {
  1087. while (*utf8_chars != 0)
  1088. {
  1089. unsigned int c = 0;
  1090. utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
  1091. if (c != 0)
  1092. InputQueueCharacters.push_back((ImWchar)c);
  1093. }
  1094. }
  1095. void ImGuiIO::ClearInputCharacters()
  1096. {
  1097. InputQueueCharacters.resize(0);
  1098. }
  1099. void ImGuiIO::ClearInputKeys()
  1100. {
  1101. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1102. memset(KeysDown, 0, sizeof(KeysDown));
  1103. #endif
  1104. for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
  1105. {
  1106. KeysData[n].Down = false;
  1107. KeysData[n].DownDuration = -1.0f;
  1108. KeysData[n].DownDurationPrev = -1.0f;
  1109. }
  1110. KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
  1111. KeyMods = KeyModsPrev = ImGuiKeyModFlags_None;
  1112. for (int n = 0; n < IM_ARRAYSIZE(NavInputsDownDuration); n++)
  1113. NavInputsDownDuration[n] = NavInputsDownDurationPrev[n] = -1.0f;
  1114. }
  1115. // Queue a new key down/up event.
  1116. // - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
  1117. // - bool down: Is the key down? use false to signify a key release.
  1118. // FIXME: In the current version this is setting key data immediately. This will evolve into a trickling queue.
  1119. void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
  1120. {
  1121. //if (e->Down) { IMGUI_DEBUG_LOG("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
  1122. if (key == ImGuiKey_None)
  1123. return;
  1124. IM_ASSERT(ImGui::IsNamedKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
  1125. // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
  1126. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1127. IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
  1128. if (BackendUsingLegacyKeyArrays == -1)
  1129. for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
  1130. IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
  1131. #endif
  1132. BackendUsingLegacyKeyArrays = 0;
  1133. // Write key
  1134. const int keydata_index = (key - ImGuiKey_KeysData_OFFSET);
  1135. KeysData[keydata_index].Down = down;
  1136. }
  1137. // [Optional] Call add AddKeyEvent().
  1138. // Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
  1139. // If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
  1140. void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
  1141. {
  1142. IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
  1143. IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey(native_legacy_index)); // >= 0 && <= 511
  1144. IM_UNUSED(native_keycode); // Yet unused
  1145. IM_UNUSED(native_scancode); // Yet unused
  1146. // Build native->imgui map so old user code can still call key functions with native 0..511 values.
  1147. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1148. const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
  1149. if (ImGui::IsLegacyKey(legacy_key))
  1150. KeyMap[legacy_key] = key;
  1151. #else
  1152. IM_UNUSED(key);
  1153. IM_UNUSED(native_legacy_index);
  1154. #endif
  1155. }
  1156. void ImGuiIO::AddFocusEvent(bool focused)
  1157. {
  1158. // We intentionally overwrite this and process in NewFrame(), in order to give a chance
  1159. // to multi-viewports backends to queue AddFocusEvent(false),AddFocusEvent(true) in same frame.
  1160. AppFocusLost = !focused;
  1161. }
  1162. //-----------------------------------------------------------------------------
  1163. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  1164. //-----------------------------------------------------------------------------
  1165. ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
  1166. {
  1167. IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
  1168. ImVec2 p_last = p1;
  1169. ImVec2 p_closest;
  1170. float p_closest_dist2 = FLT_MAX;
  1171. float t_step = 1.0f / (float)num_segments;
  1172. for (int i_step = 1; i_step <= num_segments; i_step++)
  1173. {
  1174. ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
  1175. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1176. float dist2 = ImLengthSqr(p - p_line);
  1177. if (dist2 < p_closest_dist2)
  1178. {
  1179. p_closest = p_line;
  1180. p_closest_dist2 = dist2;
  1181. }
  1182. p_last = p_current;
  1183. }
  1184. return p_closest;
  1185. }
  1186. // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
  1187. static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
  1188. {
  1189. float dx = x4 - x1;
  1190. float dy = y4 - y1;
  1191. float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
  1192. float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
  1193. d2 = (d2 >= 0) ? d2 : -d2;
  1194. d3 = (d3 >= 0) ? d3 : -d3;
  1195. if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
  1196. {
  1197. ImVec2 p_current(x4, y4);
  1198. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1199. float dist2 = ImLengthSqr(p - p_line);
  1200. if (dist2 < p_closest_dist2)
  1201. {
  1202. p_closest = p_line;
  1203. p_closest_dist2 = dist2;
  1204. }
  1205. p_last = p_current;
  1206. }
  1207. else if (level < 10)
  1208. {
  1209. float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
  1210. float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
  1211. float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
  1212. float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
  1213. float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
  1214. float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
  1215. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
  1216. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
  1217. }
  1218. }
  1219. // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
  1220. // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
  1221. ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
  1222. {
  1223. IM_ASSERT(tess_tol > 0.0f);
  1224. ImVec2 p_last = p1;
  1225. ImVec2 p_closest;
  1226. float p_closest_dist2 = FLT_MAX;
  1227. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
  1228. return p_closest;
  1229. }
  1230. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  1231. {
  1232. ImVec2 ap = p - a;
  1233. ImVec2 ab_dir = b - a;
  1234. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  1235. if (dot < 0.0f)
  1236. return a;
  1237. float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
  1238. if (dot > ab_len_sqr)
  1239. return b;
  1240. return a + ab_dir * dot / ab_len_sqr;
  1241. }
  1242. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1243. {
  1244. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  1245. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  1246. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  1247. return ((b1 == b2) && (b2 == b3));
  1248. }
  1249. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  1250. {
  1251. ImVec2 v0 = b - a;
  1252. ImVec2 v1 = c - a;
  1253. ImVec2 v2 = p - a;
  1254. const float denom = v0.x * v1.y - v1.x * v0.y;
  1255. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  1256. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  1257. out_u = 1.0f - out_v - out_w;
  1258. }
  1259. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1260. {
  1261. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  1262. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  1263. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  1264. float dist2_ab = ImLengthSqr(p - proj_ab);
  1265. float dist2_bc = ImLengthSqr(p - proj_bc);
  1266. float dist2_ca = ImLengthSqr(p - proj_ca);
  1267. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  1268. if (m == dist2_ab)
  1269. return proj_ab;
  1270. if (m == dist2_bc)
  1271. return proj_bc;
  1272. return proj_ca;
  1273. }
  1274. //-----------------------------------------------------------------------------
  1275. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  1276. //-----------------------------------------------------------------------------
  1277. // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
  1278. int ImStricmp(const char* str1, const char* str2)
  1279. {
  1280. int d;
  1281. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  1282. return d;
  1283. }
  1284. int ImStrnicmp(const char* str1, const char* str2, size_t count)
  1285. {
  1286. int d = 0;
  1287. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  1288. return d;
  1289. }
  1290. void ImStrncpy(char* dst, const char* src, size_t count)
  1291. {
  1292. if (count < 1)
  1293. return;
  1294. if (count > 1)
  1295. strncpy(dst, src, count - 1);
  1296. dst[count - 1] = 0;
  1297. }
  1298. char* ImStrdup(const char* str)
  1299. {
  1300. size_t len = strlen(str);
  1301. void* buf = IM_ALLOC(len + 1);
  1302. return (char*)memcpy(buf, (const void*)str, len + 1);
  1303. }
  1304. char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
  1305. {
  1306. size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
  1307. size_t src_size = strlen(src) + 1;
  1308. if (dst_buf_size < src_size)
  1309. {
  1310. IM_FREE(dst);
  1311. dst = (char*)IM_ALLOC(src_size);
  1312. if (p_dst_size)
  1313. *p_dst_size = src_size;
  1314. }
  1315. return (char*)memcpy(dst, (const void*)src, src_size);
  1316. }
  1317. const char* ImStrchrRange(const char* str, const char* str_end, char c)
  1318. {
  1319. const char* p = (const char*)memchr(str, (int)c, str_end - str);
  1320. return p;
  1321. }
  1322. int ImStrlenW(const ImWchar* str)
  1323. {
  1324. //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
  1325. int n = 0;
  1326. while (*str++) n++;
  1327. return n;
  1328. }
  1329. // Find end-of-line. Return pointer will point to either first \n, either str_end.
  1330. const char* ImStreolRange(const char* str, const char* str_end)
  1331. {
  1332. const char* p = (const char*)memchr(str, '\n', str_end - str);
  1333. return p ? p : str_end;
  1334. }
  1335. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  1336. {
  1337. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  1338. buf_mid_line--;
  1339. return buf_mid_line;
  1340. }
  1341. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  1342. {
  1343. if (!needle_end)
  1344. needle_end = needle + strlen(needle);
  1345. const char un0 = (char)toupper(*needle);
  1346. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  1347. {
  1348. if (toupper(*haystack) == un0)
  1349. {
  1350. const char* b = needle + 1;
  1351. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  1352. if (toupper(*a) != toupper(*b))
  1353. break;
  1354. if (b == needle_end)
  1355. return haystack;
  1356. }
  1357. haystack++;
  1358. }
  1359. return NULL;
  1360. }
  1361. // Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
  1362. void ImStrTrimBlanks(char* buf)
  1363. {
  1364. char* p = buf;
  1365. while (p[0] == ' ' || p[0] == '\t') // Leading blanks
  1366. p++;
  1367. char* p_start = p;
  1368. while (*p != 0) // Find end of string
  1369. p++;
  1370. while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
  1371. p--;
  1372. if (p_start != buf) // Copy memory if we had leading blanks
  1373. memmove(buf, p_start, p - p_start);
  1374. buf[p - p_start] = 0; // Zero terminate
  1375. }
  1376. const char* ImStrSkipBlank(const char* str)
  1377. {
  1378. while (str[0] == ' ' || str[0] == '\t')
  1379. str++;
  1380. return str;
  1381. }
  1382. // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  1383. // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
  1384. // B) When buf==NULL vsnprintf() will return the output size.
  1385. #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1386. // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
  1387. // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1388. // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
  1389. // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
  1390. #ifdef IMGUI_USE_STB_SPRINTF
  1391. #define STB_SPRINTF_IMPLEMENTATION
  1392. #include "stb_sprintf.h"
  1393. #endif
  1394. #if defined(_MSC_VER) && !defined(vsnprintf)
  1395. #define vsnprintf _vsnprintf
  1396. #endif
  1397. int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
  1398. {
  1399. va_list args;
  1400. va_start(args, fmt);
  1401. #ifdef IMGUI_USE_STB_SPRINTF
  1402. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1403. #else
  1404. int w = vsnprintf(buf, buf_size, fmt, args);
  1405. #endif
  1406. va_end(args);
  1407. if (buf == NULL)
  1408. return w;
  1409. if (w == -1 || w >= (int)buf_size)
  1410. w = (int)buf_size - 1;
  1411. buf[w] = 0;
  1412. return w;
  1413. }
  1414. int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
  1415. {
  1416. #ifdef IMGUI_USE_STB_SPRINTF
  1417. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1418. #else
  1419. int w = vsnprintf(buf, buf_size, fmt, args);
  1420. #endif
  1421. if (buf == NULL)
  1422. return w;
  1423. if (w == -1 || w >= (int)buf_size)
  1424. w = (int)buf_size - 1;
  1425. buf[w] = 0;
  1426. return w;
  1427. }
  1428. #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1429. // CRC32 needs a 1KB lookup table (not cache friendly)
  1430. // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
  1431. // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
  1432. static const ImU32 GCrc32LookupTable[256] =
  1433. {
  1434. 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
  1435. 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
  1436. 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
  1437. 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
  1438. 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
  1439. 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
  1440. 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
  1441. 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
  1442. 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
  1443. 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
  1444. 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
  1445. 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
  1446. 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
  1447. 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
  1448. 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
  1449. 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
  1450. };
  1451. // Known size hash
  1452. // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
  1453. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1454. ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
  1455. {
  1456. ImU32 crc = ~seed;
  1457. const unsigned char* data = (const unsigned char*)data_p;
  1458. const ImU32* crc32_lut = GCrc32LookupTable;
  1459. while (data_size-- != 0)
  1460. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
  1461. return ~crc;
  1462. }
  1463. // Zero-terminated string hash, with support for ### to reset back to seed value
  1464. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  1465. // Because this syntax is rarely used we are optimizing for the common case.
  1466. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  1467. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
  1468. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1469. ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
  1470. {
  1471. seed = ~seed;
  1472. ImU32 crc = seed;
  1473. const unsigned char* data = (const unsigned char*)data_p;
  1474. const ImU32* crc32_lut = GCrc32LookupTable;
  1475. if (data_size != 0)
  1476. {
  1477. while (data_size-- != 0)
  1478. {
  1479. unsigned char c = *data++;
  1480. if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
  1481. crc = seed;
  1482. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1483. }
  1484. }
  1485. else
  1486. {
  1487. while (unsigned char c = *data++)
  1488. {
  1489. if (c == '#' && data[0] == '#' && data[1] == '#')
  1490. crc = seed;
  1491. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1492. }
  1493. }
  1494. return ~crc;
  1495. }
  1496. //-----------------------------------------------------------------------------
  1497. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  1498. //-----------------------------------------------------------------------------
  1499. // Default file functions
  1500. #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1501. ImFileHandle ImFileOpen(const char* filename, const char* mode)
  1502. {
  1503. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
  1504. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
  1505. // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
  1506. const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
  1507. const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
  1508. ImVector<ImWchar> buf;
  1509. buf.resize(filename_wsize + mode_wsize);
  1510. ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
  1511. ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
  1512. return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
  1513. #else
  1514. return fopen(filename, mode);
  1515. #endif
  1516. }
  1517. // We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
  1518. bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
  1519. ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
  1520. ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
  1521. ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
  1522. #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1523. // Helper: Load file content into memory
  1524. // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
  1525. // This can't really be used with "rt" because fseek size won't match read size.
  1526. void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
  1527. {
  1528. IM_ASSERT(filename && mode);
  1529. if (out_file_size)
  1530. *out_file_size = 0;
  1531. ImFileHandle f;
  1532. if ((f = ImFileOpen(filename, mode)) == NULL)
  1533. return NULL;
  1534. size_t file_size = (size_t)ImFileGetSize(f);
  1535. if (file_size == (size_t)-1)
  1536. {
  1537. ImFileClose(f);
  1538. return NULL;
  1539. }
  1540. void* file_data = IM_ALLOC(file_size + padding_bytes);
  1541. if (file_data == NULL)
  1542. {
  1543. ImFileClose(f);
  1544. return NULL;
  1545. }
  1546. if (ImFileRead(file_data, 1, file_size, f) != file_size)
  1547. {
  1548. ImFileClose(f);
  1549. IM_FREE(file_data);
  1550. return NULL;
  1551. }
  1552. if (padding_bytes > 0)
  1553. memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
  1554. ImFileClose(f);
  1555. if (out_file_size)
  1556. *out_file_size = file_size;
  1557. return file_data;
  1558. }
  1559. //-----------------------------------------------------------------------------
  1560. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  1561. //-----------------------------------------------------------------------------
  1562. // Convert UTF-8 to 32-bit character, process single character input.
  1563. // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
  1564. // We handle UTF-8 decoding error by skipping forward.
  1565. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1566. {
  1567. static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
  1568. static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
  1569. static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
  1570. static const int shiftc[] = { 0, 18, 12, 6, 0 };
  1571. static const int shifte[] = { 0, 6, 4, 2, 0 };
  1572. int len = lengths[*(const unsigned char*)in_text >> 3];
  1573. int wanted = len + !len;
  1574. if (in_text_end == NULL)
  1575. in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
  1576. // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
  1577. // so it is fast even with excessive branching.
  1578. unsigned char s[4];
  1579. s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
  1580. s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
  1581. s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
  1582. s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
  1583. // Assume a four-byte character and load four bytes. Unused bits are shifted out.
  1584. *out_char = (uint32_t)(s[0] & masks[len]) << 18;
  1585. *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
  1586. *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
  1587. *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
  1588. *out_char >>= shiftc[len];
  1589. // Accumulate the various error conditions.
  1590. int e = 0;
  1591. e = (*out_char < mins[len]) << 6; // non-canonical encoding
  1592. e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
  1593. e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
  1594. e |= (s[1] & 0xc0) >> 2;
  1595. e |= (s[2] & 0xc0) >> 4;
  1596. e |= (s[3] ) >> 6;
  1597. e ^= 0x2a; // top two bits of each tail byte correct?
  1598. e >>= shifte[len];
  1599. if (e)
  1600. {
  1601. // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
  1602. // One byte is consumed in case of invalid first byte of in_text.
  1603. // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
  1604. // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
  1605. wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
  1606. *out_char = IM_UNICODE_CODEPOINT_INVALID;
  1607. }
  1608. return wanted;
  1609. }
  1610. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1611. {
  1612. ImWchar* buf_out = buf;
  1613. ImWchar* buf_end = buf + buf_size;
  1614. while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1615. {
  1616. unsigned int c;
  1617. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1618. if (c == 0)
  1619. break;
  1620. *buf_out++ = (ImWchar)c;
  1621. }
  1622. *buf_out = 0;
  1623. if (in_text_remaining)
  1624. *in_text_remaining = in_text;
  1625. return (int)(buf_out - buf);
  1626. }
  1627. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1628. {
  1629. int char_count = 0;
  1630. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1631. {
  1632. unsigned int c;
  1633. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1634. if (c == 0)
  1635. break;
  1636. char_count++;
  1637. }
  1638. return char_count;
  1639. }
  1640. // Based on stb_to_utf8() from github.com/nothings/stb/
  1641. static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
  1642. {
  1643. if (c < 0x80)
  1644. {
  1645. buf[0] = (char)c;
  1646. return 1;
  1647. }
  1648. if (c < 0x800)
  1649. {
  1650. if (buf_size < 2) return 0;
  1651. buf[0] = (char)(0xc0 + (c >> 6));
  1652. buf[1] = (char)(0x80 + (c & 0x3f));
  1653. return 2;
  1654. }
  1655. if (c < 0x10000)
  1656. {
  1657. if (buf_size < 3) return 0;
  1658. buf[0] = (char)(0xe0 + (c >> 12));
  1659. buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
  1660. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1661. return 3;
  1662. }
  1663. if (c <= 0x10FFFF)
  1664. {
  1665. if (buf_size < 4) return 0;
  1666. buf[0] = (char)(0xf0 + (c >> 18));
  1667. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1668. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1669. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1670. return 4;
  1671. }
  1672. // Invalid code point, the max unicode is 0x10FFFF
  1673. return 0;
  1674. }
  1675. const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
  1676. {
  1677. int count = ImTextCharToUtf8_inline(out_buf, 5, c);
  1678. out_buf[count] = 0;
  1679. return out_buf;
  1680. }
  1681. // Not optimal but we very rarely use this function.
  1682. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
  1683. {
  1684. unsigned int unused = 0;
  1685. return ImTextCharFromUtf8(&unused, in_text, in_text_end);
  1686. }
  1687. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1688. {
  1689. if (c < 0x80) return 1;
  1690. if (c < 0x800) return 2;
  1691. if (c < 0x10000) return 3;
  1692. if (c <= 0x10FFFF) return 4;
  1693. return 3;
  1694. }
  1695. int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1696. {
  1697. char* buf_p = out_buf;
  1698. const char* buf_end = out_buf + out_buf_size;
  1699. while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1700. {
  1701. unsigned int c = (unsigned int)(*in_text++);
  1702. if (c < 0x80)
  1703. *buf_p++ = (char)c;
  1704. else
  1705. buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
  1706. }
  1707. *buf_p = 0;
  1708. return (int)(buf_p - out_buf);
  1709. }
  1710. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1711. {
  1712. int bytes_count = 0;
  1713. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1714. {
  1715. unsigned int c = (unsigned int)(*in_text++);
  1716. if (c < 0x80)
  1717. bytes_count++;
  1718. else
  1719. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1720. }
  1721. return bytes_count;
  1722. }
  1723. //-----------------------------------------------------------------------------
  1724. // [SECTION] MISC HELPERS/UTILITIES (Color functions)
  1725. // Note: The Convert functions are early design which are not consistent with other API.
  1726. //-----------------------------------------------------------------------------
  1727. IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
  1728. {
  1729. float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
  1730. int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
  1731. int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
  1732. int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
  1733. return IM_COL32(r, g, b, 0xFF);
  1734. }
  1735. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1736. {
  1737. float s = 1.0f / 255.0f;
  1738. return ImVec4(
  1739. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1740. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1741. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1742. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1743. }
  1744. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1745. {
  1746. ImU32 out;
  1747. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1748. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1749. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1750. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1751. return out;
  1752. }
  1753. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1754. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1755. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1756. {
  1757. float K = 0.f;
  1758. if (g < b)
  1759. {
  1760. ImSwap(g, b);
  1761. K = -1.f;
  1762. }
  1763. if (r < g)
  1764. {
  1765. ImSwap(r, g);
  1766. K = -2.f / 6.f - K;
  1767. }
  1768. const float chroma = r - (g < b ? g : b);
  1769. out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
  1770. out_s = chroma / (r + 1e-20f);
  1771. out_v = r;
  1772. }
  1773. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1774. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1775. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1776. {
  1777. if (s == 0.0f)
  1778. {
  1779. // gray
  1780. out_r = out_g = out_b = v;
  1781. return;
  1782. }
  1783. h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
  1784. int i = (int)h;
  1785. float f = h - (float)i;
  1786. float p = v * (1.0f - s);
  1787. float q = v * (1.0f - s * f);
  1788. float t = v * (1.0f - s * (1.0f - f));
  1789. switch (i)
  1790. {
  1791. case 0: out_r = v; out_g = t; out_b = p; break;
  1792. case 1: out_r = q; out_g = v; out_b = p; break;
  1793. case 2: out_r = p; out_g = v; out_b = t; break;
  1794. case 3: out_r = p; out_g = q; out_b = v; break;
  1795. case 4: out_r = t; out_g = p; out_b = v; break;
  1796. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1797. }
  1798. }
  1799. //-----------------------------------------------------------------------------
  1800. // [SECTION] ImGuiStorage
  1801. // Helper: Key->value storage
  1802. //-----------------------------------------------------------------------------
  1803. // std::lower_bound but without the bullshit
  1804. static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
  1805. {
  1806. ImGuiStorage::ImGuiStoragePair* first = data.Data;
  1807. ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
  1808. size_t count = (size_t)(last - first);
  1809. while (count > 0)
  1810. {
  1811. size_t count2 = count >> 1;
  1812. ImGuiStorage::ImGuiStoragePair* mid = first + count2;
  1813. if (mid->key < key)
  1814. {
  1815. first = ++mid;
  1816. count -= count2 + 1;
  1817. }
  1818. else
  1819. {
  1820. count = count2;
  1821. }
  1822. }
  1823. return first;
  1824. }
  1825. // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
  1826. void ImGuiStorage::BuildSortByKey()
  1827. {
  1828. struct StaticFunc
  1829. {
  1830. static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
  1831. {
  1832. // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
  1833. if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
  1834. if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
  1835. return 0;
  1836. }
  1837. };
  1838. ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
  1839. }
  1840. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1841. {
  1842. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1843. if (it == Data.end() || it->key != key)
  1844. return default_val;
  1845. return it->val_i;
  1846. }
  1847. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1848. {
  1849. return GetInt(key, default_val ? 1 : 0) != 0;
  1850. }
  1851. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1852. {
  1853. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1854. if (it == Data.end() || it->key != key)
  1855. return default_val;
  1856. return it->val_f;
  1857. }
  1858. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1859. {
  1860. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1861. if (it == Data.end() || it->key != key)
  1862. return NULL;
  1863. return it->val_p;
  1864. }
  1865. // 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.
  1866. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1867. {
  1868. ImGuiStoragePair* it = LowerBound(Data, key);
  1869. if (it == Data.end() || it->key != key)
  1870. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1871. return &it->val_i;
  1872. }
  1873. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1874. {
  1875. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1876. }
  1877. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1878. {
  1879. ImGuiStoragePair* it = LowerBound(Data, key);
  1880. if (it == Data.end() || it->key != key)
  1881. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1882. return &it->val_f;
  1883. }
  1884. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1885. {
  1886. ImGuiStoragePair* it = LowerBound(Data, key);
  1887. if (it == Data.end() || it->key != key)
  1888. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1889. return &it->val_p;
  1890. }
  1891. // 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)
  1892. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1893. {
  1894. ImGuiStoragePair* it = LowerBound(Data, key);
  1895. if (it == Data.end() || it->key != key)
  1896. {
  1897. Data.insert(it, ImGuiStoragePair(key, val));
  1898. return;
  1899. }
  1900. it->val_i = val;
  1901. }
  1902. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1903. {
  1904. SetInt(key, val ? 1 : 0);
  1905. }
  1906. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1907. {
  1908. ImGuiStoragePair* it = LowerBound(Data, key);
  1909. if (it == Data.end() || it->key != key)
  1910. {
  1911. Data.insert(it, ImGuiStoragePair(key, val));
  1912. return;
  1913. }
  1914. it->val_f = val;
  1915. }
  1916. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1917. {
  1918. ImGuiStoragePair* it = LowerBound(Data, key);
  1919. if (it == Data.end() || it->key != key)
  1920. {
  1921. Data.insert(it, ImGuiStoragePair(key, val));
  1922. return;
  1923. }
  1924. it->val_p = val;
  1925. }
  1926. void ImGuiStorage::SetAllInt(int v)
  1927. {
  1928. for (int i = 0; i < Data.Size; i++)
  1929. Data[i].val_i = v;
  1930. }
  1931. //-----------------------------------------------------------------------------
  1932. // [SECTION] ImGuiTextFilter
  1933. //-----------------------------------------------------------------------------
  1934. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1935. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1936. {
  1937. if (default_filter)
  1938. {
  1939. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1940. Build();
  1941. }
  1942. else
  1943. {
  1944. InputBuf[0] = 0;
  1945. CountGrep = 0;
  1946. }
  1947. }
  1948. bool ImGuiTextFilter::Draw(const char* label, float width)
  1949. {
  1950. if (width != 0.0f)
  1951. ImGui::SetNextItemWidth(width);
  1952. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1953. if (value_changed)
  1954. Build();
  1955. return value_changed;
  1956. }
  1957. void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
  1958. {
  1959. out->resize(0);
  1960. const char* wb = b;
  1961. const char* we = wb;
  1962. while (we < e)
  1963. {
  1964. if (*we == separator)
  1965. {
  1966. out->push_back(ImGuiTextRange(wb, we));
  1967. wb = we + 1;
  1968. }
  1969. we++;
  1970. }
  1971. if (wb != we)
  1972. out->push_back(ImGuiTextRange(wb, we));
  1973. }
  1974. void ImGuiTextFilter::Build()
  1975. {
  1976. Filters.resize(0);
  1977. ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
  1978. input_range.split(',', &Filters);
  1979. CountGrep = 0;
  1980. for (int i = 0; i != Filters.Size; i++)
  1981. {
  1982. ImGuiTextRange& f = Filters[i];
  1983. while (f.b < f.e && ImCharIsBlankA(f.b[0]))
  1984. f.b++;
  1985. while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
  1986. f.e--;
  1987. if (f.empty())
  1988. continue;
  1989. if (Filters[i].b[0] != '-')
  1990. CountGrep += 1;
  1991. }
  1992. }
  1993. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1994. {
  1995. if (Filters.empty())
  1996. return true;
  1997. if (text == NULL)
  1998. text = "";
  1999. for (int i = 0; i != Filters.Size; i++)
  2000. {
  2001. const ImGuiTextRange& f = Filters[i];
  2002. if (f.empty())
  2003. continue;
  2004. if (f.b[0] == '-')
  2005. {
  2006. // Subtract
  2007. if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
  2008. return false;
  2009. }
  2010. else
  2011. {
  2012. // Grep
  2013. if (ImStristr(text, text_end, f.b, f.e) != NULL)
  2014. return true;
  2015. }
  2016. }
  2017. // Implicit * grep
  2018. if (CountGrep == 0)
  2019. return true;
  2020. return false;
  2021. }
  2022. //-----------------------------------------------------------------------------
  2023. // [SECTION] ImGuiTextBuffer
  2024. //-----------------------------------------------------------------------------
  2025. // On some platform vsnprintf() takes va_list by reference and modifies it.
  2026. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  2027. #ifndef va_copy
  2028. #if defined(__GNUC__) || defined(__clang__)
  2029. #define va_copy(dest, src) __builtin_va_copy(dest, src)
  2030. #else
  2031. #define va_copy(dest, src) (dest = src)
  2032. #endif
  2033. #endif
  2034. char ImGuiTextBuffer::EmptyString[1] = { 0 };
  2035. void ImGuiTextBuffer::append(const char* str, const char* str_end)
  2036. {
  2037. int len = str_end ? (int)(str_end - str) : (int)strlen(str);
  2038. // Add zero-terminator the first time
  2039. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  2040. const int needed_sz = write_off + len;
  2041. if (write_off + len >= Buf.Capacity)
  2042. {
  2043. int new_capacity = Buf.Capacity * 2;
  2044. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  2045. }
  2046. Buf.resize(needed_sz);
  2047. memcpy(&Buf[write_off - 1], str, (size_t)len);
  2048. Buf[write_off - 1 + len] = 0;
  2049. }
  2050. void ImGuiTextBuffer::appendf(const char* fmt, ...)
  2051. {
  2052. va_list args;
  2053. va_start(args, fmt);
  2054. appendfv(fmt, args);
  2055. va_end(args);
  2056. }
  2057. // Helper: Text buffer for logging/accumulating text
  2058. void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
  2059. {
  2060. va_list args_copy;
  2061. va_copy(args_copy, args);
  2062. int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  2063. if (len <= 0)
  2064. {
  2065. va_end(args_copy);
  2066. return;
  2067. }
  2068. // Add zero-terminator the first time
  2069. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  2070. const int needed_sz = write_off + len;
  2071. if (write_off + len >= Buf.Capacity)
  2072. {
  2073. int new_capacity = Buf.Capacity * 2;
  2074. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  2075. }
  2076. Buf.resize(needed_sz);
  2077. ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
  2078. va_end(args_copy);
  2079. }
  2080. //-----------------------------------------------------------------------------
  2081. // [SECTION] ImGuiListClipper
  2082. // This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
  2083. // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
  2084. //-----------------------------------------------------------------------------
  2085. // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
  2086. // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
  2087. static bool GetSkipItemForListClipping()
  2088. {
  2089. ImGuiContext& g = *GImGui;
  2090. return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
  2091. }
  2092. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  2093. // Legacy helper to calculate coarse clipping of large list of evenly sized items.
  2094. // This legacy API is not ideal because it assume we will return a single contiguous rectangle.
  2095. // Prefer using ImGuiListClipper which can returns non-contiguous ranges.
  2096. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  2097. {
  2098. ImGuiContext& g = *GImGui;
  2099. ImGuiWindow* window = g.CurrentWindow;
  2100. if (g.LogEnabled)
  2101. {
  2102. // If logging is active, do not perform any clipping
  2103. *out_items_display_start = 0;
  2104. *out_items_display_end = items_count;
  2105. return;
  2106. }
  2107. if (GetSkipItemForListClipping())
  2108. {
  2109. *out_items_display_start = *out_items_display_end = 0;
  2110. return;
  2111. }
  2112. // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
  2113. // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
  2114. ImRect rect = window->ClipRect;
  2115. if (g.NavMoveScoringItems)
  2116. rect.Add(g.NavScoringNoClipRect);
  2117. if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
  2118. rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
  2119. const ImVec2 pos = window->DC.CursorPos;
  2120. int start = (int)((rect.Min.y - pos.y) / items_height);
  2121. int end = (int)((rect.Max.y - pos.y) / items_height);
  2122. // When performing a navigation request, ensure we have one item extra in the direction we are moving to
  2123. // FIXME: Verify this works with tabbing
  2124. const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
  2125. if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
  2126. start--;
  2127. if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
  2128. end++;
  2129. start = ImClamp(start, 0, items_count);
  2130. end = ImClamp(end + 1, start, items_count);
  2131. *out_items_display_start = start;
  2132. *out_items_display_end = end;
  2133. }
  2134. #endif
  2135. static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
  2136. {
  2137. if (ranges.Size - offset <= 1)
  2138. return;
  2139. // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
  2140. for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
  2141. for (int i = offset; i < sort_end + offset; ++i)
  2142. if (ranges[i].Min > ranges[i + 1].Min)
  2143. ImSwap(ranges[i], ranges[i + 1]);
  2144. // Now fuse ranges together as much as possible.
  2145. for (int i = 1 + offset; i < ranges.Size; i++)
  2146. {
  2147. IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
  2148. if (ranges[i - 1].Max < ranges[i].Min)
  2149. continue;
  2150. ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
  2151. ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
  2152. ranges.erase(ranges.Data + i);
  2153. i--;
  2154. }
  2155. }
  2156. static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
  2157. {
  2158. // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
  2159. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
  2160. // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
  2161. ImGuiContext& g = *GImGui;
  2162. ImGuiWindow* window = g.CurrentWindow;
  2163. float off_y = pos_y - window->DC.CursorPos.y;
  2164. window->DC.CursorPos.y = pos_y;
  2165. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
  2166. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
  2167. window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
  2168. if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
  2169. columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  2170. if (ImGuiTable* table = g.CurrentTable)
  2171. {
  2172. if (table->IsInsideRow)
  2173. ImGui::TableEndRow(table);
  2174. table->RowPosY2 = window->DC.CursorPos.y;
  2175. const int row_increase = (int)((off_y / line_height) + 0.5f);
  2176. //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
  2177. table->RowBgColorCounter += row_increase;
  2178. }
  2179. }
  2180. static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
  2181. {
  2182. // StartPosY starts from ItemsFrozen hence the subtraction
  2183. // Perform the add and multiply with double to allow seeking through larger ranges
  2184. ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
  2185. float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
  2186. ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
  2187. }
  2188. ImGuiListClipper::ImGuiListClipper()
  2189. {
  2190. memset(this, 0, sizeof(*this));
  2191. ItemsCount = -1;
  2192. }
  2193. ImGuiListClipper::~ImGuiListClipper()
  2194. {
  2195. End();
  2196. }
  2197. // Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1
  2198. // Use case B: Begin() called from constructor with items_height>0
  2199. // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
  2200. void ImGuiListClipper::Begin(int items_count, float items_height)
  2201. {
  2202. ImGuiContext& g = *GImGui;
  2203. ImGuiWindow* window = g.CurrentWindow;
  2204. if (ImGuiTable* table = g.CurrentTable)
  2205. if (table->IsInsideRow)
  2206. ImGui::TableEndRow(table);
  2207. StartPosY = window->DC.CursorPos.y;
  2208. ItemsHeight = items_height;
  2209. ItemsCount = items_count;
  2210. DisplayStart = -1;
  2211. DisplayEnd = 0;
  2212. // Acquire temporary buffer
  2213. if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
  2214. g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
  2215. ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
  2216. data->Reset(this);
  2217. data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
  2218. TempData = data;
  2219. }
  2220. void ImGuiListClipper::End()
  2221. {
  2222. // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
  2223. ImGuiContext& g = *GImGui;
  2224. if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
  2225. ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
  2226. ItemsCount = -1;
  2227. // Restore temporary buffer and fix back pointers which may be invalidated when nesting
  2228. if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
  2229. {
  2230. IM_ASSERT(data->ListClipper == this);
  2231. data->StepNo = data->Ranges.Size;
  2232. if (--g.ClipperTempDataStacked > 0)
  2233. {
  2234. data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
  2235. data->ListClipper->TempData = data;
  2236. }
  2237. TempData = NULL;
  2238. }
  2239. }
  2240. void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
  2241. {
  2242. ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
  2243. IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
  2244. IM_ASSERT(item_min <= item_max);
  2245. if (item_min < item_max)
  2246. data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
  2247. }
  2248. bool ImGuiListClipper::Step()
  2249. {
  2250. ImGuiContext& g = *GImGui;
  2251. ImGuiWindow* window = g.CurrentWindow;
  2252. ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
  2253. ImGuiTable* table = g.CurrentTable;
  2254. if (table && table->IsInsideRow)
  2255. ImGui::TableEndRow(table);
  2256. // No items
  2257. if (ItemsCount == 0 || GetSkipItemForListClipping())
  2258. return (void)End(), false;
  2259. // While we are in frozen row state, keep displaying items one by one, unclipped
  2260. // FIXME: Could be stored as a table-agnostic state.
  2261. if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
  2262. {
  2263. DisplayStart = data->ItemsFrozen;
  2264. DisplayEnd = data->ItemsFrozen + 1;
  2265. if (DisplayStart >= ItemsCount)
  2266. return (void)End(), false;
  2267. data->ItemsFrozen++;
  2268. return true;
  2269. }
  2270. // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
  2271. bool calc_clipping = false;
  2272. if (data->StepNo == 0)
  2273. {
  2274. StartPosY = window->DC.CursorPos.y;
  2275. if (ItemsHeight <= 0.0f)
  2276. {
  2277. // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
  2278. data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
  2279. DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
  2280. DisplayEnd = ImMin(data->Ranges[0].Max, ItemsCount);
  2281. if (DisplayStart == DisplayEnd)
  2282. return (void)End(), false;
  2283. data->StepNo = 1;
  2284. return true;
  2285. }
  2286. calc_clipping = true; // If on the first step with known item height, calculate clipping.
  2287. }
  2288. // Step 1: Let the clipper infer height from first range
  2289. if (ItemsHeight <= 0.0f)
  2290. {
  2291. IM_ASSERT(data->StepNo == 1);
  2292. if (table)
  2293. IM_ASSERT(table->RowPosY1 == StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
  2294. ItemsHeight = (window->DC.CursorPos.y - StartPosY) / (float)(DisplayEnd - DisplayStart);
  2295. bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
  2296. if (affected_by_floating_point_precision)
  2297. ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
  2298. IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
  2299. calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
  2300. }
  2301. // Step 0 or 1: Calculate the actual ranges of visible elements.
  2302. const int already_submitted = DisplayEnd;
  2303. if (calc_clipping)
  2304. {
  2305. if (g.LogEnabled)
  2306. {
  2307. // If logging is active, do not perform any clipping
  2308. data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, ItemsCount));
  2309. }
  2310. else
  2311. {
  2312. // Add range selected to be included for navigation
  2313. const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
  2314. if (is_nav_request)
  2315. data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
  2316. if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
  2317. data->Ranges.push_back(ImGuiListClipperRange::FromIndices(ItemsCount - 1, ItemsCount));
  2318. // Add focused/active item
  2319. ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
  2320. if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
  2321. data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
  2322. // Add visible range
  2323. const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
  2324. const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
  2325. data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
  2326. }
  2327. // Convert position ranges to item index ranges
  2328. // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
  2329. // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
  2330. // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
  2331. for (int i = 0; i < data->Ranges.Size; i++)
  2332. if (data->Ranges[i].PosToIndexConvert)
  2333. {
  2334. int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / ItemsHeight);
  2335. int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / ItemsHeight) + 0.999999f);
  2336. data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, ItemsCount - 1);
  2337. data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, ItemsCount);
  2338. data->Ranges[i].PosToIndexConvert = false;
  2339. }
  2340. ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
  2341. }
  2342. // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
  2343. if (data->StepNo < data->Ranges.Size)
  2344. {
  2345. DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
  2346. DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, ItemsCount);
  2347. if (DisplayStart > already_submitted) //-V1051
  2348. ImGuiListClipper_SeekCursorForItem(this, DisplayStart);
  2349. data->StepNo++;
  2350. return true;
  2351. }
  2352. // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
  2353. // Advance the cursor to the end of the list and then returns 'false' to end the loop.
  2354. if (ItemsCount < INT_MAX)
  2355. ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
  2356. ItemsCount = -1;
  2357. return false;
  2358. }
  2359. //-----------------------------------------------------------------------------
  2360. // [SECTION] STYLING
  2361. //-----------------------------------------------------------------------------
  2362. ImGuiStyle& ImGui::GetStyle()
  2363. {
  2364. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  2365. return GImGui->Style;
  2366. }
  2367. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  2368. {
  2369. ImGuiStyle& style = GImGui->Style;
  2370. ImVec4 c = style.Colors[idx];
  2371. c.w *= style.Alpha * alpha_mul;
  2372. return ColorConvertFloat4ToU32(c);
  2373. }
  2374. ImU32 ImGui::GetColorU32(const ImVec4& col)
  2375. {
  2376. ImGuiStyle& style = GImGui->Style;
  2377. ImVec4 c = col;
  2378. c.w *= style.Alpha;
  2379. return ColorConvertFloat4ToU32(c);
  2380. }
  2381. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  2382. {
  2383. ImGuiStyle& style = GImGui->Style;
  2384. return style.Colors[idx];
  2385. }
  2386. ImU32 ImGui::GetColorU32(ImU32 col)
  2387. {
  2388. ImGuiStyle& style = GImGui->Style;
  2389. if (style.Alpha >= 1.0f)
  2390. return col;
  2391. ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  2392. a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  2393. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  2394. }
  2395. // FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
  2396. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  2397. {
  2398. ImGuiContext& g = *GImGui;
  2399. ImGuiColorMod backup;
  2400. backup.Col = idx;
  2401. backup.BackupValue = g.Style.Colors[idx];
  2402. g.ColorStack.push_back(backup);
  2403. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  2404. }
  2405. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  2406. {
  2407. ImGuiContext& g = *GImGui;
  2408. ImGuiColorMod backup;
  2409. backup.Col = idx;
  2410. backup.BackupValue = g.Style.Colors[idx];
  2411. g.ColorStack.push_back(backup);
  2412. g.Style.Colors[idx] = col;
  2413. }
  2414. void ImGui::PopStyleColor(int count)
  2415. {
  2416. ImGuiContext& g = *GImGui;
  2417. while (count > 0)
  2418. {
  2419. ImGuiColorMod& backup = g.ColorStack.back();
  2420. g.Style.Colors[backup.Col] = backup.BackupValue;
  2421. g.ColorStack.pop_back();
  2422. count--;
  2423. }
  2424. }
  2425. struct ImGuiStyleVarInfo
  2426. {
  2427. ImGuiDataType Type;
  2428. ImU32 Count;
  2429. ImU32 Offset;
  2430. void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  2431. };
  2432. static const ImGuiStyleVarInfo GStyleVarInfo[] =
  2433. {
  2434. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  2435. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
  2436. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  2437. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  2438. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
  2439. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  2440. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
  2441. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
  2442. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
  2443. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
  2444. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
  2445. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  2446. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  2447. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
  2448. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  2449. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  2450. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  2451. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
  2452. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
  2453. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
  2454. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  2455. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
  2456. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
  2457. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  2458. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
  2459. };
  2460. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  2461. {
  2462. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
  2463. IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
  2464. return &GStyleVarInfo[idx];
  2465. }
  2466. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  2467. {
  2468. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2469. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
  2470. {
  2471. ImGuiContext& g = *GImGui;
  2472. float* pvar = (float*)var_info->GetVarPtr(&g.Style);
  2473. g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
  2474. *pvar = val;
  2475. return;
  2476. }
  2477. IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
  2478. }
  2479. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  2480. {
  2481. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2482. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
  2483. {
  2484. ImGuiContext& g = *GImGui;
  2485. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
  2486. g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
  2487. *pvar = val;
  2488. return;
  2489. }
  2490. IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
  2491. }
  2492. void ImGui::PopStyleVar(int count)
  2493. {
  2494. ImGuiContext& g = *GImGui;
  2495. while (count > 0)
  2496. {
  2497. // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
  2498. ImGuiStyleMod& backup = g.StyleVarStack.back();
  2499. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  2500. void* data = info->GetVarPtr(&g.Style);
  2501. if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
  2502. else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
  2503. g.StyleVarStack.pop_back();
  2504. count--;
  2505. }
  2506. }
  2507. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  2508. {
  2509. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  2510. switch (idx)
  2511. {
  2512. case ImGuiCol_Text: return "Text";
  2513. case ImGuiCol_TextDisabled: return "TextDisabled";
  2514. case ImGuiCol_WindowBg: return "WindowBg";
  2515. case ImGuiCol_ChildBg: return "ChildBg";
  2516. case ImGuiCol_PopupBg: return "PopupBg";
  2517. case ImGuiCol_Border: return "Border";
  2518. case ImGuiCol_BorderShadow: return "BorderShadow";
  2519. case ImGuiCol_FrameBg: return "FrameBg";
  2520. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  2521. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  2522. case ImGuiCol_TitleBg: return "TitleBg";
  2523. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  2524. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  2525. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  2526. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  2527. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  2528. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  2529. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  2530. case ImGuiCol_CheckMark: return "CheckMark";
  2531. case ImGuiCol_SliderGrab: return "SliderGrab";
  2532. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  2533. case ImGuiCol_Button: return "Button";
  2534. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  2535. case ImGuiCol_ButtonActive: return "ButtonActive";
  2536. case ImGuiCol_Header: return "Header";
  2537. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  2538. case ImGuiCol_HeaderActive: return "HeaderActive";
  2539. case ImGuiCol_Separator: return "Separator";
  2540. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  2541. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  2542. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  2543. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  2544. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  2545. case ImGuiCol_Tab: return "Tab";
  2546. case ImGuiCol_TabHovered: return "TabHovered";
  2547. case ImGuiCol_TabActive: return "TabActive";
  2548. case ImGuiCol_TabUnfocused: return "TabUnfocused";
  2549. case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
  2550. case ImGuiCol_PlotLines: return "PlotLines";
  2551. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  2552. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  2553. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  2554. case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
  2555. case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
  2556. case ImGuiCol_TableBorderLight: return "TableBorderLight";
  2557. case ImGuiCol_TableRowBg: return "TableRowBg";
  2558. case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
  2559. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  2560. case ImGuiCol_DragDropTarget: return "DragDropTarget";
  2561. case ImGuiCol_NavHighlight: return "NavHighlight";
  2562. case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
  2563. case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
  2564. case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
  2565. }
  2566. IM_ASSERT(0);
  2567. return "Unknown";
  2568. }
  2569. //-----------------------------------------------------------------------------
  2570. // [SECTION] RENDER HELPERS
  2571. // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
  2572. // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
  2573. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
  2574. //-----------------------------------------------------------------------------
  2575. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  2576. {
  2577. const char* text_display_end = text;
  2578. if (!text_end)
  2579. text_end = (const char*)-1;
  2580. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2581. text_display_end++;
  2582. return text_display_end;
  2583. }
  2584. // Internal ImGui functions to render text
  2585. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  2586. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  2587. {
  2588. ImGuiContext& g = *GImGui;
  2589. ImGuiWindow* window = g.CurrentWindow;
  2590. // Hide anything after a '##' string
  2591. const char* text_display_end;
  2592. if (hide_text_after_hash)
  2593. {
  2594. text_display_end = FindRenderedTextEnd(text, text_end);
  2595. }
  2596. else
  2597. {
  2598. if (!text_end)
  2599. text_end = text + strlen(text); // FIXME-OPT
  2600. text_display_end = text_end;
  2601. }
  2602. if (text != text_display_end)
  2603. {
  2604. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  2605. if (g.LogEnabled)
  2606. LogRenderedText(&pos, text, text_display_end);
  2607. }
  2608. }
  2609. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  2610. {
  2611. ImGuiContext& g = *GImGui;
  2612. ImGuiWindow* window = g.CurrentWindow;
  2613. if (!text_end)
  2614. text_end = text + strlen(text); // FIXME-OPT
  2615. if (text != text_end)
  2616. {
  2617. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  2618. if (g.LogEnabled)
  2619. LogRenderedText(&pos, text, text_end);
  2620. }
  2621. }
  2622. // Default clip_rect uses (pos_min,pos_max)
  2623. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  2624. 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)
  2625. {
  2626. // Perform CPU side clipping for single clipped element to avoid using scissor state
  2627. ImVec2 pos = pos_min;
  2628. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  2629. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  2630. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  2631. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  2632. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  2633. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  2634. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  2635. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  2636. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  2637. // Render
  2638. if (need_clipping)
  2639. {
  2640. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  2641. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  2642. }
  2643. else
  2644. {
  2645. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2646. }
  2647. }
  2648. void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
  2649. {
  2650. // Hide anything after a '##' string
  2651. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  2652. const int text_len = (int)(text_display_end - text);
  2653. if (text_len == 0)
  2654. return;
  2655. ImGuiContext& g = *GImGui;
  2656. ImGuiWindow* window = g.CurrentWindow;
  2657. RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
  2658. if (g.LogEnabled)
  2659. LogRenderedText(&pos_min, text, text_display_end);
  2660. }
  2661. // Another overly complex function until we reorganize everything into a nice all-in-one helper.
  2662. // 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.
  2663. // 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.
  2664. 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)
  2665. {
  2666. ImGuiContext& g = *GImGui;
  2667. if (text_end_full == NULL)
  2668. text_end_full = FindRenderedTextEnd(text);
  2669. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
  2670. //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));
  2671. //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));
  2672. //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
  2673. // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
  2674. if (text_size.x > pos_max.x - pos_min.x)
  2675. {
  2676. // Hello wo...
  2677. // | | |
  2678. // min max ellipsis_max
  2679. // <-> this is generally some padding value
  2680. const ImFont* font = draw_list->_Data->Font;
  2681. const float font_size = draw_list->_Data->FontSize;
  2682. const char* text_end_ellipsis = NULL;
  2683. ImWchar ellipsis_char = font->EllipsisChar;
  2684. int ellipsis_char_count = 1;
  2685. if (ellipsis_char == (ImWchar)-1)
  2686. {
  2687. ellipsis_char = font->DotChar;
  2688. ellipsis_char_count = 3;
  2689. }
  2690. const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
  2691. float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
  2692. float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
  2693. if (ellipsis_char_count > 1)
  2694. {
  2695. // Full ellipsis size without free spacing after it.
  2696. const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
  2697. ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
  2698. ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
  2699. }
  2700. // We can now claim the space between pos_max.x and ellipsis_max.x
  2701. const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
  2702. float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
  2703. if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
  2704. {
  2705. // Always display at least 1 character if there's no room for character + ellipsis
  2706. text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
  2707. text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
  2708. }
  2709. while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
  2710. {
  2711. // 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)
  2712. text_end_ellipsis--;
  2713. 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
  2714. }
  2715. // Render text, render ellipsis
  2716. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
  2717. float ellipsis_x = pos_min.x + text_size_clipped_x;
  2718. if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
  2719. for (int i = 0; i < ellipsis_char_count; i++)
  2720. {
  2721. font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
  2722. ellipsis_x += ellipsis_glyph_width;
  2723. }
  2724. }
  2725. else
  2726. {
  2727. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
  2728. }
  2729. if (g.LogEnabled)
  2730. LogRenderedText(&pos_min, text, text_end_full);
  2731. }
  2732. // Render a rectangle shaped with optional rounding and borders
  2733. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2734. {
  2735. ImGuiContext& g = *GImGui;
  2736. ImGuiWindow* window = g.CurrentWindow;
  2737. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2738. const float border_size = g.Style.FrameBorderSize;
  2739. if (border && border_size > 0.0f)
  2740. {
  2741. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
  2742. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  2743. }
  2744. }
  2745. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  2746. {
  2747. ImGuiContext& g = *GImGui;
  2748. ImGuiWindow* window = g.CurrentWindow;
  2749. const float border_size = g.Style.FrameBorderSize;
  2750. if (border_size > 0.0f)
  2751. {
  2752. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
  2753. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  2754. }
  2755. }
  2756. void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
  2757. {
  2758. ImGuiContext& g = *GImGui;
  2759. if (id != g.NavId)
  2760. return;
  2761. if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
  2762. return;
  2763. ImGuiWindow* window = g.CurrentWindow;
  2764. if (window->DC.NavHideHighlightOneFrame)
  2765. return;
  2766. float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
  2767. ImRect display_rect = bb;
  2768. display_rect.ClipWith(window->ClipRect);
  2769. if (flags & ImGuiNavHighlightFlags_TypeDefault)
  2770. {
  2771. const float THICKNESS = 2.0f;
  2772. const float DISTANCE = 3.0f + THICKNESS * 0.5f;
  2773. display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
  2774. bool fully_visible = window->ClipRect.Contains(display_rect);
  2775. if (!fully_visible)
  2776. window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
  2777. window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
  2778. if (!fully_visible)
  2779. window->DrawList->PopClipRect();
  2780. }
  2781. if (flags & ImGuiNavHighlightFlags_TypeThin)
  2782. {
  2783. window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
  2784. }
  2785. }
  2786. //-----------------------------------------------------------------------------
  2787. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  2788. //-----------------------------------------------------------------------------
  2789. // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
  2790. ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
  2791. {
  2792. memset(this, 0, sizeof(*this));
  2793. Name = ImStrdup(name);
  2794. NameBufLen = (int)strlen(name) + 1;
  2795. ID = ImHashStr(name);
  2796. IDStack.push_back(ID);
  2797. MoveId = GetID("#MOVE");
  2798. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  2799. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  2800. AutoFitFramesX = AutoFitFramesY = -1;
  2801. AutoPosLastDirection = ImGuiDir_None;
  2802. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  2803. SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
  2804. LastFrameActive = -1;
  2805. LastTimeActive = -1.0f;
  2806. FontWindowScale = 1.0f;
  2807. SettingsOffset = -1;
  2808. DrawList = &DrawListInst;
  2809. DrawList->_Data = &context->DrawListSharedData;
  2810. DrawList->_OwnerName = Name;
  2811. }
  2812. ImGuiWindow::~ImGuiWindow()
  2813. {
  2814. IM_ASSERT(DrawList == &DrawListInst);
  2815. IM_DELETE(Name);
  2816. ColumnsStorage.clear_destruct();
  2817. }
  2818. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  2819. {
  2820. ImGuiID seed = IDStack.back();
  2821. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  2822. ImGui::KeepAliveID(id);
  2823. ImGuiContext& g = *GImGui;
  2824. if (g.DebugHookIdInfo == id)
  2825. ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
  2826. return id;
  2827. }
  2828. ImGuiID ImGuiWindow::GetID(const void* ptr)
  2829. {
  2830. ImGuiID seed = IDStack.back();
  2831. ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
  2832. ImGui::KeepAliveID(id);
  2833. ImGuiContext& g = *GImGui;
  2834. if (g.DebugHookIdInfo == id)
  2835. ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
  2836. return id;
  2837. }
  2838. ImGuiID ImGuiWindow::GetID(int n)
  2839. {
  2840. ImGuiID seed = IDStack.back();
  2841. ImGuiID id = ImHashData(&n, sizeof(n), seed);
  2842. ImGui::KeepAliveID(id);
  2843. ImGuiContext& g = *GImGui;
  2844. if (g.DebugHookIdInfo == id)
  2845. ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
  2846. return id;
  2847. }
  2848. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  2849. {
  2850. ImGuiID seed = IDStack.back();
  2851. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  2852. ImGuiContext& g = *GImGui;
  2853. if (g.DebugHookIdInfo == id)
  2854. ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
  2855. return id;
  2856. }
  2857. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
  2858. {
  2859. ImGuiID seed = IDStack.back();
  2860. ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
  2861. ImGuiContext& g = *GImGui;
  2862. if (g.DebugHookIdInfo == id)
  2863. ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
  2864. return id;
  2865. }
  2866. ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
  2867. {
  2868. ImGuiID seed = IDStack.back();
  2869. ImGuiID id = ImHashData(&n, sizeof(n), seed);
  2870. ImGuiContext& g = *GImGui;
  2871. if (g.DebugHookIdInfo == id)
  2872. ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
  2873. return id;
  2874. }
  2875. // This is only used in rare/specific situations to manufacture an ID out of nowhere.
  2876. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
  2877. {
  2878. ImGuiID seed = IDStack.back();
  2879. ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
  2880. ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
  2881. ImGui::KeepAliveID(id);
  2882. return id;
  2883. }
  2884. static void SetCurrentWindow(ImGuiWindow* window)
  2885. {
  2886. ImGuiContext& g = *GImGui;
  2887. g.CurrentWindow = window;
  2888. g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
  2889. if (window)
  2890. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  2891. }
  2892. void ImGui::GcCompactTransientMiscBuffers()
  2893. {
  2894. ImGuiContext& g = *GImGui;
  2895. g.ItemFlagsStack.clear();
  2896. g.GroupStack.clear();
  2897. TableGcCompactSettings();
  2898. }
  2899. // Free up/compact internal window buffers, we can use this when a window becomes unused.
  2900. // Not freed:
  2901. // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
  2902. // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
  2903. void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
  2904. {
  2905. window->MemoryCompacted = true;
  2906. window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
  2907. window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
  2908. window->IDStack.clear();
  2909. window->DrawList->_ClearFreeMemory();
  2910. window->DC.ChildWindows.clear();
  2911. window->DC.ItemWidthStack.clear();
  2912. window->DC.TextWrapPosStack.clear();
  2913. }
  2914. void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
  2915. {
  2916. // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
  2917. // The other buffers tends to amortize much faster.
  2918. window->MemoryCompacted = false;
  2919. window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
  2920. window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
  2921. window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
  2922. }
  2923. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  2924. {
  2925. ImGuiContext& g = *GImGui;
  2926. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  2927. if (g.ActiveIdIsJustActivated)
  2928. {
  2929. g.ActiveIdTimer = 0.0f;
  2930. g.ActiveIdHasBeenPressedBefore = false;
  2931. g.ActiveIdHasBeenEditedBefore = false;
  2932. g.ActiveIdMouseButton = -1;
  2933. if (id != 0)
  2934. {
  2935. g.LastActiveId = id;
  2936. g.LastActiveIdTimer = 0.0f;
  2937. }
  2938. }
  2939. g.ActiveId = id;
  2940. g.ActiveIdAllowOverlap = false;
  2941. g.ActiveIdNoClearOnFocusLoss = false;
  2942. g.ActiveIdWindow = window;
  2943. g.ActiveIdHasBeenEditedThisFrame = false;
  2944. if (id)
  2945. {
  2946. g.ActiveIdIsAlive = id;
  2947. g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
  2948. }
  2949. // Clear declaration of inputs claimed by the widget
  2950. // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
  2951. g.ActiveIdUsingMouseWheel = false;
  2952. g.ActiveIdUsingNavDirMask = 0x00;
  2953. g.ActiveIdUsingNavInputMask = 0x00;
  2954. g.ActiveIdUsingKeyInputMask.ClearAllBits();
  2955. }
  2956. void ImGui::ClearActiveID()
  2957. {
  2958. SetActiveID(0, NULL); // g.ActiveId = 0;
  2959. }
  2960. void ImGui::SetHoveredID(ImGuiID id)
  2961. {
  2962. ImGuiContext& g = *GImGui;
  2963. g.HoveredId = id;
  2964. g.HoveredIdAllowOverlap = false;
  2965. g.HoveredIdUsingMouseWheel = false;
  2966. if (id != 0 && g.HoveredIdPreviousFrame != id)
  2967. g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
  2968. }
  2969. ImGuiID ImGui::GetHoveredID()
  2970. {
  2971. ImGuiContext& g = *GImGui;
  2972. return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
  2973. }
  2974. void ImGui::KeepAliveID(ImGuiID id)
  2975. {
  2976. ImGuiContext& g = *GImGui;
  2977. if (g.ActiveId == id)
  2978. g.ActiveIdIsAlive = id;
  2979. if (g.ActiveIdPreviousFrame == id)
  2980. g.ActiveIdPreviousFrameIsAlive = true;
  2981. }
  2982. void ImGui::MarkItemEdited(ImGuiID id)
  2983. {
  2984. // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
  2985. // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
  2986. ImGuiContext& g = *GImGui;
  2987. IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
  2988. IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
  2989. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
  2990. g.ActiveIdHasBeenEditedThisFrame = true;
  2991. g.ActiveIdHasBeenEditedBefore = true;
  2992. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
  2993. }
  2994. static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
  2995. {
  2996. // An active popup disable hovering on other windows (apart from its own children)
  2997. // FIXME-OPT: This could be cached/stored within the window.
  2998. ImGuiContext& g = *GImGui;
  2999. if (g.NavWindow)
  3000. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
  3001. if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
  3002. {
  3003. // For the purpose of those flags we differentiate "standard popup" from "modal popup"
  3004. // NB: The order of those two tests is important because Modal windows are also Popups.
  3005. if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
  3006. return false;
  3007. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  3008. return false;
  3009. }
  3010. return true;
  3011. }
  3012. // This is roughly matching the behavior of internal-facing ItemHoverable()
  3013. // - 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()
  3014. // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
  3015. bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
  3016. {
  3017. ImGuiContext& g = *GImGui;
  3018. ImGuiWindow* window = g.CurrentWindow;
  3019. if (g.NavDisableMouseHover && !g.NavDisableHighlight)
  3020. {
  3021. if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
  3022. return false;
  3023. if (!IsItemFocused())
  3024. return false;
  3025. }
  3026. else
  3027. {
  3028. // Test for bounding box overlap, as updated as ItemAdd()
  3029. ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
  3030. if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
  3031. return false;
  3032. IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy)) == 0); // Flags not supported by this function
  3033. // Test if we are hovering the right window (our window could be behind another window)
  3034. // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
  3035. // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
  3036. // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
  3037. // the test that has been running for a long while.
  3038. if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
  3039. if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
  3040. return false;
  3041. // Test if another item is active (e.g. being dragged)
  3042. if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
  3043. if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
  3044. return false;
  3045. // Test if interactions on this window are blocked by an active popup or modal.
  3046. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
  3047. if (!IsWindowContentHoverable(window, flags))
  3048. return false;
  3049. // Test if the item is disabled
  3050. if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
  3051. return false;
  3052. // Special handling for calling after Begin() which represent the title bar or tab.
  3053. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
  3054. if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
  3055. return false;
  3056. }
  3057. return true;
  3058. }
  3059. // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
  3060. bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
  3061. {
  3062. ImGuiContext& g = *GImGui;
  3063. if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
  3064. return false;
  3065. ImGuiWindow* window = g.CurrentWindow;
  3066. if (g.HoveredWindow != window)
  3067. return false;
  3068. if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
  3069. return false;
  3070. if (!IsMouseHoveringRect(bb.Min, bb.Max))
  3071. return false;
  3072. if (g.NavDisableMouseHover)
  3073. return false;
  3074. if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
  3075. {
  3076. g.HoveredIdDisabled = true;
  3077. return false;
  3078. }
  3079. // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
  3080. // hover test in widgets code. We could also decide to split this function is two.
  3081. if (id != 0)
  3082. SetHoveredID(id);
  3083. // When disabled we'll return false but still set HoveredId
  3084. ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
  3085. if (item_flags & ImGuiItemFlags_Disabled)
  3086. {
  3087. // Release active id if turning disabled
  3088. if (g.ActiveId == id)
  3089. ClearActiveID();
  3090. g.HoveredIdDisabled = true;
  3091. return false;
  3092. }
  3093. if (id != 0)
  3094. {
  3095. // [DEBUG] Item Picker tool!
  3096. // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
  3097. // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
  3098. // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
  3099. // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
  3100. if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
  3101. GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
  3102. if (g.DebugItemPickerBreakId == id)
  3103. IM_DEBUG_BREAK();
  3104. }
  3105. return true;
  3106. }
  3107. bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
  3108. {
  3109. ImGuiContext& g = *GImGui;
  3110. ImGuiWindow* window = g.CurrentWindow;
  3111. if (!bb.Overlaps(window->ClipRect))
  3112. if (id == 0 || (id != g.ActiveId && id != g.NavId))
  3113. if (!g.LogEnabled)
  3114. return true;
  3115. return false;
  3116. }
  3117. // This is also inlined in ItemAdd()
  3118. // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
  3119. void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
  3120. {
  3121. ImGuiContext& g = *GImGui;
  3122. g.LastItemData.ID = item_id;
  3123. g.LastItemData.InFlags = in_flags;
  3124. g.LastItemData.StatusFlags = item_flags;
  3125. g.LastItemData.Rect = item_rect;
  3126. }
  3127. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  3128. {
  3129. if (wrap_pos_x < 0.0f)
  3130. return 0.0f;
  3131. ImGuiContext& g = *GImGui;
  3132. ImGuiWindow* window = g.CurrentWindow;
  3133. if (wrap_pos_x == 0.0f)
  3134. {
  3135. // We could decide to setup a default wrapping max point for auto-resizing windows,
  3136. // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
  3137. //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
  3138. // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
  3139. //else
  3140. wrap_pos_x = window->WorkRect.Max.x;
  3141. }
  3142. else if (wrap_pos_x > 0.0f)
  3143. {
  3144. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  3145. }
  3146. return ImMax(wrap_pos_x - pos.x, 1.0f);
  3147. }
  3148. // IM_ALLOC() == ImGui::MemAlloc()
  3149. void* ImGui::MemAlloc(size_t size)
  3150. {
  3151. if (ImGuiContext* ctx = GImGui)
  3152. ctx->IO.MetricsActiveAllocations++;
  3153. return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
  3154. }
  3155. // IM_FREE() == ImGui::MemFree()
  3156. void ImGui::MemFree(void* ptr)
  3157. {
  3158. if (ptr)
  3159. if (ImGuiContext* ctx = GImGui)
  3160. ctx->IO.MetricsActiveAllocations--;
  3161. return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
  3162. }
  3163. const char* ImGui::GetClipboardText()
  3164. {
  3165. ImGuiContext& g = *GImGui;
  3166. return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
  3167. }
  3168. void ImGui::SetClipboardText(const char* text)
  3169. {
  3170. ImGuiContext& g = *GImGui;
  3171. if (g.IO.SetClipboardTextFn)
  3172. g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
  3173. }
  3174. const char* ImGui::GetVersion()
  3175. {
  3176. return IMGUI_VERSION;
  3177. }
  3178. // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
  3179. // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
  3180. ImGuiContext* ImGui::GetCurrentContext()
  3181. {
  3182. return GImGui;
  3183. }
  3184. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  3185. {
  3186. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  3187. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  3188. #else
  3189. GImGui = ctx;
  3190. #endif
  3191. }
  3192. void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
  3193. {
  3194. GImAllocatorAllocFunc = alloc_func;
  3195. GImAllocatorFreeFunc = free_func;
  3196. GImAllocatorUserData = user_data;
  3197. }
  3198. // This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
  3199. void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
  3200. {
  3201. *p_alloc_func = GImAllocatorAllocFunc;
  3202. *p_free_func = GImAllocatorFreeFunc;
  3203. *p_user_data = GImAllocatorUserData;
  3204. }
  3205. ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
  3206. {
  3207. ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
  3208. if (GImGui == NULL)
  3209. SetCurrentContext(ctx);
  3210. Initialize(ctx);
  3211. return ctx;
  3212. }
  3213. void ImGui::DestroyContext(ImGuiContext* ctx)
  3214. {
  3215. if (ctx == NULL)
  3216. ctx = GImGui;
  3217. Shutdown(ctx);
  3218. if (GImGui == ctx)
  3219. SetCurrentContext(NULL);
  3220. IM_DELETE(ctx);
  3221. }
  3222. // No specific ordering/dependency support, will see as needed
  3223. ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
  3224. {
  3225. ImGuiContext& g = *ctx;
  3226. IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
  3227. g.Hooks.push_back(*hook);
  3228. g.Hooks.back().HookId = ++g.HookIdNext;
  3229. return g.HookIdNext;
  3230. }
  3231. // Deferred removal, avoiding issue with changing vector while iterating it
  3232. void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
  3233. {
  3234. ImGuiContext& g = *ctx;
  3235. IM_ASSERT(hook_id != 0);
  3236. for (int n = 0; n < g.Hooks.Size; n++)
  3237. if (g.Hooks[n].HookId == hook_id)
  3238. g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
  3239. }
  3240. // Call context hooks (used by e.g. test engine)
  3241. // We assume a small number of hooks so all stored in same array
  3242. void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
  3243. {
  3244. ImGuiContext& g = *ctx;
  3245. for (int n = 0; n < g.Hooks.Size; n++)
  3246. if (g.Hooks[n].Type == hook_type)
  3247. g.Hooks[n].Callback(&g, &g.Hooks[n]);
  3248. }
  3249. ImGuiIO& ImGui::GetIO()
  3250. {
  3251. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  3252. return GImGui->IO;
  3253. }
  3254. // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
  3255. ImDrawData* ImGui::GetDrawData()
  3256. {
  3257. ImGuiContext& g = *GImGui;
  3258. ImGuiViewportP* viewport = g.Viewports[0];
  3259. return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
  3260. }
  3261. double ImGui::GetTime()
  3262. {
  3263. return GImGui->Time;
  3264. }
  3265. int ImGui::GetFrameCount()
  3266. {
  3267. return GImGui->FrameCount;
  3268. }
  3269. static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
  3270. {
  3271. // Create the draw list on demand, because they are not frequently used for all viewports
  3272. ImGuiContext& g = *GImGui;
  3273. IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
  3274. ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
  3275. if (draw_list == NULL)
  3276. {
  3277. draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
  3278. draw_list->_OwnerName = drawlist_name;
  3279. viewport->DrawLists[drawlist_no] = draw_list;
  3280. }
  3281. // Our ImDrawList system requires that there is always a command
  3282. if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
  3283. {
  3284. draw_list->_ResetForNewFrame();
  3285. draw_list->PushTextureID(g.IO.Fonts->TexID);
  3286. draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
  3287. viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
  3288. }
  3289. return draw_list;
  3290. }
  3291. ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
  3292. {
  3293. return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
  3294. }
  3295. ImDrawList* ImGui::GetBackgroundDrawList()
  3296. {
  3297. ImGuiContext& g = *GImGui;
  3298. return GetBackgroundDrawList(g.Viewports[0]);
  3299. }
  3300. ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
  3301. {
  3302. return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
  3303. }
  3304. ImDrawList* ImGui::GetForegroundDrawList()
  3305. {
  3306. ImGuiContext& g = *GImGui;
  3307. return GetForegroundDrawList(g.Viewports[0]);
  3308. }
  3309. ImDrawListSharedData* ImGui::GetDrawListSharedData()
  3310. {
  3311. return &GImGui->DrawListSharedData;
  3312. }
  3313. void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
  3314. {
  3315. // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
  3316. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
  3317. // This is because we want ActiveId to be set even when the window is not permitted to move.
  3318. ImGuiContext& g = *GImGui;
  3319. FocusWindow(window);
  3320. SetActiveID(window->MoveId, window);
  3321. g.NavDisableHighlight = true;
  3322. g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
  3323. g.ActiveIdNoClearOnFocusLoss = true;
  3324. SetActiveIdUsingNavAndKeys();
  3325. bool can_move_window = true;
  3326. if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
  3327. can_move_window = false;
  3328. if (can_move_window)
  3329. g.MovingWindow = window;
  3330. }
  3331. // Handle mouse moving window
  3332. // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
  3333. // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
  3334. // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
  3335. // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
  3336. void ImGui::UpdateMouseMovingWindowNewFrame()
  3337. {
  3338. ImGuiContext& g = *GImGui;
  3339. if (g.MovingWindow != NULL)
  3340. {
  3341. // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
  3342. // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
  3343. KeepAliveID(g.ActiveId);
  3344. IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
  3345. ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
  3346. if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
  3347. {
  3348. ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
  3349. if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
  3350. {
  3351. MarkIniSettingsDirty(moving_window);
  3352. SetWindowPos(moving_window, pos, ImGuiCond_Always);
  3353. }
  3354. FocusWindow(g.MovingWindow);
  3355. }
  3356. else
  3357. {
  3358. g.MovingWindow = NULL;
  3359. ClearActiveID();
  3360. }
  3361. }
  3362. else
  3363. {
  3364. // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
  3365. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
  3366. {
  3367. KeepAliveID(g.ActiveId);
  3368. if (!g.IO.MouseDown[0])
  3369. ClearActiveID();
  3370. }
  3371. }
  3372. }
  3373. // Initiate moving window when clicking on empty space or title bar.
  3374. // Handle left-click and right-click focus.
  3375. void ImGui::UpdateMouseMovingWindowEndFrame()
  3376. {
  3377. ImGuiContext& g = *GImGui;
  3378. if (g.ActiveId != 0 || g.HoveredId != 0)
  3379. return;
  3380. // Unless we just made a window/popup appear
  3381. if (g.NavWindow && g.NavWindow->Appearing)
  3382. return;
  3383. // Click on empty space to focus window and start moving
  3384. // (after we're done with all our widgets)
  3385. if (g.IO.MouseClicked[0])
  3386. {
  3387. // Handle the edge case of a popup being closed while clicking in its empty space.
  3388. // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
  3389. ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
  3390. const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
  3391. if (root_window != NULL && !is_closed_popup)
  3392. {
  3393. StartMouseMovingWindow(g.HoveredWindow); //-V595
  3394. // Cancel moving if clicked outside of title bar
  3395. if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
  3396. if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
  3397. g.MovingWindow = NULL;
  3398. // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
  3399. if (g.HoveredIdDisabled)
  3400. g.MovingWindow = NULL;
  3401. }
  3402. else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
  3403. {
  3404. // Clicking on void disable focus
  3405. FocusWindow(NULL);
  3406. }
  3407. }
  3408. // With right mouse button we close popups without changing focus based on where the mouse is aimed
  3409. // Instead, focus will be restored to the window under the bottom-most closed popup.
  3410. // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
  3411. if (g.IO.MouseClicked[1])
  3412. {
  3413. // Find the top-most window between HoveredWindow and the top-most Modal Window.
  3414. // This is where we can trim the popup stack.
  3415. ImGuiWindow* modal = GetTopMostPopupModal();
  3416. bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
  3417. ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
  3418. }
  3419. }
  3420. static bool IsWindowActiveAndVisible(ImGuiWindow* window)
  3421. {
  3422. return (window->Active) && (!window->Hidden);
  3423. }
  3424. static void ImGui::UpdateKeyboardInputs()
  3425. {
  3426. ImGuiContext& g = *GImGui;
  3427. ImGuiIO& io = g.IO;
  3428. // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools
  3429. io.KeyMods = GetMergedKeyModFlags();
  3430. // Import legacy keys or verify they are not used
  3431. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  3432. if (io.BackendUsingLegacyKeyArrays == 0)
  3433. {
  3434. // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written too.
  3435. for (int n = 0; n < IM_ARRAYSIZE(io.KeysDown); n++)
  3436. IM_ASSERT(io.KeysDown[n] == false && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
  3437. }
  3438. else
  3439. {
  3440. if (g.FrameCount == 0)
  3441. for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
  3442. IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
  3443. // Build reverse KeyMap (Named -> Legacy)
  3444. for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
  3445. if (io.KeyMap[n] != -1)
  3446. {
  3447. IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
  3448. io.KeyMap[io.KeyMap[n]] = n;
  3449. }
  3450. // Import legacy keys into new ones
  3451. for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
  3452. if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
  3453. {
  3454. const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
  3455. IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
  3456. io.KeysData[key].Down = io.KeysDown[n];
  3457. io.BackendUsingLegacyKeyArrays = 1;
  3458. }
  3459. }
  3460. #endif
  3461. // Update keys
  3462. for (int i = 0; i < IM_ARRAYSIZE(io.KeysData); i++)
  3463. {
  3464. ImGuiKeyData& key_data = io.KeysData[i];
  3465. key_data.DownDurationPrev = key_data.DownDuration;
  3466. key_data.DownDuration = key_data.Down ? (key_data.DownDuration < 0.0f ? 0.0f : key_data.DownDuration + io.DeltaTime) : -1.0f;
  3467. }
  3468. }
  3469. static void ImGui::UpdateMouseInputs()
  3470. {
  3471. ImGuiContext& g = *GImGui;
  3472. ImGuiIO& io = g.IO;
  3473. // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
  3474. if (IsMousePosValid(&io.MousePos))
  3475. io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
  3476. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
  3477. if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
  3478. io.MouseDelta = io.MousePos - io.MousePosPrev;
  3479. else
  3480. io.MouseDelta = ImVec2(0.0f, 0.0f);
  3481. // 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.
  3482. if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
  3483. g.NavDisableMouseHover = false;
  3484. io.MousePosPrev = io.MousePos;
  3485. for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
  3486. {
  3487. io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
  3488. io.MouseClickedCount[i] = 0; // Will be filled below
  3489. io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
  3490. io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
  3491. io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
  3492. if (io.MouseClicked[i])
  3493. {
  3494. bool is_repeated_click = false;
  3495. if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
  3496. {
  3497. ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  3498. if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
  3499. is_repeated_click = true;
  3500. }
  3501. if (is_repeated_click)
  3502. io.MouseClickedLastCount[i]++;
  3503. else
  3504. io.MouseClickedLastCount[i] = 1;
  3505. io.MouseClickedTime[i] = g.Time;
  3506. io.MouseClickedPos[i] = io.MousePos;
  3507. io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
  3508. io.MouseDragMaxDistanceSqr[i] = 0.0f;
  3509. }
  3510. else if (io.MouseDown[i])
  3511. {
  3512. // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
  3513. float delta_sqr_click_pos = IsMousePosValid(&io.MousePos) ? ImLengthSqr(io.MousePos - io.MouseClickedPos[i]) : 0.0f;
  3514. io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], delta_sqr_click_pos);
  3515. }
  3516. // We provide io.MouseDoubleClicked[] as a legacy service
  3517. io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
  3518. // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
  3519. if (io.MouseClicked[i])
  3520. g.NavDisableMouseHover = false;
  3521. }
  3522. }
  3523. static void StartLockWheelingWindow(ImGuiWindow* window)
  3524. {
  3525. ImGuiContext& g = *GImGui;
  3526. if (g.WheelingWindow == window)
  3527. return;
  3528. g.WheelingWindow = window;
  3529. g.WheelingWindowRefMousePos = g.IO.MousePos;
  3530. g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
  3531. }
  3532. void ImGui::UpdateMouseWheel()
  3533. {
  3534. ImGuiContext& g = *GImGui;
  3535. // Reset the locked window if we move the mouse or after the timer elapses
  3536. if (g.WheelingWindow != NULL)
  3537. {
  3538. g.WheelingWindowTimer -= g.IO.DeltaTime;
  3539. if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
  3540. g.WheelingWindowTimer = 0.0f;
  3541. if (g.WheelingWindowTimer <= 0.0f)
  3542. {
  3543. g.WheelingWindow = NULL;
  3544. g.WheelingWindowTimer = 0.0f;
  3545. }
  3546. }
  3547. if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
  3548. return;
  3549. if ((g.ActiveId != 0 && g.ActiveIdUsingMouseWheel) || (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel))
  3550. return;
  3551. ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
  3552. if (!window || window->Collapsed)
  3553. return;
  3554. // Zoom / Scale window
  3555. // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
  3556. if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  3557. {
  3558. StartLockWheelingWindow(window);
  3559. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  3560. const float scale = new_font_scale / window->FontWindowScale;
  3561. window->FontWindowScale = new_font_scale;
  3562. if (window == window->RootWindow)
  3563. {
  3564. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  3565. SetWindowPos(window, window->Pos + offset, 0);
  3566. window->Size = ImFloor(window->Size * scale);
  3567. window->SizeFull = ImFloor(window->SizeFull * scale);
  3568. }
  3569. return;
  3570. }
  3571. // Mouse wheel scrolling
  3572. // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
  3573. if (g.IO.KeyCtrl)
  3574. return;
  3575. // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
  3576. // (we avoid doing it on OSX as it the OS input layer handles this already)
  3577. const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
  3578. const float wheel_y = swap_axis ? 0.0f : g.IO.MouseWheel;
  3579. const float wheel_x = swap_axis ? g.IO.MouseWheel : g.IO.MouseWheelH;
  3580. // Vertical Mouse Wheel scrolling
  3581. if (wheel_y != 0.0f)
  3582. {
  3583. StartLockWheelingWindow(window);
  3584. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3585. window = window->ParentWindow;
  3586. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3587. {
  3588. float max_step = window->InnerRect.GetHeight() * 0.67f;
  3589. float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
  3590. SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
  3591. }
  3592. }
  3593. // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
  3594. if (wheel_x != 0.0f)
  3595. {
  3596. StartLockWheelingWindow(window);
  3597. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3598. window = window->ParentWindow;
  3599. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3600. {
  3601. float max_step = window->InnerRect.GetWidth() * 0.67f;
  3602. float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
  3603. SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
  3604. }
  3605. }
  3606. }
  3607. // 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)
  3608. void ImGui::UpdateHoveredWindowAndCaptureFlags()
  3609. {
  3610. ImGuiContext& g = *GImGui;
  3611. ImGuiIO& io = g.IO;
  3612. g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
  3613. // Find the window hovered by mouse:
  3614. // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
  3615. // - 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.
  3616. // - 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.
  3617. bool clear_hovered_windows = false;
  3618. FindHoveredWindow();
  3619. // Modal windows prevents mouse from hovering behind them.
  3620. ImGuiWindow* modal_window = GetTopMostPopupModal();
  3621. if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window))
  3622. clear_hovered_windows = true;
  3623. // Disabled mouse?
  3624. if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
  3625. clear_hovered_windows = true;
  3626. // We track click ownership. When clicked outside of a window the click is owned by the application and
  3627. // won't report hovering nor request capture even while dragging over our windows afterward.
  3628. const bool has_open_popup = (g.OpenPopupStack.Size > 0);
  3629. const bool has_open_modal = (modal_window != NULL);
  3630. int mouse_earliest_down = -1;
  3631. bool mouse_any_down = false;
  3632. for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
  3633. {
  3634. if (io.MouseClicked[i])
  3635. {
  3636. io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
  3637. io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
  3638. }
  3639. mouse_any_down |= io.MouseDown[i];
  3640. if (io.MouseDown[i])
  3641. if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
  3642. mouse_earliest_down = i;
  3643. }
  3644. const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
  3645. const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
  3646. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  3647. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
  3648. const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
  3649. if (!mouse_avail && !mouse_dragging_extern_payload)
  3650. clear_hovered_windows = true;
  3651. if (clear_hovered_windows)
  3652. g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3653. // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
  3654. // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
  3655. if (g.WantCaptureMouseNextFrame != -1)
  3656. {
  3657. io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
  3658. }
  3659. else
  3660. {
  3661. io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
  3662. io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
  3663. }
  3664. // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
  3665. if (g.WantCaptureKeyboardNextFrame != -1)
  3666. io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
  3667. else
  3668. io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
  3669. if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
  3670. io.WantCaptureKeyboard = true;
  3671. // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
  3672. io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
  3673. }
  3674. ImGuiKeyModFlags ImGui::GetMergedKeyModFlags()
  3675. {
  3676. ImGuiContext& g = *GImGui;
  3677. ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None;
  3678. if (g.IO.KeyCtrl) { key_mod_flags |= ImGuiKeyModFlags_Ctrl; }
  3679. if (g.IO.KeyShift) { key_mod_flags |= ImGuiKeyModFlags_Shift; }
  3680. if (g.IO.KeyAlt) { key_mod_flags |= ImGuiKeyModFlags_Alt; }
  3681. if (g.IO.KeySuper) { key_mod_flags |= ImGuiKeyModFlags_Super; }
  3682. return key_mod_flags;
  3683. }
  3684. void ImGui::NewFrame()
  3685. {
  3686. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  3687. ImGuiContext& g = *GImGui;
  3688. // Remove pending delete hooks before frame start.
  3689. // This deferred removal avoid issues of removal while iterating the hook vector
  3690. for (int n = g.Hooks.Size - 1; n >= 0; n--)
  3691. if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
  3692. g.Hooks.erase(&g.Hooks[n]);
  3693. CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
  3694. // Check and assert for various common IO and Configuration mistakes
  3695. ErrorCheckNewFrameSanityChecks();
  3696. // Load settings on first frame, save settings when modified (after a delay)
  3697. UpdateSettings();
  3698. g.Time += g.IO.DeltaTime;
  3699. g.WithinFrameScope = true;
  3700. g.FrameCount += 1;
  3701. g.TooltipOverrideCount = 0;
  3702. g.WindowsActiveCount = 0;
  3703. g.MenusIdSubmittedThisFrame.resize(0);
  3704. // Calculate frame-rate for the user, as a purely luxurious feature
  3705. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  3706. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  3707. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  3708. g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
  3709. g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
  3710. UpdateViewportsNewFrame();
  3711. // Setup current font and draw list shared data
  3712. g.IO.Fonts->Locked = true;
  3713. SetCurrentFont(GetDefaultFont());
  3714. IM_ASSERT(g.Font->IsLoaded());
  3715. ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  3716. for (int n = 0; n < g.Viewports.Size; n++)
  3717. virtual_space.Add(g.Viewports[n]->GetMainRect());
  3718. g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
  3719. g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
  3720. g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
  3721. g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
  3722. if (g.Style.AntiAliasedLines)
  3723. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
  3724. if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
  3725. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
  3726. if (g.Style.AntiAliasedFill)
  3727. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
  3728. if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
  3729. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
  3730. // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
  3731. for (int n = 0; n < g.Viewports.Size; n++)
  3732. {
  3733. ImGuiViewportP* viewport = g.Viewports[n];
  3734. viewport->DrawDataP.Clear();
  3735. }
  3736. // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
  3737. if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
  3738. KeepAliveID(g.DragDropPayload.SourceId);
  3739. // Update HoveredId data
  3740. if (!g.HoveredIdPreviousFrame)
  3741. g.HoveredIdTimer = 0.0f;
  3742. if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
  3743. g.HoveredIdNotActiveTimer = 0.0f;
  3744. if (g.HoveredId)
  3745. g.HoveredIdTimer += g.IO.DeltaTime;
  3746. if (g.HoveredId && g.ActiveId != g.HoveredId)
  3747. g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
  3748. g.HoveredIdPreviousFrame = g.HoveredId;
  3749. g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel;
  3750. g.HoveredId = 0;
  3751. g.HoveredIdAllowOverlap = false;
  3752. g.HoveredIdUsingMouseWheel = false;
  3753. g.HoveredIdDisabled = false;
  3754. // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
  3755. if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  3756. ClearActiveID();
  3757. if (g.ActiveId)
  3758. g.ActiveIdTimer += g.IO.DeltaTime;
  3759. g.LastActiveIdTimer += g.IO.DeltaTime;
  3760. g.ActiveIdPreviousFrame = g.ActiveId;
  3761. g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
  3762. g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
  3763. g.ActiveIdIsAlive = 0;
  3764. g.ActiveIdHasBeenEditedThisFrame = false;
  3765. g.ActiveIdPreviousFrameIsAlive = false;
  3766. g.ActiveIdIsJustActivated = false;
  3767. if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
  3768. g.TempInputId = 0;
  3769. if (g.ActiveId == 0)
  3770. {
  3771. g.ActiveIdUsingNavDirMask = 0x00;
  3772. g.ActiveIdUsingNavInputMask = 0x00;
  3773. g.ActiveIdUsingKeyInputMask.ClearAllBits();
  3774. }
  3775. // Drag and drop
  3776. g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
  3777. g.DragDropAcceptIdCurr = 0;
  3778. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  3779. g.DragDropWithinSource = false;
  3780. g.DragDropWithinTarget = false;
  3781. g.DragDropHoldJustPressedId = 0;
  3782. // Close popups on focus lost (currently wip/opt-in)
  3783. //if (g.IO.AppFocusLost)
  3784. // ClosePopupsExceptModals();
  3785. // Clear buttons state when focus is lost
  3786. // (this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle)
  3787. if (g.IO.AppFocusLost)
  3788. {
  3789. g.IO.ClearInputKeys();
  3790. g.IO.AppFocusLost = false;
  3791. }
  3792. // Update keyboard input state
  3793. UpdateKeyboardInputs();
  3794. // Update gamepad/keyboard navigation
  3795. NavUpdate();
  3796. // Update mouse input state
  3797. UpdateMouseInputs();
  3798. // Find hovered window
  3799. // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
  3800. UpdateHoveredWindowAndCaptureFlags();
  3801. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
  3802. UpdateMouseMovingWindowNewFrame();
  3803. // Background darkening/whitening
  3804. if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
  3805. g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  3806. else
  3807. g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
  3808. g.MouseCursor = ImGuiMouseCursor_Arrow;
  3809. g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
  3810. // Platform IME data: reset for the frame
  3811. g.PlatformImeDataPrev = g.PlatformImeData;
  3812. g.PlatformImeData.WantVisible = false;
  3813. // Mouse wheel scrolling, scale
  3814. UpdateMouseWheel();
  3815. // Mark all windows as not visible and compact unused memory.
  3816. IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
  3817. const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
  3818. for (int i = 0; i != g.Windows.Size; i++)
  3819. {
  3820. ImGuiWindow* window = g.Windows[i];
  3821. window->WasActive = window->Active;
  3822. window->BeginCount = 0;
  3823. window->Active = false;
  3824. window->WriteAccessed = false;
  3825. // Garbage collect transient buffers of recently unused windows
  3826. if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
  3827. GcCompactTransientWindowBuffers(window);
  3828. }
  3829. // Garbage collect transient buffers of recently unused tables
  3830. for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
  3831. if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
  3832. TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
  3833. for (int i = 0; i < g.TablesTempData.Size; i++)
  3834. if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
  3835. TableGcCompactTransientBuffers(&g.TablesTempData[i]);
  3836. if (g.GcCompactAll)
  3837. GcCompactTransientMiscBuffers();
  3838. g.GcCompactAll = false;
  3839. // Closing the focused window restore focus to the first active root window in descending z-order
  3840. if (g.NavWindow && !g.NavWindow->WasActive)
  3841. FocusTopMostWindowUnderOne(NULL, NULL);
  3842. // No window should be open at the beginning of the frame.
  3843. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  3844. g.CurrentWindowStack.resize(0);
  3845. g.BeginPopupStack.resize(0);
  3846. g.ItemFlagsStack.resize(0);
  3847. g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
  3848. g.GroupStack.resize(0);
  3849. // [DEBUG] Update debug features
  3850. UpdateDebugToolItemPicker();
  3851. UpdateDebugToolStackQueries();
  3852. // Create implicit/fallback window - which we will only render it if the user has added something to it.
  3853. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
  3854. // This fallback is particularly important as it avoid ImGui:: calls from crashing.
  3855. g.WithinFrameScopeWithImplicitWindow = true;
  3856. SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
  3857. Begin("Debug##Default");
  3858. IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
  3859. CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
  3860. }
  3861. void ImGui::Initialize(ImGuiContext* context)
  3862. {
  3863. ImGuiContext& g = *context;
  3864. IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
  3865. // Add .ini handle for ImGuiWindow type
  3866. {
  3867. ImGuiSettingsHandler ini_handler;
  3868. ini_handler.TypeName = "Window";
  3869. ini_handler.TypeHash = ImHashStr("Window");
  3870. ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
  3871. ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
  3872. ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
  3873. ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
  3874. ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
  3875. g.SettingsHandlers.push_back(ini_handler);
  3876. }
  3877. // Add .ini handle for ImGuiTable type
  3878. TableSettingsInstallHandler(context);
  3879. // Create default viewport
  3880. ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
  3881. g.Viewports.push_back(viewport);
  3882. #ifdef IMGUI_HAS_DOCK
  3883. #endif
  3884. g.Initialized = true;
  3885. }
  3886. // This function is merely here to free heap allocations.
  3887. void ImGui::Shutdown(ImGuiContext* context)
  3888. {
  3889. // 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)
  3890. ImGuiContext& g = *context;
  3891. if (g.IO.Fonts && g.FontAtlasOwnedByContext)
  3892. {
  3893. g.IO.Fonts->Locked = false;
  3894. IM_DELETE(g.IO.Fonts);
  3895. }
  3896. g.IO.Fonts = NULL;
  3897. // Cleanup of other data are conditional on actually having initialized Dear ImGui.
  3898. if (!g.Initialized)
  3899. return;
  3900. // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
  3901. if (g.SettingsLoaded && g.IO.IniFilename != NULL)
  3902. {
  3903. ImGuiContext* backup_context = GImGui;
  3904. SetCurrentContext(&g);
  3905. SaveIniSettingsToDisk(g.IO.IniFilename);
  3906. SetCurrentContext(backup_context);
  3907. }
  3908. CallContextHooks(&g, ImGuiContextHookType_Shutdown);
  3909. // Clear everything else
  3910. g.Windows.clear_delete();
  3911. g.WindowsFocusOrder.clear();
  3912. g.WindowsTempSortBuffer.clear();
  3913. g.CurrentWindow = NULL;
  3914. g.CurrentWindowStack.clear();
  3915. g.WindowsById.Clear();
  3916. g.NavWindow = NULL;
  3917. g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3918. g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
  3919. g.MovingWindow = NULL;
  3920. g.ColorStack.clear();
  3921. g.StyleVarStack.clear();
  3922. g.FontStack.clear();
  3923. g.OpenPopupStack.clear();
  3924. g.BeginPopupStack.clear();
  3925. g.Viewports.clear_delete();
  3926. g.TabBars.Clear();
  3927. g.CurrentTabBarStack.clear();
  3928. g.ShrinkWidthBuffer.clear();
  3929. g.ClipperTempData.clear_destruct();
  3930. g.Tables.Clear();
  3931. g.TablesTempData.clear_destruct();
  3932. g.DrawChannelsTempMergeBuffer.clear();
  3933. g.ClipboardHandlerData.clear();
  3934. g.MenusIdSubmittedThisFrame.clear();
  3935. g.InputTextState.ClearFreeMemory();
  3936. g.SettingsWindows.clear();
  3937. g.SettingsHandlers.clear();
  3938. if (g.LogFile)
  3939. {
  3940. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  3941. if (g.LogFile != stdout)
  3942. #endif
  3943. ImFileClose(g.LogFile);
  3944. g.LogFile = NULL;
  3945. }
  3946. g.LogBuffer.clear();
  3947. g.Initialized = false;
  3948. }
  3949. // FIXME: Add a more explicit sort order in the window structure.
  3950. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
  3951. {
  3952. const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
  3953. const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
  3954. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  3955. return d;
  3956. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  3957. return d;
  3958. return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
  3959. }
  3960. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
  3961. {
  3962. out_sorted_windows->push_back(window);
  3963. if (window->Active)
  3964. {
  3965. int count = window->DC.ChildWindows.Size;
  3966. ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  3967. for (int i = 0; i < count; i++)
  3968. {
  3969. ImGuiWindow* child = window->DC.ChildWindows[i];
  3970. if (child->Active)
  3971. AddWindowToSortBuffer(out_sorted_windows, child);
  3972. }
  3973. }
  3974. }
  3975. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
  3976. {
  3977. // Remove trailing command if unused.
  3978. // Technically we could return directly instead of popping, but this make things looks neat in Metrics/Debugger window as well.
  3979. draw_list->_PopUnusedDrawCmd();
  3980. if (draw_list->CmdBuffer.Size == 0)
  3981. return;
  3982. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
  3983. // May trigger for you if you are using PrimXXX functions incorrectly.
  3984. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  3985. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  3986. if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
  3987. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  3988. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
  3989. // If this assert triggers because you are drawing lots of stuff manually:
  3990. // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
  3991. // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
  3992. // - If you want large meshes with more than 64K vertices, you can either:
  3993. // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
  3994. // Most example backends already support this from 1.71. Pre-1.71 backends won't.
  3995. // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
  3996. // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
  3997. // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
  3998. // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
  3999. // Your own engine or render API may use different parameters or function calls to specify index sizes.
  4000. // 2 and 4 bytes indices are generally supported by most graphics API.
  4001. // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
  4002. // the 64K limit to split your draw commands in multiple draw lists.
  4003. if (sizeof(ImDrawIdx) == 2)
  4004. IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
  4005. out_list->push_back(draw_list);
  4006. }
  4007. static void AddWindowToDrawData(ImGuiWindow* window, int layer)
  4008. {
  4009. ImGuiContext& g = *GImGui;
  4010. ImGuiViewportP* viewport = g.Viewports[0];
  4011. g.IO.MetricsRenderWindows++;
  4012. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
  4013. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  4014. {
  4015. ImGuiWindow* child = window->DC.ChildWindows[i];
  4016. if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
  4017. AddWindowToDrawData(child, layer);
  4018. }
  4019. }
  4020. static inline int GetWindowDisplayLayer(ImGuiWindow* window)
  4021. {
  4022. return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
  4023. }
  4024. // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
  4025. static inline void AddRootWindowToDrawData(ImGuiWindow* window)
  4026. {
  4027. AddWindowToDrawData(window, GetWindowDisplayLayer(window));
  4028. }
  4029. void ImDrawDataBuilder::FlattenIntoSingleLayer()
  4030. {
  4031. int n = Layers[0].Size;
  4032. int size = n;
  4033. for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
  4034. size += Layers[i].Size;
  4035. Layers[0].resize(size);
  4036. for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
  4037. {
  4038. ImVector<ImDrawList*>& layer = Layers[layer_n];
  4039. if (layer.empty())
  4040. continue;
  4041. memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  4042. n += layer.Size;
  4043. layer.resize(0);
  4044. }
  4045. }
  4046. static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
  4047. {
  4048. ImGuiIO& io = ImGui::GetIO();
  4049. ImDrawData* draw_data = &viewport->DrawDataP;
  4050. draw_data->Valid = true;
  4051. draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
  4052. draw_data->CmdListsCount = draw_lists->Size;
  4053. draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
  4054. draw_data->DisplayPos = viewport->Pos;
  4055. draw_data->DisplaySize = viewport->Size;
  4056. draw_data->FramebufferScale = io.DisplayFramebufferScale;
  4057. for (int n = 0; n < draw_lists->Size; n++)
  4058. {
  4059. draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
  4060. draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
  4061. }
  4062. }
  4063. // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
  4064. // - When using this function it is sane to ensure that float are perfectly rounded to integer values,
  4065. // so that e.g. (int)(max.x-min.x) in user's render produce correct result.
  4066. // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
  4067. // some frequently called functions which to modify both channels and clipping simultaneously tend to use the
  4068. // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
  4069. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  4070. {
  4071. ImGuiWindow* window = GetCurrentWindow();
  4072. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  4073. window->ClipRect = window->DrawList->_ClipRectStack.back();
  4074. }
  4075. void ImGui::PopClipRect()
  4076. {
  4077. ImGuiWindow* window = GetCurrentWindow();
  4078. window->DrawList->PopClipRect();
  4079. window->ClipRect = window->DrawList->_ClipRectStack.back();
  4080. }
  4081. static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
  4082. {
  4083. if ((col & IM_COL32_A_MASK) == 0)
  4084. return;
  4085. ImGuiViewportP* viewport = (ImGuiViewportP*)GetMainViewport();
  4086. ImRect viewport_rect = viewport->GetMainRect();
  4087. // Draw behind window by moving the draw command at the FRONT of the draw list
  4088. {
  4089. // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
  4090. // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
  4091. ImDrawList* draw_list = window->RootWindow->DrawList;
  4092. if (draw_list->CmdBuffer.Size == 0)
  4093. draw_list->AddDrawCmd();
  4094. draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
  4095. draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
  4096. ImDrawCmd cmd = draw_list->CmdBuffer.back();
  4097. IM_ASSERT(cmd.ElemCount == 6);
  4098. draw_list->CmdBuffer.pop_back();
  4099. draw_list->CmdBuffer.push_front(cmd);
  4100. draw_list->PopClipRect();
  4101. draw_list->_PopUnusedDrawCmd(); // Since are past the calls to AddDrawListToDrawData() we don't have a _PopUnusedDrawCmd() running on commands.
  4102. }
  4103. }
  4104. ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
  4105. {
  4106. ImGuiContext& g = *GImGui;
  4107. ImGuiWindow* bottom_most_visible_window = parent_window;
  4108. for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
  4109. {
  4110. ImGuiWindow* window = g.Windows[i];
  4111. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  4112. continue;
  4113. if (!IsWindowWithinBeginStackOf(window, parent_window))
  4114. break;
  4115. if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
  4116. bottom_most_visible_window = window;
  4117. }
  4118. return bottom_most_visible_window;
  4119. }
  4120. static void ImGui::RenderDimmedBackgrounds()
  4121. {
  4122. ImGuiContext& g = *GImGui;
  4123. ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
  4124. const bool dim_bg_for_modal = (modal_window != NULL);
  4125. const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
  4126. if (!dim_bg_for_modal && !dim_bg_for_window_list)
  4127. return;
  4128. if (dim_bg_for_modal)
  4129. {
  4130. // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
  4131. ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
  4132. RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
  4133. }
  4134. else if (dim_bg_for_window_list)
  4135. {
  4136. // Draw dimming behind CTRL+Tab target window
  4137. RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
  4138. // Draw border around CTRL+Tab target window
  4139. ImGuiWindow* window = g.NavWindowingTargetAnim;
  4140. ImGuiViewport* viewport = GetMainViewport();
  4141. float distance = g.FontSize;
  4142. ImRect bb = window->Rect();
  4143. bb.Expand(distance);
  4144. if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
  4145. bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
  4146. if (window->DrawList->CmdBuffer.Size == 0)
  4147. window->DrawList->AddDrawCmd();
  4148. window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
  4149. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
  4150. window->DrawList->PopClipRect();
  4151. window->DrawList->_PopUnusedDrawCmd(); // Since are past the calls to AddDrawListToDrawData() we don't have a _PopUnusedDrawCmd() running on commands.
  4152. }
  4153. }
  4154. // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
  4155. void ImGui::EndFrame()
  4156. {
  4157. ImGuiContext& g = *GImGui;
  4158. IM_ASSERT(g.Initialized);
  4159. // Don't process EndFrame() multiple times.
  4160. if (g.FrameCountEnded == g.FrameCount)
  4161. return;
  4162. IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
  4163. CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
  4164. ErrorCheckEndFrameSanityChecks();
  4165. // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  4166. if (g.IO.SetPlatformImeDataFn && memcmp(&g.PlatformImeData, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
  4167. g.IO.SetPlatformImeDataFn(GetMainViewport(), &g.PlatformImeData);
  4168. // Hide implicit/fallback "Debug" window if it hasn't been used
  4169. g.WithinFrameScopeWithImplicitWindow = false;
  4170. if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
  4171. g.CurrentWindow->Active = false;
  4172. End();
  4173. // Update navigation: CTRL+Tab, wrap-around requests
  4174. NavEndFrame();
  4175. // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
  4176. if (g.DragDropActive)
  4177. {
  4178. bool is_delivered = g.DragDropPayload.Delivery;
  4179. bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
  4180. if (is_delivered || is_elapsed)
  4181. ClearDragDrop();
  4182. }
  4183. // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
  4184. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  4185. {
  4186. g.DragDropWithinSource = true;
  4187. SetTooltip("...");
  4188. g.DragDropWithinSource = false;
  4189. }
  4190. // End frame
  4191. g.WithinFrameScope = false;
  4192. g.FrameCountEnded = g.FrameCount;
  4193. // Initiate moving window + handle left-click and right-click focus
  4194. UpdateMouseMovingWindowEndFrame();
  4195. // Sort the window list so that all child windows are after their parent
  4196. // We cannot do that on FocusWindow() because children may not exist yet
  4197. g.WindowsTempSortBuffer.resize(0);
  4198. g.WindowsTempSortBuffer.reserve(g.Windows.Size);
  4199. for (int i = 0; i != g.Windows.Size; i++)
  4200. {
  4201. ImGuiWindow* window = g.Windows[i];
  4202. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  4203. continue;
  4204. AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
  4205. }
  4206. // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
  4207. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
  4208. g.Windows.swap(g.WindowsTempSortBuffer);
  4209. g.IO.MetricsActiveWindows = g.WindowsActiveCount;
  4210. // Unlock font atlas
  4211. g.IO.Fonts->Locked = false;
  4212. // Clear Input data for next frame
  4213. g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
  4214. g.IO.InputQueueCharacters.resize(0);
  4215. g.IO.KeyModsPrev = g.IO.KeyMods; // doing it here is better than in NewFrame() as we'll tolerate backend writing to KeyMods. If we want to firmly disallow it we should detect it.
  4216. memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
  4217. CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
  4218. }
  4219. // Prepare the data for rendering so you can call GetDrawData()
  4220. // (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
  4221. // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
  4222. void ImGui::Render()
  4223. {
  4224. ImGuiContext& g = *GImGui;
  4225. IM_ASSERT(g.Initialized);
  4226. if (g.FrameCountEnded != g.FrameCount)
  4227. EndFrame();
  4228. const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
  4229. g.FrameCountRendered = g.FrameCount;
  4230. g.IO.MetricsRenderWindows = 0;
  4231. CallContextHooks(&g, ImGuiContextHookType_RenderPre);
  4232. // Add background ImDrawList (for each active viewport)
  4233. for (int n = 0; n != g.Viewports.Size; n++)
  4234. {
  4235. ImGuiViewportP* viewport = g.Viewports[n];
  4236. viewport->DrawDataBuilder.Clear();
  4237. if (viewport->DrawLists[0] != NULL)
  4238. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
  4239. }
  4240. // Draw modal/window whitening backgrounds
  4241. if (first_render_of_frame)
  4242. RenderDimmedBackgrounds();
  4243. // Add ImDrawList to render
  4244. ImGuiWindow* windows_to_render_top_most[2];
  4245. windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
  4246. windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
  4247. for (int n = 0; n != g.Windows.Size; n++)
  4248. {
  4249. ImGuiWindow* window = g.Windows[n];
  4250. IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
  4251. if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
  4252. AddRootWindowToDrawData(window);
  4253. }
  4254. for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
  4255. if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
  4256. AddRootWindowToDrawData(windows_to_render_top_most[n]);
  4257. // Setup ImDrawData structures for end-user
  4258. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
  4259. for (int n = 0; n < g.Viewports.Size; n++)
  4260. {
  4261. ImGuiViewportP* viewport = g.Viewports[n];
  4262. viewport->DrawDataBuilder.FlattenIntoSingleLayer();
  4263. // Draw software mouse cursor if requested by io.MouseDrawCursor flag
  4264. if (g.IO.MouseDrawCursor && first_render_of_frame)
  4265. RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
  4266. // Add foreground ImDrawList (for each active viewport)
  4267. if (viewport->DrawLists[1] != NULL)
  4268. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
  4269. SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
  4270. ImDrawData* draw_data = &viewport->DrawDataP;
  4271. g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
  4272. g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
  4273. }
  4274. CallContextHooks(&g, ImGuiContextHookType_RenderPost);
  4275. }
  4276. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  4277. // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
  4278. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  4279. {
  4280. ImGuiContext& g = *GImGui;
  4281. const char* text_display_end;
  4282. if (hide_text_after_double_hash)
  4283. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  4284. else
  4285. text_display_end = text_end;
  4286. ImFont* font = g.Font;
  4287. const float font_size = g.FontSize;
  4288. if (text == text_display_end)
  4289. return ImVec2(0.0f, font_size);
  4290. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  4291. // Round
  4292. // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
  4293. // FIXME: Investigate using ceilf or e.g.
  4294. // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
  4295. // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
  4296. text_size.x = IM_FLOOR(text_size.x + 0.99999f);
  4297. return text_size;
  4298. }
  4299. // Find window given position, search front-to-back
  4300. // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
  4301. // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
  4302. // called, aka before the next Begin(). Moving window isn't affected.
  4303. static void FindHoveredWindow()
  4304. {
  4305. ImGuiContext& g = *GImGui;
  4306. ImGuiWindow* hovered_window = NULL;
  4307. ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
  4308. if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
  4309. hovered_window = g.MovingWindow;
  4310. ImVec2 padding_regular = g.Style.TouchExtraPadding;
  4311. ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
  4312. for (int i = g.Windows.Size - 1; i >= 0; i--)
  4313. {
  4314. ImGuiWindow* window = g.Windows[i];
  4315. IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
  4316. if (!window->Active || window->Hidden)
  4317. continue;
  4318. if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
  4319. continue;
  4320. // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
  4321. ImRect bb(window->OuterRectClipped);
  4322. if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
  4323. bb.Expand(padding_regular);
  4324. else
  4325. bb.Expand(padding_for_resize);
  4326. if (!bb.Contains(g.IO.MousePos))
  4327. continue;
  4328. // Support for one rectangular hole in any given window
  4329. // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
  4330. if (window->HitTestHoleSize.x != 0)
  4331. {
  4332. ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
  4333. ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
  4334. if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
  4335. continue;
  4336. }
  4337. if (hovered_window == NULL)
  4338. hovered_window = window;
  4339. IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
  4340. if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
  4341. hovered_window_ignoring_moving_window = window;
  4342. if (hovered_window && hovered_window_ignoring_moving_window)
  4343. break;
  4344. }
  4345. g.HoveredWindow = hovered_window;
  4346. g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
  4347. }
  4348. bool ImGui::IsItemActive()
  4349. {
  4350. ImGuiContext& g = *GImGui;
  4351. if (g.ActiveId)
  4352. return g.ActiveId == g.LastItemData.ID;
  4353. return false;
  4354. }
  4355. bool ImGui::IsItemActivated()
  4356. {
  4357. ImGuiContext& g = *GImGui;
  4358. if (g.ActiveId)
  4359. if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
  4360. return true;
  4361. return false;
  4362. }
  4363. bool ImGui::IsItemDeactivated()
  4364. {
  4365. ImGuiContext& g = *GImGui;
  4366. if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
  4367. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
  4368. return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
  4369. }
  4370. bool ImGui::IsItemDeactivatedAfterEdit()
  4371. {
  4372. ImGuiContext& g = *GImGui;
  4373. return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
  4374. }
  4375. // == GetItemID() == GetFocusID()
  4376. bool ImGui::IsItemFocused()
  4377. {
  4378. ImGuiContext& g = *GImGui;
  4379. if (g.NavId != g.LastItemData.ID || g.NavId == 0)
  4380. return false;
  4381. return true;
  4382. }
  4383. // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
  4384. // Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
  4385. bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
  4386. {
  4387. return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
  4388. }
  4389. bool ImGui::IsItemToggledOpen()
  4390. {
  4391. ImGuiContext& g = *GImGui;
  4392. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
  4393. }
  4394. bool ImGui::IsItemToggledSelection()
  4395. {
  4396. ImGuiContext& g = *GImGui;
  4397. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
  4398. }
  4399. bool ImGui::IsAnyItemHovered()
  4400. {
  4401. ImGuiContext& g = *GImGui;
  4402. return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
  4403. }
  4404. bool ImGui::IsAnyItemActive()
  4405. {
  4406. ImGuiContext& g = *GImGui;
  4407. return g.ActiveId != 0;
  4408. }
  4409. bool ImGui::IsAnyItemFocused()
  4410. {
  4411. ImGuiContext& g = *GImGui;
  4412. return g.NavId != 0 && !g.NavDisableHighlight;
  4413. }
  4414. bool ImGui::IsItemVisible()
  4415. {
  4416. ImGuiContext& g = *GImGui;
  4417. return g.CurrentWindow->ClipRect.Overlaps(g.LastItemData.Rect);
  4418. }
  4419. bool ImGui::IsItemEdited()
  4420. {
  4421. ImGuiContext& g = *GImGui;
  4422. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
  4423. }
  4424. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  4425. // FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
  4426. void ImGui::SetItemAllowOverlap()
  4427. {
  4428. ImGuiContext& g = *GImGui;
  4429. ImGuiID id = g.LastItemData.ID;
  4430. if (g.HoveredId == id)
  4431. g.HoveredIdAllowOverlap = true;
  4432. if (g.ActiveId == id)
  4433. g.ActiveIdAllowOverlap = true;
  4434. }
  4435. void ImGui::SetItemUsingMouseWheel()
  4436. {
  4437. ImGuiContext& g = *GImGui;
  4438. ImGuiID id = g.LastItemData.ID;
  4439. if (g.HoveredId == id)
  4440. g.HoveredIdUsingMouseWheel = true;
  4441. if (g.ActiveId == id)
  4442. g.ActiveIdUsingMouseWheel = true;
  4443. }
  4444. void ImGui::SetActiveIdUsingNavAndKeys()
  4445. {
  4446. ImGuiContext& g = *GImGui;
  4447. IM_ASSERT(g.ActiveId != 0);
  4448. g.ActiveIdUsingNavDirMask = ~(ImU32)0;
  4449. g.ActiveIdUsingNavInputMask = ~(ImU32)0;
  4450. g.ActiveIdUsingKeyInputMask.SetAllBits();
  4451. NavMoveRequestCancel();
  4452. }
  4453. ImVec2 ImGui::GetItemRectMin()
  4454. {
  4455. ImGuiContext& g = *GImGui;
  4456. return g.LastItemData.Rect.Min;
  4457. }
  4458. ImVec2 ImGui::GetItemRectMax()
  4459. {
  4460. ImGuiContext& g = *GImGui;
  4461. return g.LastItemData.Rect.Max;
  4462. }
  4463. ImVec2 ImGui::GetItemRectSize()
  4464. {
  4465. ImGuiContext& g = *GImGui;
  4466. return g.LastItemData.Rect.GetSize();
  4467. }
  4468. bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
  4469. {
  4470. ImGuiContext& g = *GImGui;
  4471. ImGuiWindow* parent_window = g.CurrentWindow;
  4472. flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;
  4473. flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
  4474. // Size
  4475. const ImVec2 content_avail = GetContentRegionAvail();
  4476. ImVec2 size = ImFloor(size_arg);
  4477. const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
  4478. if (size.x <= 0.0f)
  4479. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  4480. if (size.y <= 0.0f)
  4481. size.y = ImMax(content_avail.y + size.y, 4.0f);
  4482. SetNextWindowSize(size);
  4483. // 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.
  4484. if (name)
  4485. ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%s_%08X", parent_window->Name, name, id);
  4486. else
  4487. ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%08X", parent_window->Name, id);
  4488. const float backup_border_size = g.Style.ChildBorderSize;
  4489. if (!border)
  4490. g.Style.ChildBorderSize = 0.0f;
  4491. bool ret = Begin(g.TempBuffer, NULL, flags);
  4492. g.Style.ChildBorderSize = backup_border_size;
  4493. ImGuiWindow* child_window = g.CurrentWindow;
  4494. child_window->ChildId = id;
  4495. child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
  4496. // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
  4497. // While this is not really documented/defined, it seems that the expected thing to do.
  4498. if (child_window->BeginCount == 1)
  4499. parent_window->DC.CursorPos = child_window->Pos;
  4500. // Process navigation-in immediately so NavInit can run on first frame
  4501. if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
  4502. {
  4503. FocusWindow(child_window);
  4504. NavInitWindow(child_window, false);
  4505. SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
  4506. g.ActiveIdSource = ImGuiInputSource_Nav;
  4507. }
  4508. return ret;
  4509. }
  4510. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4511. {
  4512. ImGuiWindow* window = GetCurrentWindow();
  4513. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  4514. }
  4515. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4516. {
  4517. IM_ASSERT(id != 0);
  4518. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  4519. }
  4520. void ImGui::EndChild()
  4521. {
  4522. ImGuiContext& g = *GImGui;
  4523. ImGuiWindow* window = g.CurrentWindow;
  4524. IM_ASSERT(g.WithinEndChild == false);
  4525. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
  4526. g.WithinEndChild = true;
  4527. if (window->BeginCount > 1)
  4528. {
  4529. End();
  4530. }
  4531. else
  4532. {
  4533. ImVec2 sz = window->Size;
  4534. if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  4535. sz.x = ImMax(4.0f, sz.x);
  4536. if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
  4537. sz.y = ImMax(4.0f, sz.y);
  4538. End();
  4539. ImGuiWindow* parent_window = g.CurrentWindow;
  4540. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  4541. ItemSize(sz);
  4542. if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
  4543. {
  4544. ItemAdd(bb, window->ChildId);
  4545. RenderNavHighlight(bb, window->ChildId);
  4546. // 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)
  4547. if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
  4548. RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
  4549. }
  4550. else
  4551. {
  4552. // Not navigable into
  4553. ItemAdd(bb, 0);
  4554. }
  4555. if (g.HoveredWindow == window)
  4556. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
  4557. }
  4558. g.WithinEndChild = false;
  4559. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  4560. }
  4561. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  4562. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  4563. {
  4564. ImGuiContext& g = *GImGui;
  4565. const ImGuiStyle& style = g.Style;
  4566. PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
  4567. PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
  4568. PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
  4569. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  4570. bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  4571. PopStyleVar(3);
  4572. PopStyleColor();
  4573. return ret;
  4574. }
  4575. void ImGui::EndChildFrame()
  4576. {
  4577. EndChild();
  4578. }
  4579. static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
  4580. {
  4581. window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
  4582. window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
  4583. window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
  4584. }
  4585. ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
  4586. {
  4587. ImGuiContext& g = *GImGui;
  4588. return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
  4589. }
  4590. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  4591. {
  4592. ImGuiID id = ImHashStr(name);
  4593. return FindWindowByID(id);
  4594. }
  4595. static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
  4596. {
  4597. window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y));
  4598. if (settings->Size.x > 0 && settings->Size.y > 0)
  4599. window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
  4600. window->Collapsed = settings->Collapsed;
  4601. }
  4602. static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
  4603. {
  4604. ImGuiContext& g = *GImGui;
  4605. const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0;
  4606. const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
  4607. if ((just_created || child_flag_changed) && !new_is_explicit_child)
  4608. {
  4609. IM_ASSERT(!g.WindowsFocusOrder.contains(window));
  4610. g.WindowsFocusOrder.push_back(window);
  4611. window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
  4612. }
  4613. else if (!just_created && child_flag_changed && new_is_explicit_child)
  4614. {
  4615. IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
  4616. for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
  4617. g.WindowsFocusOrder[n]->FocusOrder--;
  4618. g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
  4619. window->FocusOrder = -1;
  4620. }
  4621. window->IsExplicitChild = new_is_explicit_child;
  4622. }
  4623. static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
  4624. {
  4625. ImGuiContext& g = *GImGui;
  4626. //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
  4627. // Create window the first time
  4628. ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
  4629. window->Flags = flags;
  4630. g.WindowsById.SetVoidPtr(window->ID, window);
  4631. // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  4632. const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  4633. window->Pos = main_viewport->Pos + ImVec2(60, 60);
  4634. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  4635. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4636. if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
  4637. {
  4638. // Retrieve settings from .ini file
  4639. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  4640. SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
  4641. ApplyWindowSettings(window, settings);
  4642. }
  4643. window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
  4644. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  4645. {
  4646. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  4647. window->AutoFitOnlyGrows = false;
  4648. }
  4649. else
  4650. {
  4651. if (window->Size.x <= 0.0f)
  4652. window->AutoFitFramesX = 2;
  4653. if (window->Size.y <= 0.0f)
  4654. window->AutoFitFramesY = 2;
  4655. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  4656. }
  4657. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  4658. g.Windows.push_front(window); // Quite slow but rare and only once
  4659. else
  4660. g.Windows.push_back(window);
  4661. UpdateWindowInFocusOrderList(window, true, window->Flags);
  4662. return window;
  4663. }
  4664. static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
  4665. {
  4666. ImGuiContext& g = *GImGui;
  4667. ImVec2 new_size = size_desired;
  4668. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
  4669. {
  4670. // Using -1,-1 on either X/Y axis to preserve the current size.
  4671. ImRect cr = g.NextWindowData.SizeConstraintRect;
  4672. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  4673. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  4674. if (g.NextWindowData.SizeCallback)
  4675. {
  4676. ImGuiSizeCallbackData data;
  4677. data.UserData = g.NextWindowData.SizeCallbackUserData;
  4678. data.Pos = window->Pos;
  4679. data.CurrentSize = window->SizeFull;
  4680. data.DesiredSize = new_size;
  4681. g.NextWindowData.SizeCallback(&data);
  4682. new_size = data.DesiredSize;
  4683. }
  4684. new_size.x = IM_FLOOR(new_size.x);
  4685. new_size.y = IM_FLOOR(new_size.y);
  4686. }
  4687. // Minimum size
  4688. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  4689. {
  4690. ImGuiWindow* window_for_height = window;
  4691. const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight();
  4692. new_size = ImMax(new_size, g.Style.WindowMinSize);
  4693. new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
  4694. }
  4695. return new_size;
  4696. }
  4697. static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
  4698. {
  4699. bool preserve_old_content_sizes = false;
  4700. if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  4701. preserve_old_content_sizes = true;
  4702. else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
  4703. preserve_old_content_sizes = true;
  4704. if (preserve_old_content_sizes)
  4705. {
  4706. *content_size_current = window->ContentSize;
  4707. *content_size_ideal = window->ContentSizeIdeal;
  4708. return;
  4709. }
  4710. content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
  4711. content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
  4712. content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
  4713. content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
  4714. }
  4715. static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
  4716. {
  4717. ImGuiContext& g = *GImGui;
  4718. ImGuiStyle& style = g.Style;
  4719. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  4720. ImVec2 size_pad = window->WindowPadding * 2.0f;
  4721. ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height);
  4722. if (window->Flags & ImGuiWindowFlags_Tooltip)
  4723. {
  4724. // Tooltip always resize
  4725. return size_desired;
  4726. }
  4727. else
  4728. {
  4729. // Maximum window size is determined by the viewport size or monitor size
  4730. const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
  4731. const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
  4732. ImVec2 size_min = style.WindowMinSize;
  4733. if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
  4734. size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
  4735. // FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows?
  4736. ImVec2 avail_size = ImGui::GetMainViewport()->Size;
  4737. ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
  4738. // When the window cannot fit all contents (either because of constraints, either because screen is too small),
  4739. // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
  4740. ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4741. bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - 0.0f < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
  4742. bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_up_height < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
  4743. if (will_have_scrollbar_x)
  4744. size_auto_fit.y += style.ScrollbarSize;
  4745. if (will_have_scrollbar_y)
  4746. size_auto_fit.x += style.ScrollbarSize;
  4747. return size_auto_fit;
  4748. }
  4749. }
  4750. ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
  4751. {
  4752. ImVec2 size_contents_current;
  4753. ImVec2 size_contents_ideal;
  4754. CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
  4755. ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
  4756. ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4757. return size_final;
  4758. }
  4759. static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
  4760. {
  4761. if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  4762. return ImGuiCol_PopupBg;
  4763. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  4764. return ImGuiCol_ChildBg;
  4765. return ImGuiCol_WindowBg;
  4766. }
  4767. static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
  4768. {
  4769. ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
  4770. ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
  4771. ImVec2 size_expected = pos_max - pos_min;
  4772. ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
  4773. *out_pos = pos_min;
  4774. if (corner_norm.x == 0.0f)
  4775. out_pos->x -= (size_constrained.x - size_expected.x);
  4776. if (corner_norm.y == 0.0f)
  4777. out_pos->y -= (size_constrained.y - size_expected.y);
  4778. *out_size = size_constrained;
  4779. }
  4780. // Data for resizing from corner
  4781. struct ImGuiResizeGripDef
  4782. {
  4783. ImVec2 CornerPosN;
  4784. ImVec2 InnerDir;
  4785. int AngleMin12, AngleMax12;
  4786. };
  4787. static const ImGuiResizeGripDef resize_grip_def[4] =
  4788. {
  4789. { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
  4790. { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
  4791. { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
  4792. { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
  4793. };
  4794. // Data for resizing from borders
  4795. struct ImGuiResizeBorderDef
  4796. {
  4797. ImVec2 InnerDir;
  4798. ImVec2 SegmentN1, SegmentN2;
  4799. float OuterAngle;
  4800. };
  4801. static const ImGuiResizeBorderDef resize_border_def[4] =
  4802. {
  4803. { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
  4804. { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
  4805. { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
  4806. { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
  4807. };
  4808. static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
  4809. {
  4810. ImRect rect = window->Rect();
  4811. if (thickness == 0.0f)
  4812. rect.Max -= ImVec2(1, 1);
  4813. if (border_n == ImGuiDir_Left) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); }
  4814. if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); }
  4815. if (border_n == ImGuiDir_Up) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); }
  4816. if (border_n == ImGuiDir_Down) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); }
  4817. IM_ASSERT(0);
  4818. return ImRect();
  4819. }
  4820. // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
  4821. ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
  4822. {
  4823. IM_ASSERT(n >= 0 && n < 4);
  4824. ImGuiID id = window->ID;
  4825. id = ImHashStr("#RESIZE", 0, id);
  4826. id = ImHashData(&n, sizeof(int), id);
  4827. return id;
  4828. }
  4829. // Borders (Left, Right, Up, Down)
  4830. ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
  4831. {
  4832. IM_ASSERT(dir >= 0 && dir < 4);
  4833. int n = (int)dir + 4;
  4834. ImGuiID id = window->ID;
  4835. id = ImHashStr("#RESIZE", 0, id);
  4836. id = ImHashData(&n, sizeof(int), id);
  4837. return id;
  4838. }
  4839. // Handle resize for: Resize Grips, Borders, Gamepad
  4840. // Return true when using auto-fit (double click on resize grip)
  4841. static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
  4842. {
  4843. ImGuiContext& g = *GImGui;
  4844. ImGuiWindowFlags flags = window->Flags;
  4845. if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  4846. return false;
  4847. if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
  4848. return false;
  4849. bool ret_auto_fit = false;
  4850. const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
  4851. const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  4852. const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
  4853. const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
  4854. ImVec2 pos_target(FLT_MAX, FLT_MAX);
  4855. ImVec2 size_target(FLT_MAX, FLT_MAX);
  4856. // Resize grips and borders are on layer 1
  4857. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  4858. // Manual resize grips
  4859. PushID("#RESIZE");
  4860. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  4861. {
  4862. const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
  4863. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
  4864. // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
  4865. bool hovered, held;
  4866. ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
  4867. if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
  4868. if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
  4869. ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
  4870. ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  4871. //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
  4872. if (hovered || held)
  4873. g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  4874. if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
  4875. {
  4876. // Manual auto-fit when double-clicking
  4877. size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4878. ret_auto_fit = true;
  4879. ClearActiveID();
  4880. }
  4881. else if (held)
  4882. {
  4883. // Resize from any of the four corners
  4884. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  4885. ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
  4886. ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
  4887. ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
  4888. corner_target = ImClamp(corner_target, clamp_min, clamp_max);
  4889. CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
  4890. }
  4891. // Only lower-left grip is visible before hovering/activating
  4892. if (resize_grip_n == 0 || held || hovered)
  4893. resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  4894. }
  4895. for (int border_n = 0; border_n < resize_border_count; border_n++)
  4896. {
  4897. const ImGuiResizeBorderDef& def = resize_border_def[border_n];
  4898. const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  4899. bool hovered, held;
  4900. ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
  4901. ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
  4902. ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  4903. //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
  4904. if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
  4905. {
  4906. g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
  4907. if (held)
  4908. *border_held = border_n;
  4909. }
  4910. if (held)
  4911. {
  4912. ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
  4913. ImVec2 clamp_max(border_n == ImGuiDir_Left ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? visibility_rect.Max.y : +FLT_MAX);
  4914. ImVec2 border_target = window->Pos;
  4915. border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
  4916. border_target = ImClamp(border_target, clamp_min, clamp_max);
  4917. CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
  4918. }
  4919. }
  4920. PopID();
  4921. // Restore nav layer
  4922. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  4923. // Navigation resize (keyboard/gamepad)
  4924. if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
  4925. {
  4926. ImVec2 nav_resize_delta;
  4927. if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
  4928. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_RawKeyboard, ImGuiInputReadMode_Down);
  4929. if (g.NavInputSource == ImGuiInputSource_Gamepad)
  4930. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
  4931. if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
  4932. {
  4933. const float NAV_RESIZE_SPEED = 600.0f;
  4934. nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
  4935. nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);
  4936. g.NavWindowingToggleLayer = false;
  4937. g.NavDisableMouseHover = true;
  4938. resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
  4939. // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
  4940. size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
  4941. }
  4942. }
  4943. // Apply back modified position/size to window
  4944. if (size_target.x != FLT_MAX)
  4945. {
  4946. window->SizeFull = size_target;
  4947. MarkIniSettingsDirty(window);
  4948. }
  4949. if (pos_target.x != FLT_MAX)
  4950. {
  4951. window->Pos = ImFloor(pos_target);
  4952. MarkIniSettingsDirty(window);
  4953. }
  4954. window->Size = window->SizeFull;
  4955. return ret_auto_fit;
  4956. }
  4957. static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)
  4958. {
  4959. ImGuiContext& g = *GImGui;
  4960. ImVec2 size_for_clamping = window->Size;
  4961. if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  4962. size_for_clamping.y = window->TitleBarHeight();
  4963. window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
  4964. }
  4965. static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
  4966. {
  4967. ImGuiContext& g = *GImGui;
  4968. float rounding = window->WindowRounding;
  4969. float border_size = window->WindowBorderSize;
  4970. if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
  4971. window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  4972. int border_held = window->ResizeBorderHeld;
  4973. if (border_held != -1)
  4974. {
  4975. const ImGuiResizeBorderDef& def = resize_border_def[border_held];
  4976. ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
  4977. window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
  4978. 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);
  4979. window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
  4980. }
  4981. if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  4982. {
  4983. float y = window->Pos.y + window->TitleBarHeight() - 1;
  4984. window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
  4985. }
  4986. }
  4987. // Draw background and borders
  4988. // Draw and handle scrollbars
  4989. void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
  4990. {
  4991. ImGuiContext& g = *GImGui;
  4992. ImGuiStyle& style = g.Style;
  4993. ImGuiWindowFlags flags = window->Flags;
  4994. // Ensure that ScrollBar doesn't read last frame's SkipItems
  4995. IM_ASSERT(window->BeginCount == 0);
  4996. window->SkipItems = false;
  4997. // Draw window + handle manual resize
  4998. // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
  4999. const float window_rounding = window->WindowRounding;
  5000. const float window_border_size = window->WindowBorderSize;
  5001. if (window->Collapsed)
  5002. {
  5003. // Title bar only
  5004. float backup_border_size = style.FrameBorderSize;
  5005. g.Style.FrameBorderSize = window->WindowBorderSize;
  5006. ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
  5007. RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
  5008. g.Style.FrameBorderSize = backup_border_size;
  5009. }
  5010. else
  5011. {
  5012. // Window background
  5013. if (!(flags & ImGuiWindowFlags_NoBackground))
  5014. {
  5015. ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
  5016. bool override_alpha = false;
  5017. float alpha = 1.0f;
  5018. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
  5019. {
  5020. alpha = g.NextWindowData.BgAlphaVal;
  5021. override_alpha = true;
  5022. }
  5023. if (override_alpha)
  5024. bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
  5025. window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
  5026. }
  5027. // Title bar
  5028. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  5029. {
  5030. ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  5031. window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
  5032. }
  5033. // Menu bar
  5034. if (flags & ImGuiWindowFlags_MenuBar)
  5035. {
  5036. ImRect menu_bar_rect = window->MenuBarRect();
  5037. 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.
  5038. 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);
  5039. if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
  5040. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  5041. }
  5042. // Scrollbars
  5043. if (window->ScrollbarX)
  5044. Scrollbar(ImGuiAxis_X);
  5045. if (window->ScrollbarY)
  5046. Scrollbar(ImGuiAxis_Y);
  5047. // Render resize grips (after their input handling so we don't have a frame of latency)
  5048. if (!(flags & ImGuiWindowFlags_NoResize))
  5049. {
  5050. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5051. {
  5052. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  5053. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
  5054. 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)));
  5055. 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)));
  5056. 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);
  5057. window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
  5058. }
  5059. }
  5060. // Borders
  5061. RenderWindowOuterBorders(window);
  5062. }
  5063. }
  5064. // Render title text, collapse button, close button
  5065. void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
  5066. {
  5067. ImGuiContext& g = *GImGui;
  5068. ImGuiStyle& style = g.Style;
  5069. ImGuiWindowFlags flags = window->Flags;
  5070. const bool has_close_button = (p_open != NULL);
  5071. const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
  5072. // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
  5073. // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
  5074. const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
  5075. g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
  5076. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  5077. // Layout buttons
  5078. // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
  5079. float pad_l = style.FramePadding.x;
  5080. float pad_r = style.FramePadding.x;
  5081. float button_sz = g.FontSize;
  5082. ImVec2 close_button_pos;
  5083. ImVec2 collapse_button_pos;
  5084. if (has_close_button)
  5085. {
  5086. pad_r += button_sz;
  5087. close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5088. }
  5089. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
  5090. {
  5091. pad_r += button_sz;
  5092. collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5093. }
  5094. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
  5095. {
  5096. collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
  5097. pad_l += button_sz;
  5098. }
  5099. // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
  5100. if (has_collapse_button)
  5101. if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
  5102. window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
  5103. // Close button
  5104. if (has_close_button)
  5105. if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
  5106. *p_open = false;
  5107. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5108. g.CurrentItemFlags = item_flags_backup;
  5109. // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
  5110. // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
  5111. const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
  5112. const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
  5113. // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
  5114. // while uncentered title text will still reach edges correctly.
  5115. if (pad_l > style.FramePadding.x)
  5116. pad_l += g.Style.ItemInnerSpacing.x;
  5117. if (pad_r > style.FramePadding.x)
  5118. pad_r += g.Style.ItemInnerSpacing.x;
  5119. if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
  5120. {
  5121. float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
  5122. float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
  5123. pad_l = ImMax(pad_l, pad_extend * centerness);
  5124. pad_r = ImMax(pad_r, pad_extend * centerness);
  5125. }
  5126. 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);
  5127. 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);
  5128. if (flags & ImGuiWindowFlags_UnsavedDocument)
  5129. {
  5130. ImVec2 marker_pos;
  5131. marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
  5132. marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
  5133. if (marker_pos.x > layout_r.Min.x)
  5134. {
  5135. RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
  5136. clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
  5137. }
  5138. }
  5139. //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
  5140. //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
  5141. RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
  5142. }
  5143. void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
  5144. {
  5145. window->ParentWindow = parent_window;
  5146. window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
  5147. if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  5148. window->RootWindow = parent_window->RootWindow;
  5149. if (parent_window && (flags & ImGuiWindowFlags_Popup))
  5150. window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
  5151. if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  5152. window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
  5153. while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
  5154. {
  5155. IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
  5156. window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
  5157. }
  5158. }
  5159. // When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
  5160. // should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
  5161. // In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
  5162. // - Window // FindBlockingModal() returns Modal1
  5163. // - Window // .. returns Modal1
  5164. // - Modal1 // .. returns Modal2
  5165. // - Window // .. returns Modal2
  5166. // - Window // .. returns Modal2
  5167. // - Modal2 // .. returns Modal2
  5168. static ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
  5169. {
  5170. ImGuiContext& g = *GImGui;
  5171. if (g.OpenPopupStack.Size <= 0)
  5172. return NULL;
  5173. // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
  5174. for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
  5175. {
  5176. ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
  5177. if (popup_window == NULL || !popup_window->WasActive || !(popup_window->Flags & ImGuiWindowFlags_Modal)) // Check WasActive, because this code may run before popup renders on current frame.
  5178. continue;
  5179. if (IsWindowWithinBeginStackOf(window, popup_window)) // Window is rendered over last modal, no render order change needed.
  5180. break;
  5181. for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
  5182. if (IsWindowWithinBeginStackOf(window, parent))
  5183. return popup_window; // Place window above its begin stack parent.
  5184. }
  5185. return NULL;
  5186. }
  5187. // Push a new Dear ImGui window to add widgets to.
  5188. // - 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.
  5189. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  5190. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  5191. // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
  5192. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
  5193. // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
  5194. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  5195. {
  5196. ImGuiContext& g = *GImGui;
  5197. const ImGuiStyle& style = g.Style;
  5198. IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
  5199. IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
  5200. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  5201. // Find or create
  5202. ImGuiWindow* window = FindWindowByName(name);
  5203. const bool window_just_created = (window == NULL);
  5204. if (window_just_created)
  5205. window = CreateNewWindow(name, flags);
  5206. else
  5207. UpdateWindowInFocusOrderList(window, window_just_created, flags);
  5208. // Automatically disable manual moving/resizing when NoInputs is set
  5209. if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
  5210. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  5211. if (flags & ImGuiWindowFlags_NavFlattened)
  5212. IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
  5213. const int current_frame = g.FrameCount;
  5214. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  5215. window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
  5216. // Update the Appearing flag
  5217. bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  5218. if (flags & ImGuiWindowFlags_Popup)
  5219. {
  5220. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5221. window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
  5222. window_just_activated_by_user |= (window != popup_ref.Window);
  5223. }
  5224. window->Appearing = window_just_activated_by_user;
  5225. if (window->Appearing)
  5226. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
  5227. // Update Flags, LastFrameActive, BeginOrderXXX fields
  5228. if (first_begin_of_the_frame)
  5229. {
  5230. window->Flags = (ImGuiWindowFlags)flags;
  5231. window->LastFrameActive = current_frame;
  5232. window->LastTimeActive = (float)g.Time;
  5233. window->BeginOrderWithinParent = 0;
  5234. window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
  5235. }
  5236. else
  5237. {
  5238. flags = window->Flags;
  5239. }
  5240. // 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
  5241. ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
  5242. ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
  5243. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  5244. // We allow window memory to be compacted so recreate the base stack when needed.
  5245. if (window->IDStack.Size == 0)
  5246. window->IDStack.push_back(window->ID);
  5247. // Add to stack
  5248. // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
  5249. g.CurrentWindow = window;
  5250. ImGuiWindowStackData window_stack_data;
  5251. window_stack_data.Window = window;
  5252. window_stack_data.ParentLastItemDataBackup = g.LastItemData;
  5253. window_stack_data.StackSizesOnBegin.SetToCurrentState();
  5254. g.CurrentWindowStack.push_back(window_stack_data);
  5255. g.CurrentWindow = NULL;
  5256. if (flags & ImGuiWindowFlags_ChildMenu)
  5257. g.BeginMenuCount++;
  5258. if (flags & ImGuiWindowFlags_Popup)
  5259. {
  5260. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5261. popup_ref.Window = window;
  5262. g.BeginPopupStack.push_back(popup_ref);
  5263. window->PopupId = popup_ref.PopupId;
  5264. }
  5265. // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
  5266. if (first_begin_of_the_frame)
  5267. {
  5268. UpdateWindowParentAndRootLinks(window, flags, parent_window);
  5269. window->ParentWindowInBeginStack = parent_window_in_stack;
  5270. }
  5271. // Process SetNextWindow***() calls
  5272. // (FIXME: Consider splitting the HasXXX flags into X/Y components
  5273. bool window_pos_set_by_api = false;
  5274. bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
  5275. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
  5276. {
  5277. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
  5278. if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
  5279. {
  5280. // May be processed on the next frame if this is our first frame and we are measuring size
  5281. // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
  5282. window->SetWindowPosVal = g.NextWindowData.PosVal;
  5283. window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
  5284. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5285. }
  5286. else
  5287. {
  5288. SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
  5289. }
  5290. }
  5291. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
  5292. {
  5293. window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
  5294. window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
  5295. SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
  5296. }
  5297. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
  5298. {
  5299. if (g.NextWindowData.ScrollVal.x >= 0.0f)
  5300. {
  5301. window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
  5302. window->ScrollTargetCenterRatio.x = 0.0f;
  5303. }
  5304. if (g.NextWindowData.ScrollVal.y >= 0.0f)
  5305. {
  5306. window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
  5307. window->ScrollTargetCenterRatio.y = 0.0f;
  5308. }
  5309. }
  5310. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
  5311. window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
  5312. else if (first_begin_of_the_frame)
  5313. window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
  5314. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
  5315. SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
  5316. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
  5317. FocusWindow(window);
  5318. if (window->Appearing)
  5319. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
  5320. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  5321. if (first_begin_of_the_frame)
  5322. {
  5323. // Initialize
  5324. const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
  5325. window->Active = true;
  5326. window->HasCloseButton = (p_open != NULL);
  5327. window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
  5328. window->IDStack.resize(1);
  5329. window->DrawList->_ResetForNewFrame();
  5330. window->DC.CurrentTableIdx = -1;
  5331. // Restore buffer capacity when woken from a compacted state, to avoid
  5332. if (window->MemoryCompacted)
  5333. GcAwakeTransientWindowBuffers(window);
  5334. // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
  5335. // 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.
  5336. bool window_title_visible_elsewhere = false;
  5337. if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
  5338. window_title_visible_elsewhere = true;
  5339. if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
  5340. {
  5341. size_t buf_len = (size_t)window->NameBufLen;
  5342. window->Name = ImStrdupcpy(window->Name, &buf_len, name);
  5343. window->NameBufLen = (int)buf_len;
  5344. }
  5345. // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
  5346. // Update contents size from last frame for auto-fitting (or use explicit size)
  5347. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
  5348. CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
  5349. if (window->HiddenFramesCanSkipItems > 0)
  5350. window->HiddenFramesCanSkipItems--;
  5351. if (window->HiddenFramesCannotSkipItems > 0)
  5352. window->HiddenFramesCannotSkipItems--;
  5353. if (window->HiddenFramesForRenderOnly > 0)
  5354. window->HiddenFramesForRenderOnly--;
  5355. // Hide new windows for one frame until they calculate their size
  5356. if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
  5357. window->HiddenFramesCannotSkipItems = 1;
  5358. // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
  5359. // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
  5360. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
  5361. {
  5362. window->HiddenFramesCannotSkipItems = 1;
  5363. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  5364. {
  5365. if (!window_size_x_set_by_api)
  5366. window->Size.x = window->SizeFull.x = 0.f;
  5367. if (!window_size_y_set_by_api)
  5368. window->Size.y = window->SizeFull.y = 0.f;
  5369. window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
  5370. }
  5371. }
  5372. // SELECT VIEWPORT
  5373. // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
  5374. SetCurrentWindow(window);
  5375. // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
  5376. if (flags & ImGuiWindowFlags_ChildWindow)
  5377. window->WindowBorderSize = style.ChildBorderSize;
  5378. else
  5379. window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
  5380. window->WindowPadding = style.WindowPadding;
  5381. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
  5382. window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
  5383. // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
  5384. window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
  5385. window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
  5386. // Collapse window by double-clicking on title bar
  5387. // 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
  5388. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  5389. {
  5390. // 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.
  5391. ImRect title_bar_rect = window->TitleBarRect();
  5392. if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
  5393. window->WantCollapseToggle = true;
  5394. if (window->WantCollapseToggle)
  5395. {
  5396. window->Collapsed = !window->Collapsed;
  5397. MarkIniSettingsDirty(window);
  5398. }
  5399. }
  5400. else
  5401. {
  5402. window->Collapsed = false;
  5403. }
  5404. window->WantCollapseToggle = false;
  5405. // SIZE
  5406. // Calculate auto-fit size, handle automatic resize
  5407. const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
  5408. bool use_current_size_for_scrollbar_x = window_just_created;
  5409. bool use_current_size_for_scrollbar_y = window_just_created;
  5410. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
  5411. {
  5412. // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
  5413. if (!window_size_x_set_by_api)
  5414. {
  5415. window->SizeFull.x = size_auto_fit.x;
  5416. use_current_size_for_scrollbar_x = true;
  5417. }
  5418. if (!window_size_y_set_by_api)
  5419. {
  5420. window->SizeFull.y = size_auto_fit.y;
  5421. use_current_size_for_scrollbar_y = true;
  5422. }
  5423. }
  5424. else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5425. {
  5426. // Auto-fit may only grow window during the first few frames
  5427. // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  5428. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
  5429. {
  5430. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  5431. use_current_size_for_scrollbar_x = true;
  5432. }
  5433. if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
  5434. {
  5435. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  5436. use_current_size_for_scrollbar_y = true;
  5437. }
  5438. if (!window->Collapsed)
  5439. MarkIniSettingsDirty(window);
  5440. }
  5441. // Apply minimum/maximum window size constraints and final size
  5442. window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
  5443. window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
  5444. // Decoration size
  5445. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  5446. // POSITION
  5447. // Popup latch its initial position, will position itself when it appears next frame
  5448. if (window_just_activated_by_user)
  5449. {
  5450. window->AutoPosLastDirection = ImGuiDir_None;
  5451. if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
  5452. window->Pos = g.BeginPopupStack.back().OpenPopupPos;
  5453. }
  5454. // Position child window
  5455. if (flags & ImGuiWindowFlags_ChildWindow)
  5456. {
  5457. IM_ASSERT(parent_window && parent_window->Active);
  5458. window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
  5459. parent_window->DC.ChildWindows.push_back(window);
  5460. if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
  5461. window->Pos = parent_window->DC.CursorPos;
  5462. }
  5463. const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
  5464. if (window_pos_with_pivot)
  5465. SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
  5466. else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
  5467. window->Pos = FindBestWindowPosForPopup(window);
  5468. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
  5469. window->Pos = FindBestWindowPosForPopup(window);
  5470. else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
  5471. window->Pos = FindBestWindowPosForPopup(window);
  5472. // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
  5473. // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
  5474. ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
  5475. ImRect viewport_rect(viewport->GetMainRect());
  5476. ImRect viewport_work_rect(viewport->GetWorkRect());
  5477. ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  5478. ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
  5479. // Clamp position/size so window stays visible within its viewport or monitor
  5480. // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
  5481. if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  5482. if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
  5483. ClampWindowRect(window, visibility_rect);
  5484. window->Pos = ImFloor(window->Pos);
  5485. // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
  5486. // Large values tend to lead to variety of artifacts and are not recommended.
  5487. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
  5488. // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
  5489. //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5490. // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
  5491. // Apply window focus (new and reactivated windows are moved to front)
  5492. bool want_focus = false;
  5493. if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  5494. {
  5495. if (flags & ImGuiWindowFlags_Popup)
  5496. want_focus = true;
  5497. else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
  5498. want_focus = true;
  5499. ImGuiWindow* modal = GetTopMostPopupModal();
  5500. if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))
  5501. {
  5502. // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.
  5503. // Since window is not focused it would reappear at the same display position like the last time it was visible.
  5504. // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.
  5505. // Position window behind a modal that is not a begin-parent of this window.
  5506. want_focus = false;
  5507. if (window == window->RootWindow)
  5508. {
  5509. ImGuiWindow* blocking_modal = FindBlockingModal(window);
  5510. IM_ASSERT(blocking_modal != NULL);
  5511. BringWindowToDisplayBehind(window, blocking_modal);
  5512. }
  5513. }
  5514. }
  5515. // Handle manual resize: Resize Grips, Borders, Gamepad
  5516. int border_held = -1;
  5517. ImU32 resize_grip_col[4] = {};
  5518. const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
  5519. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  5520. if (!window->Collapsed)
  5521. if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
  5522. use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
  5523. window->ResizeBorderHeld = (signed char)border_held;
  5524. // SCROLLBAR VISIBILITY
  5525. // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
  5526. if (!window->Collapsed)
  5527. {
  5528. // When reading the current size we need to read it after size constraints have been applied.
  5529. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
  5530. ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
  5531. ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
  5532. ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
  5533. float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
  5534. float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
  5535. //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
  5536. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
  5537. 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));
  5538. if (window->ScrollbarX && !window->ScrollbarY)
  5539. window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
  5540. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  5541. }
  5542. // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
  5543. // Update various regions. Variables they depends on should be set above in this function.
  5544. // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
  5545. // Outer rectangle
  5546. // Not affected by window border size. Used by:
  5547. // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
  5548. // - Begin() initial clipping rect for drawing window background and borders.
  5549. // - Begin() clipping whole child
  5550. const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
  5551. const ImRect outer_rect = window->Rect();
  5552. const ImRect title_bar_rect = window->TitleBarRect();
  5553. window->OuterRectClipped = outer_rect;
  5554. window->OuterRectClipped.ClipWith(host_rect);
  5555. // Inner rectangle
  5556. // Not affected by window border size. Used by:
  5557. // - InnerClipRect
  5558. // - ScrollToRectEx()
  5559. // - NavUpdatePageUpPageDown()
  5560. // - Scrollbar()
  5561. window->InnerRect.Min.x = window->Pos.x;
  5562. window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
  5563. window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
  5564. window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
  5565. // Inner clipping rectangle.
  5566. // Will extend a little bit outside the normal work region.
  5567. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
  5568. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  5569. // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
  5570. // Affected by window/frame border size. Used by:
  5571. // - Begin() initial clip rect
  5572. float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
  5573. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5574. window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
  5575. window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5576. window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
  5577. window->InnerClipRect.ClipWithFull(host_rect);
  5578. // Default item width. Make it proportional to window size if window manually resizes
  5579. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  5580. window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
  5581. else
  5582. window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
  5583. // SCROLLING
  5584. // Lock down maximum scrolling
  5585. // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
  5586. // for right/bottom aligned items without creating a scrollbar.
  5587. window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
  5588. window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
  5589. // Apply scrolling
  5590. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  5591. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  5592. // DRAWING
  5593. // Setup draw list and outer clipping rectangle
  5594. IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
  5595. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  5596. PushClipRect(host_rect.Min, host_rect.Max, false);
  5597. // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
  5598. // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
  5599. // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
  5600. {
  5601. bool render_decorations_in_parent = false;
  5602. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
  5603. {
  5604. // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
  5605. // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
  5606. ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
  5607. bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
  5608. bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
  5609. if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
  5610. render_decorations_in_parent = true;
  5611. }
  5612. if (render_decorations_in_parent)
  5613. window->DrawList = parent_window->DrawList;
  5614. // Handle title bar, scrollbar, resize grips and resize borders
  5615. const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
  5616. const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
  5617. RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
  5618. if (render_decorations_in_parent)
  5619. window->DrawList = &window->DrawListInst;
  5620. }
  5621. // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
  5622. // Work rectangle.
  5623. // Affected by window padding and border size. Used by:
  5624. // - Columns() for right-most edge
  5625. // - TreeNode(), CollapsingHeader() for right-most edge
  5626. // - BeginTabBar() for right-most edge
  5627. const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
  5628. const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
  5629. const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
  5630. const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
  5631. window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
  5632. window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
  5633. window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
  5634. window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
  5635. window->ParentWorkRect = window->WorkRect;
  5636. // [LEGACY] Content Region
  5637. // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
  5638. // Used by:
  5639. // - Mouse wheel scrolling + many other things
  5640. window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
  5641. window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
  5642. window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
  5643. window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
  5644. // Setup drawing context
  5645. // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
  5646. window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
  5647. window->DC.GroupOffset.x = 0.0f;
  5648. window->DC.ColumnsOffset.x = 0.0f;
  5649. // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
  5650. // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
  5651. double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DC.ColumnsOffset.x;
  5652. double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + decoration_up_height;
  5653. window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
  5654. window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
  5655. window->DC.CursorPos = window->DC.CursorStartPos;
  5656. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  5657. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  5658. window->DC.IdealMaxPos = window->DC.CursorStartPos;
  5659. window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
  5660. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  5661. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5662. window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
  5663. window->DC.NavLayersActiveMaskNext = 0x00;
  5664. window->DC.NavHideHighlightOneFrame = false;
  5665. window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
  5666. window->DC.MenuBarAppending = false;
  5667. window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
  5668. window->DC.TreeDepth = 0;
  5669. window->DC.TreeJumpToParentOnPopMask = 0x00;
  5670. window->DC.ChildWindows.resize(0);
  5671. window->DC.StateStorage = &window->StateStorage;
  5672. window->DC.CurrentColumns = NULL;
  5673. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  5674. window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
  5675. window->DC.ItemWidth = window->ItemWidthDefault;
  5676. window->DC.TextWrapPos = -1.0f; // disabled
  5677. window->DC.ItemWidthStack.resize(0);
  5678. window->DC.TextWrapPosStack.resize(0);
  5679. if (window->AutoFitFramesX > 0)
  5680. window->AutoFitFramesX--;
  5681. if (window->AutoFitFramesY > 0)
  5682. window->AutoFitFramesY--;
  5683. // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  5684. if (want_focus)
  5685. {
  5686. FocusWindow(window);
  5687. NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
  5688. }
  5689. // Title bar
  5690. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  5691. 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);
  5692. // Clear hit test shape every frame
  5693. window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
  5694. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  5695. // 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.
  5696. // Maybe we can support CTRL+C on every element?
  5697. /*
  5698. //if (g.NavWindow == window && g.ActiveId == 0)
  5699. if (g.ActiveId == window->MoveId)
  5700. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  5701. LogToClipboard();
  5702. */
  5703. // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
  5704. // This is useful to allow creating context menus on title bar only, etc.
  5705. SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
  5706. #ifdef IMGUI_ENABLE_TEST_ENGINE
  5707. if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5708. IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);
  5709. #endif
  5710. }
  5711. else
  5712. {
  5713. // Append
  5714. SetCurrentWindow(window);
  5715. }
  5716. // Pull/inherit current state
  5717. window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : window->GetID("#FOCUSSCOPE"); // Inherit from parent only // -V595
  5718. PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
  5719. // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
  5720. window->WriteAccessed = false;
  5721. window->BeginCount++;
  5722. g.NextWindowData.ClearFlags();
  5723. // Update visibility
  5724. if (first_begin_of_the_frame)
  5725. {
  5726. if (flags & ImGuiWindowFlags_ChildWindow)
  5727. {
  5728. // Child window can be out of sight and have "negative" clip windows.
  5729. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
  5730. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  5731. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
  5732. {
  5733. const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
  5734. if (!g.LogEnabled && !nav_request)
  5735. if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
  5736. window->HiddenFramesCanSkipItems = 1;
  5737. }
  5738. // Hide along with parent or if parent is collapsed
  5739. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
  5740. window->HiddenFramesCanSkipItems = 1;
  5741. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
  5742. window->HiddenFramesCannotSkipItems = 1;
  5743. }
  5744. // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
  5745. if (style.Alpha <= 0.0f)
  5746. window->HiddenFramesCanSkipItems = 1;
  5747. // Update the Hidden flag
  5748. bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
  5749. window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
  5750. // Disable inputs for requested number of frames
  5751. if (window->DisableInputsFrames > 0)
  5752. {
  5753. window->DisableInputsFrames--;
  5754. window->Flags |= ImGuiWindowFlags_NoInputs;
  5755. }
  5756. // Update the SkipItems flag, used to early out of all items functions (no layout required)
  5757. bool skip_items = false;
  5758. if (window->Collapsed || !window->Active || hidden_regular)
  5759. if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
  5760. skip_items = true;
  5761. window->SkipItems = skip_items;
  5762. }
  5763. return !window->SkipItems;
  5764. }
  5765. void ImGui::End()
  5766. {
  5767. ImGuiContext& g = *GImGui;
  5768. ImGuiWindow* window = g.CurrentWindow;
  5769. // Error checking: verify that user hasn't called End() too many times!
  5770. if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
  5771. {
  5772. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
  5773. return;
  5774. }
  5775. IM_ASSERT(g.CurrentWindowStack.Size > 0);
  5776. // Error checking: verify that user doesn't directly call End() on a child window.
  5777. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  5778. IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
  5779. // Close anything that is open
  5780. if (window->DC.CurrentColumns)
  5781. EndColumns();
  5782. PopClipRect(); // Inner window clip rectangle
  5783. // Stop logging
  5784. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  5785. LogFinish();
  5786. // Pop from window stack
  5787. g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
  5788. if (window->Flags & ImGuiWindowFlags_ChildMenu)
  5789. g.BeginMenuCount--;
  5790. if (window->Flags & ImGuiWindowFlags_Popup)
  5791. g.BeginPopupStack.pop_back();
  5792. g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();
  5793. g.CurrentWindowStack.pop_back();
  5794. SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
  5795. }
  5796. void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
  5797. {
  5798. ImGuiContext& g = *GImGui;
  5799. IM_ASSERT(window == window->RootWindow);
  5800. const int cur_order = window->FocusOrder;
  5801. IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
  5802. if (g.WindowsFocusOrder.back() == window)
  5803. return;
  5804. const int new_order = g.WindowsFocusOrder.Size - 1;
  5805. for (int n = cur_order; n < new_order; n++)
  5806. {
  5807. g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
  5808. g.WindowsFocusOrder[n]->FocusOrder--;
  5809. IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
  5810. }
  5811. g.WindowsFocusOrder[new_order] = window;
  5812. window->FocusOrder = (short)new_order;
  5813. }
  5814. void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
  5815. {
  5816. ImGuiContext& g = *GImGui;
  5817. ImGuiWindow* current_front_window = g.Windows.back();
  5818. if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
  5819. return;
  5820. for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
  5821. if (g.Windows[i] == window)
  5822. {
  5823. memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
  5824. g.Windows[g.Windows.Size - 1] = window;
  5825. break;
  5826. }
  5827. }
  5828. void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
  5829. {
  5830. ImGuiContext& g = *GImGui;
  5831. if (g.Windows[0] == window)
  5832. return;
  5833. for (int i = 0; i < g.Windows.Size; i++)
  5834. if (g.Windows[i] == window)
  5835. {
  5836. memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
  5837. g.Windows[0] = window;
  5838. break;
  5839. }
  5840. }
  5841. void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
  5842. {
  5843. IM_ASSERT(window != NULL && behind_window != NULL);
  5844. ImGuiContext& g = *GImGui;
  5845. window = window->RootWindow;
  5846. behind_window = behind_window->RootWindow;
  5847. int pos_wnd = FindWindowDisplayIndex(window);
  5848. int pos_beh = FindWindowDisplayIndex(behind_window);
  5849. if (pos_wnd < pos_beh)
  5850. {
  5851. size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
  5852. memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
  5853. g.Windows[pos_beh - 1] = window;
  5854. }
  5855. else
  5856. {
  5857. size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
  5858. memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
  5859. g.Windows[pos_beh] = window;
  5860. }
  5861. }
  5862. int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
  5863. {
  5864. ImGuiContext& g = *GImGui;
  5865. return g.Windows.index_from_ptr(g.Windows.find(window));
  5866. }
  5867. // Moving window to front of display and set focus (which happens to be back of our sorted list)
  5868. void ImGui::FocusWindow(ImGuiWindow* window)
  5869. {
  5870. ImGuiContext& g = *GImGui;
  5871. if (g.NavWindow != window)
  5872. {
  5873. g.NavWindow = window;
  5874. if (window && g.NavDisableMouseHover)
  5875. g.NavMousePosDirty = true;
  5876. g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
  5877. g.NavFocusScopeId = 0;
  5878. g.NavIdIsAlive = false;
  5879. g.NavLayer = ImGuiNavLayer_Main;
  5880. g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
  5881. NavUpdateAnyRequestFlag();
  5882. //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
  5883. }
  5884. // Close popups if any
  5885. ClosePopupsOverWindow(window, false);
  5886. // Move the root window to the top of the pile
  5887. IM_ASSERT(window == NULL || window->RootWindow != NULL);
  5888. ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
  5889. ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
  5890. // Steal active widgets. Some of the cases it triggers includes:
  5891. // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
  5892. // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
  5893. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
  5894. if (!g.ActiveIdNoClearOnFocusLoss)
  5895. ClearActiveID();
  5896. // Passing NULL allow to disable keyboard focus
  5897. if (!window)
  5898. return;
  5899. // Bring to front
  5900. BringWindowToFocusFront(focus_front_window);
  5901. if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
  5902. BringWindowToDisplayFront(display_front_window);
  5903. }
  5904. void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
  5905. {
  5906. ImGuiContext& g = *GImGui;
  5907. int start_idx = g.WindowsFocusOrder.Size - 1;
  5908. if (under_this_window != NULL)
  5909. {
  5910. // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
  5911. int offset = -1;
  5912. while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
  5913. {
  5914. under_this_window = under_this_window->ParentWindow;
  5915. offset = 0;
  5916. }
  5917. start_idx = FindWindowFocusIndex(under_this_window) + offset;
  5918. }
  5919. for (int i = start_idx; i >= 0; i--)
  5920. {
  5921. // 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.
  5922. ImGuiWindow* window = g.WindowsFocusOrder[i];
  5923. IM_ASSERT(window == window->RootWindow);
  5924. if (window != ignore_window && window->WasActive)
  5925. if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
  5926. {
  5927. ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
  5928. FocusWindow(focus_window);
  5929. return;
  5930. }
  5931. }
  5932. FocusWindow(NULL);
  5933. }
  5934. // Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
  5935. void ImGui::SetCurrentFont(ImFont* font)
  5936. {
  5937. ImGuiContext& g = *GImGui;
  5938. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  5939. IM_ASSERT(font->Scale > 0.0f);
  5940. g.Font = font;
  5941. g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
  5942. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  5943. ImFontAtlas* atlas = g.Font->ContainerAtlas;
  5944. g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
  5945. g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
  5946. g.DrawListSharedData.Font = g.Font;
  5947. g.DrawListSharedData.FontSize = g.FontSize;
  5948. }
  5949. void ImGui::PushFont(ImFont* font)
  5950. {
  5951. ImGuiContext& g = *GImGui;
  5952. if (!font)
  5953. font = GetDefaultFont();
  5954. SetCurrentFont(font);
  5955. g.FontStack.push_back(font);
  5956. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  5957. }
  5958. void ImGui::PopFont()
  5959. {
  5960. ImGuiContext& g = *GImGui;
  5961. g.CurrentWindow->DrawList->PopTextureID();
  5962. g.FontStack.pop_back();
  5963. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  5964. }
  5965. void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
  5966. {
  5967. ImGuiContext& g = *GImGui;
  5968. ImGuiItemFlags item_flags = g.CurrentItemFlags;
  5969. IM_ASSERT(item_flags == g.ItemFlagsStack.back());
  5970. if (enabled)
  5971. item_flags |= option;
  5972. else
  5973. item_flags &= ~option;
  5974. g.CurrentItemFlags = item_flags;
  5975. g.ItemFlagsStack.push_back(item_flags);
  5976. }
  5977. void ImGui::PopItemFlag()
  5978. {
  5979. ImGuiContext& g = *GImGui;
  5980. IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
  5981. g.ItemFlagsStack.pop_back();
  5982. g.CurrentItemFlags = g.ItemFlagsStack.back();
  5983. }
  5984. // BeginDisabled()/EndDisabled()
  5985. // - 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)
  5986. // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
  5987. // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
  5988. // - 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.
  5989. // - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
  5990. void ImGui::BeginDisabled(bool disabled)
  5991. {
  5992. ImGuiContext& g = *GImGui;
  5993. bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
  5994. if (!was_disabled && disabled)
  5995. {
  5996. g.DisabledAlphaBackup = g.Style.Alpha;
  5997. g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
  5998. }
  5999. if (was_disabled || disabled)
  6000. g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
  6001. g.ItemFlagsStack.push_back(g.CurrentItemFlags);
  6002. g.DisabledStackSize++;
  6003. }
  6004. void ImGui::EndDisabled()
  6005. {
  6006. ImGuiContext& g = *GImGui;
  6007. IM_ASSERT(g.DisabledStackSize > 0);
  6008. g.DisabledStackSize--;
  6009. bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
  6010. //PopItemFlag();
  6011. g.ItemFlagsStack.pop_back();
  6012. g.CurrentItemFlags = g.ItemFlagsStack.back();
  6013. if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
  6014. g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
  6015. }
  6016. // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
  6017. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  6018. {
  6019. PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
  6020. }
  6021. void ImGui::PopAllowKeyboardFocus()
  6022. {
  6023. PopItemFlag();
  6024. }
  6025. void ImGui::PushButtonRepeat(bool repeat)
  6026. {
  6027. PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
  6028. }
  6029. void ImGui::PopButtonRepeat()
  6030. {
  6031. PopItemFlag();
  6032. }
  6033. void ImGui::PushTextWrapPos(float wrap_pos_x)
  6034. {
  6035. ImGuiWindow* window = GetCurrentWindow();
  6036. window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
  6037. window->DC.TextWrapPos = wrap_pos_x;
  6038. }
  6039. void ImGui::PopTextWrapPos()
  6040. {
  6041. ImGuiWindow* window = GetCurrentWindow();
  6042. window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
  6043. window->DC.TextWrapPosStack.pop_back();
  6044. }
  6045. static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy)
  6046. {
  6047. ImGuiWindow* last_window = NULL;
  6048. while (last_window != window)
  6049. {
  6050. last_window = window;
  6051. window = window->RootWindow;
  6052. if (popup_hierarchy)
  6053. window = window->RootWindowPopupTree;
  6054. }
  6055. return window;
  6056. }
  6057. bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy)
  6058. {
  6059. ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy);
  6060. if (window_root == potential_parent)
  6061. return true;
  6062. while (window != NULL)
  6063. {
  6064. if (window == potential_parent)
  6065. return true;
  6066. if (window == window_root) // end of chain
  6067. return false;
  6068. window = window->ParentWindow;
  6069. }
  6070. return false;
  6071. }
  6072. bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
  6073. {
  6074. if (window->RootWindow == potential_parent)
  6075. return true;
  6076. while (window != NULL)
  6077. {
  6078. if (window == potential_parent)
  6079. return true;
  6080. window = window->ParentWindowInBeginStack;
  6081. }
  6082. return false;
  6083. }
  6084. bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
  6085. {
  6086. ImGuiContext& g = *GImGui;
  6087. // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
  6088. const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
  6089. if (display_layer_delta != 0)
  6090. return display_layer_delta > 0;
  6091. for (int i = g.Windows.Size - 1; i >= 0; i--)
  6092. {
  6093. ImGuiWindow* candidate_window = g.Windows[i];
  6094. if (candidate_window == potential_above)
  6095. return true;
  6096. if (candidate_window == potential_below)
  6097. return false;
  6098. }
  6099. return false;
  6100. }
  6101. bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
  6102. {
  6103. IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0); // Flags not supported by this function
  6104. ImGuiContext& g = *GImGui;
  6105. ImGuiWindow* ref_window = g.HoveredWindow;
  6106. ImGuiWindow* cur_window = g.CurrentWindow;
  6107. if (ref_window == NULL)
  6108. return false;
  6109. if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
  6110. {
  6111. IM_ASSERT(cur_window); // Not inside a Begin()/End()
  6112. const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
  6113. if (flags & ImGuiHoveredFlags_RootWindow)
  6114. cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
  6115. bool result;
  6116. if (flags & ImGuiHoveredFlags_ChildWindows)
  6117. result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
  6118. else
  6119. result = (ref_window == cur_window);
  6120. if (!result)
  6121. return false;
  6122. }
  6123. if (!IsWindowContentHoverable(ref_window, flags))
  6124. return false;
  6125. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  6126. if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
  6127. return false;
  6128. return true;
  6129. }
  6130. bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
  6131. {
  6132. ImGuiContext& g = *GImGui;
  6133. ImGuiWindow* ref_window = g.NavWindow;
  6134. ImGuiWindow* cur_window = g.CurrentWindow;
  6135. if (ref_window == NULL)
  6136. return false;
  6137. if (flags & ImGuiFocusedFlags_AnyWindow)
  6138. return true;
  6139. IM_ASSERT(cur_window); // Not inside a Begin()/End()
  6140. const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
  6141. if (flags & ImGuiHoveredFlags_RootWindow)
  6142. cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
  6143. if (flags & ImGuiHoveredFlags_ChildWindows)
  6144. return IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
  6145. else
  6146. return (ref_window == cur_window);
  6147. }
  6148. // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
  6149. // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
  6150. // If you want a window to never be focused, you may use the e.g. NoInputs flag.
  6151. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
  6152. {
  6153. return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
  6154. }
  6155. float ImGui::GetWindowWidth()
  6156. {
  6157. ImGuiWindow* window = GImGui->CurrentWindow;
  6158. return window->Size.x;
  6159. }
  6160. float ImGui::GetWindowHeight()
  6161. {
  6162. ImGuiWindow* window = GImGui->CurrentWindow;
  6163. return window->Size.y;
  6164. }
  6165. ImVec2 ImGui::GetWindowPos()
  6166. {
  6167. ImGuiContext& g = *GImGui;
  6168. ImGuiWindow* window = g.CurrentWindow;
  6169. return window->Pos;
  6170. }
  6171. void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  6172. {
  6173. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6174. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  6175. return;
  6176. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6177. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6178. window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
  6179. // Set
  6180. const ImVec2 old_pos = window->Pos;
  6181. window->Pos = ImFloor(pos);
  6182. ImVec2 offset = window->Pos - old_pos;
  6183. window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
  6184. window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
  6185. window->DC.IdealMaxPos += offset;
  6186. window->DC.CursorStartPos += offset;
  6187. }
  6188. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  6189. {
  6190. ImGuiWindow* window = GetCurrentWindowRead();
  6191. SetWindowPos(window, pos, cond);
  6192. }
  6193. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  6194. {
  6195. if (ImGuiWindow* window = FindWindowByName(name))
  6196. SetWindowPos(window, pos, cond);
  6197. }
  6198. ImVec2 ImGui::GetWindowSize()
  6199. {
  6200. ImGuiWindow* window = GetCurrentWindowRead();
  6201. return window->Size;
  6202. }
  6203. void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  6204. {
  6205. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6206. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  6207. return;
  6208. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6209. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6210. // Set
  6211. if (size.x > 0.0f)
  6212. {
  6213. window->AutoFitFramesX = 0;
  6214. window->SizeFull.x = IM_FLOOR(size.x);
  6215. }
  6216. else
  6217. {
  6218. window->AutoFitFramesX = 2;
  6219. window->AutoFitOnlyGrows = false;
  6220. }
  6221. if (size.y > 0.0f)
  6222. {
  6223. window->AutoFitFramesY = 0;
  6224. window->SizeFull.y = IM_FLOOR(size.y);
  6225. }
  6226. else
  6227. {
  6228. window->AutoFitFramesY = 2;
  6229. window->AutoFitOnlyGrows = false;
  6230. }
  6231. }
  6232. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  6233. {
  6234. SetWindowSize(GImGui->CurrentWindow, size, cond);
  6235. }
  6236. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  6237. {
  6238. if (ImGuiWindow* window = FindWindowByName(name))
  6239. SetWindowSize(window, size, cond);
  6240. }
  6241. void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  6242. {
  6243. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6244. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  6245. return;
  6246. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6247. // Set
  6248. window->Collapsed = collapsed;
  6249. }
  6250. void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
  6251. {
  6252. IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
  6253. window->HitTestHoleSize = ImVec2ih(size);
  6254. window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
  6255. }
  6256. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  6257. {
  6258. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  6259. }
  6260. bool ImGui::IsWindowCollapsed()
  6261. {
  6262. ImGuiWindow* window = GetCurrentWindowRead();
  6263. return window->Collapsed;
  6264. }
  6265. bool ImGui::IsWindowAppearing()
  6266. {
  6267. ImGuiWindow* window = GetCurrentWindowRead();
  6268. return window->Appearing;
  6269. }
  6270. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  6271. {
  6272. if (ImGuiWindow* window = FindWindowByName(name))
  6273. SetWindowCollapsed(window, collapsed, cond);
  6274. }
  6275. void ImGui::SetWindowFocus()
  6276. {
  6277. FocusWindow(GImGui->CurrentWindow);
  6278. }
  6279. void ImGui::SetWindowFocus(const char* name)
  6280. {
  6281. if (name)
  6282. {
  6283. if (ImGuiWindow* window = FindWindowByName(name))
  6284. FocusWindow(window);
  6285. }
  6286. else
  6287. {
  6288. FocusWindow(NULL);
  6289. }
  6290. }
  6291. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
  6292. {
  6293. ImGuiContext& g = *GImGui;
  6294. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6295. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
  6296. g.NextWindowData.PosVal = pos;
  6297. g.NextWindowData.PosPivotVal = pivot;
  6298. g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
  6299. }
  6300. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  6301. {
  6302. ImGuiContext& g = *GImGui;
  6303. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6304. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
  6305. g.NextWindowData.SizeVal = size;
  6306. g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
  6307. }
  6308. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
  6309. {
  6310. ImGuiContext& g = *GImGui;
  6311. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
  6312. g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
  6313. g.NextWindowData.SizeCallback = custom_callback;
  6314. g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
  6315. }
  6316. // Content size = inner scrollable rectangle, padded with WindowPadding.
  6317. // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
  6318. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  6319. {
  6320. ImGuiContext& g = *GImGui;
  6321. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
  6322. g.NextWindowData.ContentSizeVal = ImFloor(size);
  6323. }
  6324. void ImGui::SetNextWindowScroll(const ImVec2& scroll)
  6325. {
  6326. ImGuiContext& g = *GImGui;
  6327. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
  6328. g.NextWindowData.ScrollVal = scroll;
  6329. }
  6330. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  6331. {
  6332. ImGuiContext& g = *GImGui;
  6333. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6334. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
  6335. g.NextWindowData.CollapsedVal = collapsed;
  6336. g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
  6337. }
  6338. void ImGui::SetNextWindowFocus()
  6339. {
  6340. ImGuiContext& g = *GImGui;
  6341. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
  6342. }
  6343. void ImGui::SetNextWindowBgAlpha(float alpha)
  6344. {
  6345. ImGuiContext& g = *GImGui;
  6346. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
  6347. g.NextWindowData.BgAlphaVal = alpha;
  6348. }
  6349. ImDrawList* ImGui::GetWindowDrawList()
  6350. {
  6351. ImGuiWindow* window = GetCurrentWindow();
  6352. return window->DrawList;
  6353. }
  6354. ImFont* ImGui::GetFont()
  6355. {
  6356. return GImGui->Font;
  6357. }
  6358. float ImGui::GetFontSize()
  6359. {
  6360. return GImGui->FontSize;
  6361. }
  6362. ImVec2 ImGui::GetFontTexUvWhitePixel()
  6363. {
  6364. return GImGui->DrawListSharedData.TexUvWhitePixel;
  6365. }
  6366. void ImGui::SetWindowFontScale(float scale)
  6367. {
  6368. IM_ASSERT(scale > 0.0f);
  6369. ImGuiContext& g = *GImGui;
  6370. ImGuiWindow* window = GetCurrentWindow();
  6371. window->FontWindowScale = scale;
  6372. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  6373. }
  6374. void ImGui::ActivateItem(ImGuiID id)
  6375. {
  6376. ImGuiContext& g = *GImGui;
  6377. g.NavNextActivateId = id;
  6378. g.NavNextActivateFlags = ImGuiActivateFlags_None;
  6379. }
  6380. void ImGui::PushFocusScope(ImGuiID id)
  6381. {
  6382. ImGuiContext& g = *GImGui;
  6383. ImGuiWindow* window = g.CurrentWindow;
  6384. g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent);
  6385. window->DC.NavFocusScopeIdCurrent = id;
  6386. }
  6387. void ImGui::PopFocusScope()
  6388. {
  6389. ImGuiContext& g = *GImGui;
  6390. ImGuiWindow* window = g.CurrentWindow;
  6391. IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
  6392. window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back();
  6393. g.FocusScopeStack.pop_back();
  6394. }
  6395. void ImGui::SetKeyboardFocusHere(int offset)
  6396. {
  6397. ImGuiContext& g = *GImGui;
  6398. ImGuiWindow* window = g.CurrentWindow;
  6399. IM_ASSERT(offset >= -1); // -1 is allowed but not below
  6400. g.NavWindow = window;
  6401. ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
  6402. NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
  6403. if (offset == -1)
  6404. {
  6405. NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
  6406. }
  6407. else
  6408. {
  6409. g.NavTabbingDir = 1;
  6410. g.NavTabbingCounter = offset + 1;
  6411. }
  6412. }
  6413. void ImGui::SetItemDefaultFocus()
  6414. {
  6415. ImGuiContext& g = *GImGui;
  6416. ImGuiWindow* window = g.CurrentWindow;
  6417. if (!window->Appearing)
  6418. return;
  6419. if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
  6420. return;
  6421. g.NavInitRequest = false;
  6422. g.NavInitResultId = g.LastItemData.ID;
  6423. g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
  6424. NavUpdateAnyRequestFlag();
  6425. // Scroll could be done in NavInitRequestApplyResult() via a opt-in flag (we however don't want regular init requests to scroll)
  6426. if (!IsItemVisible())
  6427. ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
  6428. }
  6429. void ImGui::SetStateStorage(ImGuiStorage* tree)
  6430. {
  6431. ImGuiWindow* window = GImGui->CurrentWindow;
  6432. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  6433. }
  6434. ImGuiStorage* ImGui::GetStateStorage()
  6435. {
  6436. ImGuiWindow* window = GImGui->CurrentWindow;
  6437. return window->DC.StateStorage;
  6438. }
  6439. void ImGui::PushID(const char* str_id)
  6440. {
  6441. ImGuiContext& g = *GImGui;
  6442. ImGuiWindow* window = g.CurrentWindow;
  6443. ImGuiID id = window->GetIDNoKeepAlive(str_id);
  6444. window->IDStack.push_back(id);
  6445. }
  6446. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  6447. {
  6448. ImGuiContext& g = *GImGui;
  6449. ImGuiWindow* window = g.CurrentWindow;
  6450. ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end);
  6451. window->IDStack.push_back(id);
  6452. }
  6453. void ImGui::PushID(const void* ptr_id)
  6454. {
  6455. ImGuiContext& g = *GImGui;
  6456. ImGuiWindow* window = g.CurrentWindow;
  6457. ImGuiID id = window->GetIDNoKeepAlive(ptr_id);
  6458. window->IDStack.push_back(id);
  6459. }
  6460. void ImGui::PushID(int int_id)
  6461. {
  6462. ImGuiContext& g = *GImGui;
  6463. ImGuiWindow* window = g.CurrentWindow;
  6464. ImGuiID id = window->GetIDNoKeepAlive(int_id);
  6465. window->IDStack.push_back(id);
  6466. }
  6467. // Push a given id value ignoring the ID stack as a seed.
  6468. void ImGui::PushOverrideID(ImGuiID id)
  6469. {
  6470. ImGuiContext& g = *GImGui;
  6471. ImGuiWindow* window = g.CurrentWindow;
  6472. if (g.DebugHookIdInfo == id)
  6473. DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
  6474. window->IDStack.push_back(id);
  6475. }
  6476. // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
  6477. // (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
  6478. // for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
  6479. ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
  6480. {
  6481. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  6482. KeepAliveID(id);
  6483. ImGuiContext& g = *GImGui;
  6484. if (g.DebugHookIdInfo == id)
  6485. DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
  6486. return id;
  6487. }
  6488. void ImGui::PopID()
  6489. {
  6490. ImGuiWindow* window = GImGui->CurrentWindow;
  6491. IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
  6492. window->IDStack.pop_back();
  6493. }
  6494. ImGuiID ImGui::GetID(const char* str_id)
  6495. {
  6496. ImGuiWindow* window = GImGui->CurrentWindow;
  6497. return window->GetID(str_id);
  6498. }
  6499. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  6500. {
  6501. ImGuiWindow* window = GImGui->CurrentWindow;
  6502. return window->GetID(str_id_begin, str_id_end);
  6503. }
  6504. ImGuiID ImGui::GetID(const void* ptr_id)
  6505. {
  6506. ImGuiWindow* window = GImGui->CurrentWindow;
  6507. return window->GetID(ptr_id);
  6508. }
  6509. bool ImGui::IsRectVisible(const ImVec2& size)
  6510. {
  6511. ImGuiWindow* window = GImGui->CurrentWindow;
  6512. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  6513. }
  6514. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  6515. {
  6516. ImGuiWindow* window = GImGui->CurrentWindow;
  6517. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  6518. }
  6519. //-----------------------------------------------------------------------------
  6520. // [SECTION] INPUTS
  6521. //-----------------------------------------------------------------------------
  6522. // Test if mouse cursor is hovering given rectangle
  6523. // NB- Rectangle is clipped by our current clip setting
  6524. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  6525. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  6526. {
  6527. ImGuiContext& g = *GImGui;
  6528. // Clip
  6529. ImRect rect_clipped(r_min, r_max);
  6530. if (clip)
  6531. rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
  6532. // Expand for touch input
  6533. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  6534. if (!rect_for_touch.Contains(g.IO.MousePos))
  6535. return false;
  6536. return true;
  6537. }
  6538. const ImGuiKeyData* ImGui::GetKeyData(ImGuiKey key)
  6539. {
  6540. ImGuiContext& g = *GImGui;
  6541. int index;
  6542. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  6543. IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
  6544. if (IsLegacyKey(key))
  6545. index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native
  6546. else
  6547. index = key;
  6548. #else
  6549. IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
  6550. index = key - ImGuiKey_NamedKey_BEGIN;
  6551. #endif
  6552. return &g.IO.KeysData[index];
  6553. }
  6554. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  6555. int ImGui::GetKeyIndex(ImGuiKey key)
  6556. {
  6557. ImGuiContext& g = *GImGui;
  6558. IM_ASSERT(IsNamedKey(key));
  6559. const ImGuiKeyData* key_data = GetKeyData(key);
  6560. return (int)(key_data - g.IO.KeysData);
  6561. }
  6562. #endif
  6563. // Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
  6564. static const char* const GKeyNames[] =
  6565. {
  6566. "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
  6567. "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
  6568. "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
  6569. "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
  6570. "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
  6571. "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
  6572. "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual", "LeftShift", "LeftControl",
  6573. "LeftAlt", "LeftSuper", "RightShift", "RightControl", "RightAlt", "RightSuper", "Menu",
  6574. "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
  6575. "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
  6576. "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"
  6577. };
  6578. IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
  6579. const char* ImGui::GetKeyName(ImGuiKey key)
  6580. {
  6581. #ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
  6582. IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
  6583. #else
  6584. if (IsLegacyKey(key))
  6585. {
  6586. ImGuiIO& io = GetIO();
  6587. if (io.KeyMap[key] == -1)
  6588. return "N/A";
  6589. IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key]));
  6590. key = (ImGuiKey)io.KeyMap[key];
  6591. }
  6592. #endif
  6593. if (key == ImGuiKey_None)
  6594. return "None";
  6595. return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
  6596. }
  6597. // Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
  6598. // Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
  6599. bool ImGui::IsKeyDown(ImGuiKey key)
  6600. {
  6601. const ImGuiKeyData* key_data = GetKeyData(key);
  6602. return key_data->Down;
  6603. }
  6604. // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
  6605. // t1 = current time (e.g.: g.Time)
  6606. // An event is triggered at:
  6607. // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
  6608. int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
  6609. {
  6610. if (t1 == 0.0f)
  6611. return 1;
  6612. if (t0 >= t1)
  6613. return 0;
  6614. if (repeat_rate <= 0.0f)
  6615. return (t0 < repeat_delay) && (t1 >= repeat_delay);
  6616. const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
  6617. const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
  6618. const int count = count_t1 - count_t0;
  6619. return count;
  6620. }
  6621. int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
  6622. {
  6623. ImGuiContext& g = *GImGui;
  6624. const ImGuiKeyData* key_data = GetKeyData(key);
  6625. const float t = key_data->DownDuration;
  6626. return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
  6627. }
  6628. bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
  6629. {
  6630. ImGuiContext& g = *GImGui;
  6631. const ImGuiKeyData* key_data = GetKeyData(key);
  6632. const float t = key_data->DownDuration;
  6633. if (t == 0.0f)
  6634. return true;
  6635. if (repeat && t > g.IO.KeyRepeatDelay)
  6636. return GetKeyPressedAmount(key, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  6637. return false;
  6638. }
  6639. bool ImGui::IsKeyReleased(ImGuiKey key)
  6640. {
  6641. const ImGuiKeyData* key_data = GetKeyData(key);
  6642. return key_data->DownDurationPrev >= 0.0f && !key_data->Down;
  6643. }
  6644. bool ImGui::IsMouseDown(ImGuiMouseButton button)
  6645. {
  6646. ImGuiContext& g = *GImGui;
  6647. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6648. return g.IO.MouseDown[button];
  6649. }
  6650. bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
  6651. {
  6652. ImGuiContext& g = *GImGui;
  6653. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6654. const float t = g.IO.MouseDownDuration[button];
  6655. if (t == 0.0f)
  6656. return true;
  6657. if (repeat && t > g.IO.KeyRepeatDelay)
  6658. {
  6659. // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
  6660. int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
  6661. if (amount > 0)
  6662. return true;
  6663. }
  6664. return false;
  6665. }
  6666. bool ImGui::IsMouseReleased(ImGuiMouseButton button)
  6667. {
  6668. ImGuiContext& g = *GImGui;
  6669. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6670. return g.IO.MouseReleased[button];
  6671. }
  6672. bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
  6673. {
  6674. ImGuiContext& g = *GImGui;
  6675. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6676. return g.IO.MouseClickedCount[button] == 2;
  6677. }
  6678. int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
  6679. {
  6680. ImGuiContext& g = *GImGui;
  6681. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6682. return g.IO.MouseClickedCount[button];
  6683. }
  6684. // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
  6685. // [Internal] This doesn't test if the button is pressed
  6686. bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
  6687. {
  6688. ImGuiContext& g = *GImGui;
  6689. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6690. if (lock_threshold < 0.0f)
  6691. lock_threshold = g.IO.MouseDragThreshold;
  6692. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  6693. }
  6694. bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
  6695. {
  6696. ImGuiContext& g = *GImGui;
  6697. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6698. if (!g.IO.MouseDown[button])
  6699. return false;
  6700. return IsMouseDragPastThreshold(button, lock_threshold);
  6701. }
  6702. ImVec2 ImGui::GetMousePos()
  6703. {
  6704. ImGuiContext& g = *GImGui;
  6705. return g.IO.MousePos;
  6706. }
  6707. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  6708. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  6709. {
  6710. ImGuiContext& g = *GImGui;
  6711. if (g.BeginPopupStack.Size > 0)
  6712. return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
  6713. return g.IO.MousePos;
  6714. }
  6715. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
  6716. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  6717. {
  6718. // The assert is only to silence a false-positive in XCode Static Analysis.
  6719. // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
  6720. IM_ASSERT(GImGui != NULL);
  6721. const float MOUSE_INVALID = -256000.0f;
  6722. ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
  6723. return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
  6724. }
  6725. bool ImGui::IsAnyMouseDown()
  6726. {
  6727. ImGuiContext& g = *GImGui;
  6728. for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
  6729. if (g.IO.MouseDown[n])
  6730. return true;
  6731. return false;
  6732. }
  6733. // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
  6734. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
  6735. // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
  6736. ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
  6737. {
  6738. ImGuiContext& g = *GImGui;
  6739. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6740. if (lock_threshold < 0.0f)
  6741. lock_threshold = g.IO.MouseDragThreshold;
  6742. if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
  6743. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  6744. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
  6745. return g.IO.MousePos - g.IO.MouseClickedPos[button];
  6746. return ImVec2(0.0f, 0.0f);
  6747. }
  6748. void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
  6749. {
  6750. ImGuiContext& g = *GImGui;
  6751. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  6752. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  6753. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  6754. }
  6755. ImGuiMouseCursor ImGui::GetMouseCursor()
  6756. {
  6757. ImGuiContext& g = *GImGui;
  6758. return g.MouseCursor;
  6759. }
  6760. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  6761. {
  6762. ImGuiContext& g = *GImGui;
  6763. g.MouseCursor = cursor_type;
  6764. }
  6765. void ImGui::CaptureKeyboardFromApp(bool capture)
  6766. {
  6767. ImGuiContext& g = *GImGui;
  6768. g.WantCaptureKeyboardNextFrame = capture ? 1 : 0;
  6769. }
  6770. void ImGui::CaptureMouseFromApp(bool capture)
  6771. {
  6772. ImGuiContext& g = *GImGui;
  6773. g.WantCaptureMouseNextFrame = capture ? 1 : 0;
  6774. }
  6775. //-----------------------------------------------------------------------------
  6776. // [SECTION] ERROR CHECKING
  6777. //-----------------------------------------------------------------------------
  6778. // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
  6779. // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
  6780. // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
  6781. // may see different structures than what imgui.cpp sees, which is problematic.
  6782. // We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
  6783. bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
  6784. {
  6785. bool error = false;
  6786. if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
  6787. if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
  6788. if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
  6789. if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
  6790. if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
  6791. if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
  6792. if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
  6793. return !error;
  6794. }
  6795. static void ImGui::ErrorCheckNewFrameSanityChecks()
  6796. {
  6797. ImGuiContext& g = *GImGui;
  6798. // Check user IM_ASSERT macro
  6799. // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
  6800. // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
  6801. // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
  6802. // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
  6803. // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
  6804. if (true) IM_ASSERT(1); else IM_ASSERT(0);
  6805. // Check user data
  6806. // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
  6807. IM_ASSERT(g.Initialized);
  6808. IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
  6809. IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
  6810. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
  6811. 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()");
  6812. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
  6813. IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
  6814. 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
  6815. IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
  6816. IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
  6817. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  6818. for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
  6819. IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
  6820. // 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)
  6821. if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
  6822. IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
  6823. #endif
  6824. // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
  6825. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
  6826. g.IO.ConfigWindowsResizeFromEdges = false;
  6827. }
  6828. static void ImGui::ErrorCheckEndFrameSanityChecks()
  6829. {
  6830. ImGuiContext& g = *GImGui;
  6831. // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
  6832. // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
  6833. // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
  6834. // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
  6835. // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
  6836. // while still correctly asserting on mid-frame key press events.
  6837. const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags();
  6838. IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
  6839. IM_UNUSED(key_mod_flags);
  6840. // Recover from errors
  6841. //ErrorCheckEndFrameRecover();
  6842. // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
  6843. // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
  6844. if (g.CurrentWindowStack.Size != 1)
  6845. {
  6846. if (g.CurrentWindowStack.Size > 1)
  6847. {
  6848. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
  6849. while (g.CurrentWindowStack.Size > 1)
  6850. End();
  6851. }
  6852. else
  6853. {
  6854. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
  6855. }
  6856. }
  6857. IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
  6858. }
  6859. // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
  6860. // Must be called during or before EndFrame().
  6861. // This is generally flawed as we are not necessarily End/Popping things in the right order.
  6862. // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
  6863. // FIXME: Can't recover from interleaved BeginTabBar/Begin
  6864. void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
  6865. {
  6866. // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
  6867. ImGuiContext& g = *GImGui;
  6868. while (g.CurrentWindowStack.Size > 0) //-V1044
  6869. {
  6870. ErrorCheckEndWindowRecover(log_callback, user_data);
  6871. ImGuiWindow* window = g.CurrentWindow;
  6872. if (g.CurrentWindowStack.Size == 1)
  6873. {
  6874. IM_ASSERT(window->IsFallbackWindow);
  6875. break;
  6876. }
  6877. IM_ASSERT(window == g.CurrentWindow);
  6878. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  6879. {
  6880. if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
  6881. EndChild();
  6882. }
  6883. else
  6884. {
  6885. if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
  6886. End();
  6887. }
  6888. }
  6889. }
  6890. // Must be called before End()/EndChild()
  6891. void ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
  6892. {
  6893. ImGuiContext& g = *GImGui;
  6894. while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
  6895. {
  6896. if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
  6897. EndTable();
  6898. }
  6899. ImGuiWindow* window = g.CurrentWindow;
  6900. ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
  6901. IM_ASSERT(window != NULL);
  6902. while (g.CurrentTabBar != NULL) //-V1044
  6903. {
  6904. if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
  6905. EndTabBar();
  6906. }
  6907. while (window->DC.TreeDepth > 0)
  6908. {
  6909. if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
  6910. TreePop();
  6911. }
  6912. while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
  6913. {
  6914. if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
  6915. EndGroup();
  6916. }
  6917. while (window->IDStack.Size > 1)
  6918. {
  6919. if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
  6920. PopID();
  6921. }
  6922. while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
  6923. {
  6924. if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
  6925. EndDisabled();
  6926. }
  6927. while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
  6928. {
  6929. if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
  6930. PopStyleColor();
  6931. }
  6932. while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
  6933. {
  6934. if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
  6935. PopItemFlag();
  6936. }
  6937. while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
  6938. {
  6939. if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
  6940. PopStyleVar();
  6941. }
  6942. while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack) //-V1044
  6943. {
  6944. if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
  6945. PopFocusScope();
  6946. }
  6947. }
  6948. // Save current stack sizes for later compare
  6949. void ImGuiStackSizes::SetToCurrentState()
  6950. {
  6951. ImGuiContext& g = *GImGui;
  6952. ImGuiWindow* window = g.CurrentWindow;
  6953. SizeOfIDStack = (short)window->IDStack.Size;
  6954. SizeOfColorStack = (short)g.ColorStack.Size;
  6955. SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
  6956. SizeOfFontStack = (short)g.FontStack.Size;
  6957. SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
  6958. SizeOfGroupStack = (short)g.GroupStack.Size;
  6959. SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
  6960. SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
  6961. SizeOfDisabledStack = (short)g.DisabledStackSize;
  6962. }
  6963. // Compare to detect usage errors
  6964. void ImGuiStackSizes::CompareWithCurrentState()
  6965. {
  6966. ImGuiContext& g = *GImGui;
  6967. ImGuiWindow* window = g.CurrentWindow;
  6968. IM_UNUSED(window);
  6969. // Window stacks
  6970. // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
  6971. IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
  6972. // Global stacks
  6973. // 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.
  6974. IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
  6975. IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
  6976. IM_ASSERT(SizeOfDisabledStack == g.DisabledStackSize && "BeginDisabled/EndDisabled Mismatch!");
  6977. IM_ASSERT(SizeOfItemFlagsStack >= g.ItemFlagsStack.Size && "PushItemFlag/PopItemFlag Mismatch!");
  6978. IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
  6979. IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
  6980. IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
  6981. IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
  6982. }
  6983. //-----------------------------------------------------------------------------
  6984. // [SECTION] LAYOUT
  6985. //-----------------------------------------------------------------------------
  6986. // - ItemSize()
  6987. // - ItemAdd()
  6988. // - SameLine()
  6989. // - GetCursorScreenPos()
  6990. // - SetCursorScreenPos()
  6991. // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
  6992. // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
  6993. // - GetCursorStartPos()
  6994. // - Indent()
  6995. // - Unindent()
  6996. // - SetNextItemWidth()
  6997. // - PushItemWidth()
  6998. // - PushMultiItemsWidths()
  6999. // - PopItemWidth()
  7000. // - CalcItemWidth()
  7001. // - CalcItemSize()
  7002. // - GetTextLineHeight()
  7003. // - GetTextLineHeightWithSpacing()
  7004. // - GetFrameHeight()
  7005. // - GetFrameHeightWithSpacing()
  7006. // - GetContentRegionMax()
  7007. // - GetContentRegionMaxAbs() [Internal]
  7008. // - GetContentRegionAvail(),
  7009. // - GetWindowContentRegionMin(), GetWindowContentRegionMax()
  7010. // - BeginGroup()
  7011. // - EndGroup()
  7012. // Also see in imgui_widgets: tab bars, columns.
  7013. //-----------------------------------------------------------------------------
  7014. // Advance cursor given item size for layout.
  7015. // Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
  7016. // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
  7017. void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
  7018. {
  7019. ImGuiContext& g = *GImGui;
  7020. ImGuiWindow* window = g.CurrentWindow;
  7021. if (window->SkipItems)
  7022. return;
  7023. // We increase the height in this function to accommodate for baseline offset.
  7024. // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
  7025. // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
  7026. const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
  7027. const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
  7028. // Always align ourselves on pixel boundaries
  7029. //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
  7030. window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
  7031. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
  7032. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
  7033. window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
  7034. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  7035. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
  7036. //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
  7037. window->DC.PrevLineSize.y = line_height;
  7038. window->DC.CurrLineSize.y = 0.0f;
  7039. window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
  7040. window->DC.CurrLineTextBaseOffset = 0.0f;
  7041. // Horizontal layout mode
  7042. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  7043. SameLine();
  7044. }
  7045. void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
  7046. {
  7047. ItemSize(bb.GetSize(), text_baseline_y);
  7048. }
  7049. // Declare item bounding box for clipping and interaction.
  7050. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  7051. // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
  7052. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
  7053. {
  7054. ImGuiContext& g = *GImGui;
  7055. ImGuiWindow* window = g.CurrentWindow;
  7056. // Set item data
  7057. // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
  7058. g.LastItemData.ID = id;
  7059. g.LastItemData.Rect = bb;
  7060. g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
  7061. g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
  7062. g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
  7063. // Directional navigation processing
  7064. if (id != 0)
  7065. {
  7066. // Runs prior to clipping early-out
  7067. // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
  7068. // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
  7069. // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
  7070. // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
  7071. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
  7072. // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
  7073. // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
  7074. // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
  7075. window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
  7076. if (g.NavId == id || g.NavAnyRequest)
  7077. if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
  7078. if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
  7079. NavProcessItem();
  7080. // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
  7081. // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
  7082. // READ THE FAQ: https://dearimgui.org/faq
  7083. 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!");
  7084. // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
  7085. #ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
  7086. if (id == g.DebugItemPickerBreakId)
  7087. {
  7088. IM_DEBUG_BREAK();
  7089. g.DebugItemPickerBreakId = 0;
  7090. }
  7091. #endif
  7092. }
  7093. g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
  7094. #ifdef IMGUI_ENABLE_TEST_ENGINE
  7095. if (id != 0)
  7096. IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
  7097. #endif
  7098. // Clipping test
  7099. const bool is_clipped = IsClippedEx(bb, id);
  7100. if (is_clipped)
  7101. return false;
  7102. //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
  7103. // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
  7104. if (IsMouseHoveringRect(bb.Min, bb.Max))
  7105. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
  7106. return true;
  7107. }
  7108. // Gets back to previous line and continue with horizontal layout
  7109. // offset_from_start_x == 0 : follow right after previous item
  7110. // offset_from_start_x != 0 : align to specified x position (relative to window/group left)
  7111. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  7112. // spacing_w >= 0 : enforce spacing amount
  7113. void ImGui::SameLine(float offset_from_start_x, float spacing_w)
  7114. {
  7115. ImGuiWindow* window = GetCurrentWindow();
  7116. if (window->SkipItems)
  7117. return;
  7118. ImGuiContext& g = *GImGui;
  7119. if (offset_from_start_x != 0.0f)
  7120. {
  7121. if (spacing_w < 0.0f) spacing_w = 0.0f;
  7122. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
  7123. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  7124. }
  7125. else
  7126. {
  7127. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  7128. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  7129. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  7130. }
  7131. window->DC.CurrLineSize = window->DC.PrevLineSize;
  7132. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  7133. }
  7134. ImVec2 ImGui::GetCursorScreenPos()
  7135. {
  7136. ImGuiWindow* window = GetCurrentWindowRead();
  7137. return window->DC.CursorPos;
  7138. }
  7139. void ImGui::SetCursorScreenPos(const ImVec2& pos)
  7140. {
  7141. ImGuiWindow* window = GetCurrentWindow();
  7142. window->DC.CursorPos = pos;
  7143. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  7144. }
  7145. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  7146. // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
  7147. ImVec2 ImGui::GetCursorPos()
  7148. {
  7149. ImGuiWindow* window = GetCurrentWindowRead();
  7150. return window->DC.CursorPos - window->Pos + window->Scroll;
  7151. }
  7152. float ImGui::GetCursorPosX()
  7153. {
  7154. ImGuiWindow* window = GetCurrentWindowRead();
  7155. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  7156. }
  7157. float ImGui::GetCursorPosY()
  7158. {
  7159. ImGuiWindow* window = GetCurrentWindowRead();
  7160. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  7161. }
  7162. void ImGui::SetCursorPos(const ImVec2& local_pos)
  7163. {
  7164. ImGuiWindow* window = GetCurrentWindow();
  7165. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  7166. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  7167. }
  7168. void ImGui::SetCursorPosX(float x)
  7169. {
  7170. ImGuiWindow* window = GetCurrentWindow();
  7171. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  7172. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  7173. }
  7174. void ImGui::SetCursorPosY(float y)
  7175. {
  7176. ImGuiWindow* window = GetCurrentWindow();
  7177. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  7178. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  7179. }
  7180. ImVec2 ImGui::GetCursorStartPos()
  7181. {
  7182. ImGuiWindow* window = GetCurrentWindowRead();
  7183. return window->DC.CursorStartPos - window->Pos;
  7184. }
  7185. void ImGui::Indent(float indent_w)
  7186. {
  7187. ImGuiContext& g = *GImGui;
  7188. ImGuiWindow* window = GetCurrentWindow();
  7189. window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  7190. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  7191. }
  7192. void ImGui::Unindent(float indent_w)
  7193. {
  7194. ImGuiContext& g = *GImGui;
  7195. ImGuiWindow* window = GetCurrentWindow();
  7196. window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  7197. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  7198. }
  7199. // Affect large frame+labels widgets only.
  7200. void ImGui::SetNextItemWidth(float item_width)
  7201. {
  7202. ImGuiContext& g = *GImGui;
  7203. g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
  7204. g.NextItemData.Width = item_width;
  7205. }
  7206. // FIXME: Remove the == 0.0f behavior?
  7207. void ImGui::PushItemWidth(float item_width)
  7208. {
  7209. ImGuiContext& g = *GImGui;
  7210. ImGuiWindow* window = g.CurrentWindow;
  7211. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
  7212. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  7213. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  7214. }
  7215. void ImGui::PushMultiItemsWidths(int components, float w_full)
  7216. {
  7217. ImGuiContext& g = *GImGui;
  7218. ImGuiWindow* window = g.CurrentWindow;
  7219. const ImGuiStyle& style = g.Style;
  7220. const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
  7221. const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
  7222. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
  7223. window->DC.ItemWidthStack.push_back(w_item_last);
  7224. for (int i = 0; i < components - 2; i++)
  7225. window->DC.ItemWidthStack.push_back(w_item_one);
  7226. window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
  7227. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  7228. }
  7229. void ImGui::PopItemWidth()
  7230. {
  7231. ImGuiWindow* window = GetCurrentWindow();
  7232. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  7233. window->DC.ItemWidthStack.pop_back();
  7234. }
  7235. // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
  7236. // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
  7237. float ImGui::CalcItemWidth()
  7238. {
  7239. ImGuiContext& g = *GImGui;
  7240. ImGuiWindow* window = g.CurrentWindow;
  7241. float w;
  7242. if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
  7243. w = g.NextItemData.Width;
  7244. else
  7245. w = window->DC.ItemWidth;
  7246. if (w < 0.0f)
  7247. {
  7248. float region_max_x = GetContentRegionMaxAbs().x;
  7249. w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
  7250. }
  7251. w = IM_FLOOR(w);
  7252. return w;
  7253. }
  7254. // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
  7255. // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
  7256. // Note that only CalcItemWidth() is publicly exposed.
  7257. // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
  7258. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
  7259. {
  7260. ImGuiWindow* window = GImGui->CurrentWindow;
  7261. ImVec2 region_max;
  7262. if (size.x < 0.0f || size.y < 0.0f)
  7263. region_max = GetContentRegionMaxAbs();
  7264. if (size.x == 0.0f)
  7265. size.x = default_w;
  7266. else if (size.x < 0.0f)
  7267. size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
  7268. if (size.y == 0.0f)
  7269. size.y = default_h;
  7270. else if (size.y < 0.0f)
  7271. size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
  7272. return size;
  7273. }
  7274. float ImGui::GetTextLineHeight()
  7275. {
  7276. ImGuiContext& g = *GImGui;
  7277. return g.FontSize;
  7278. }
  7279. float ImGui::GetTextLineHeightWithSpacing()
  7280. {
  7281. ImGuiContext& g = *GImGui;
  7282. return g.FontSize + g.Style.ItemSpacing.y;
  7283. }
  7284. float ImGui::GetFrameHeight()
  7285. {
  7286. ImGuiContext& g = *GImGui;
  7287. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  7288. }
  7289. float ImGui::GetFrameHeightWithSpacing()
  7290. {
  7291. ImGuiContext& g = *GImGui;
  7292. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  7293. }
  7294. // 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!
  7295. // FIXME: This is in window space (not screen space!).
  7296. ImVec2 ImGui::GetContentRegionMax()
  7297. {
  7298. ImGuiContext& g = *GImGui;
  7299. ImGuiWindow* window = g.CurrentWindow;
  7300. ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
  7301. if (window->DC.CurrentColumns || g.CurrentTable)
  7302. mx.x = window->WorkRect.Max.x - window->Pos.x;
  7303. return mx;
  7304. }
  7305. // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
  7306. ImVec2 ImGui::GetContentRegionMaxAbs()
  7307. {
  7308. ImGuiContext& g = *GImGui;
  7309. ImGuiWindow* window = g.CurrentWindow;
  7310. ImVec2 mx = window->ContentRegionRect.Max;
  7311. if (window->DC.CurrentColumns || g.CurrentTable)
  7312. mx.x = window->WorkRect.Max.x;
  7313. return mx;
  7314. }
  7315. ImVec2 ImGui::GetContentRegionAvail()
  7316. {
  7317. ImGuiWindow* window = GImGui->CurrentWindow;
  7318. return GetContentRegionMaxAbs() - window->DC.CursorPos;
  7319. }
  7320. // In window space (not screen space!)
  7321. ImVec2 ImGui::GetWindowContentRegionMin()
  7322. {
  7323. ImGuiWindow* window = GImGui->CurrentWindow;
  7324. return window->ContentRegionRect.Min - window->Pos;
  7325. }
  7326. ImVec2 ImGui::GetWindowContentRegionMax()
  7327. {
  7328. ImGuiWindow* window = GImGui->CurrentWindow;
  7329. return window->ContentRegionRect.Max - window->Pos;
  7330. }
  7331. // 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.)
  7332. // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
  7333. // FIXME-OPT: Could we safely early out on ->SkipItems?
  7334. void ImGui::BeginGroup()
  7335. {
  7336. ImGuiContext& g = *GImGui;
  7337. ImGuiWindow* window = g.CurrentWindow;
  7338. g.GroupStack.resize(g.GroupStack.Size + 1);
  7339. ImGuiGroupData& group_data = g.GroupStack.back();
  7340. group_data.WindowID = window->ID;
  7341. group_data.BackupCursorPos = window->DC.CursorPos;
  7342. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  7343. group_data.BackupIndent = window->DC.Indent;
  7344. group_data.BackupGroupOffset = window->DC.GroupOffset;
  7345. group_data.BackupCurrLineSize = window->DC.CurrLineSize;
  7346. group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
  7347. group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
  7348. group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
  7349. group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
  7350. group_data.EmitItem = true;
  7351. window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
  7352. window->DC.Indent = window->DC.GroupOffset;
  7353. window->DC.CursorMaxPos = window->DC.CursorPos;
  7354. window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
  7355. if (g.LogEnabled)
  7356. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  7357. }
  7358. void ImGui::EndGroup()
  7359. {
  7360. ImGuiContext& g = *GImGui;
  7361. ImGuiWindow* window = g.CurrentWindow;
  7362. IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
  7363. ImGuiGroupData& group_data = g.GroupStack.back();
  7364. IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
  7365. ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
  7366. window->DC.CursorPos = group_data.BackupCursorPos;
  7367. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  7368. window->DC.Indent = group_data.BackupIndent;
  7369. window->DC.GroupOffset = group_data.BackupGroupOffset;
  7370. window->DC.CurrLineSize = group_data.BackupCurrLineSize;
  7371. window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
  7372. if (g.LogEnabled)
  7373. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  7374. if (!group_data.EmitItem)
  7375. {
  7376. g.GroupStack.pop_back();
  7377. return;
  7378. }
  7379. 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.
  7380. ItemSize(group_bb.GetSize());
  7381. ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
  7382. // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
  7383. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
  7384. // Also if you grep for LastItemId you'll notice it is only used in that context.
  7385. // (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.)
  7386. const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
  7387. const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
  7388. if (group_contains_curr_active_id)
  7389. g.LastItemData.ID = g.ActiveId;
  7390. else if (group_contains_prev_active_id)
  7391. g.LastItemData.ID = g.ActiveIdPreviousFrame;
  7392. g.LastItemData.Rect = group_bb;
  7393. // Forward Hovered flag
  7394. const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
  7395. if (group_contains_curr_hovered_id)
  7396. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
  7397. // Forward Edited flag
  7398. if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
  7399. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
  7400. // Forward Deactivated flag
  7401. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
  7402. if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
  7403. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
  7404. g.GroupStack.pop_back();
  7405. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  7406. }
  7407. //-----------------------------------------------------------------------------
  7408. // [SECTION] SCROLLING
  7409. //-----------------------------------------------------------------------------
  7410. // Helper to snap on edges when aiming at an item very close to the edge,
  7411. // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
  7412. // When we refactor the scrolling API this may be configurable with a flag?
  7413. // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
  7414. static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
  7415. {
  7416. if (target <= snap_min + snap_threshold)
  7417. return ImLerp(snap_min, target, center_ratio);
  7418. if (target >= snap_max - snap_threshold)
  7419. return ImLerp(target, snap_max, center_ratio);
  7420. return target;
  7421. }
  7422. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
  7423. {
  7424. ImVec2 scroll = window->Scroll;
  7425. if (window->ScrollTarget.x < FLT_MAX)
  7426. {
  7427. float decoration_total_width = window->ScrollbarSizes.x;
  7428. float center_x_ratio = window->ScrollTargetCenterRatio.x;
  7429. float scroll_target_x = window->ScrollTarget.x;
  7430. if (window->ScrollTargetEdgeSnapDist.x > 0.0f)
  7431. {
  7432. float snap_x_min = 0.0f;
  7433. float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width;
  7434. scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);
  7435. }
  7436. scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width);
  7437. }
  7438. if (window->ScrollTarget.y < FLT_MAX)
  7439. {
  7440. float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y;
  7441. float center_y_ratio = window->ScrollTargetCenterRatio.y;
  7442. float scroll_target_y = window->ScrollTarget.y;
  7443. if (window->ScrollTargetEdgeSnapDist.y > 0.0f)
  7444. {
  7445. float snap_y_min = 0.0f;
  7446. float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height;
  7447. scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);
  7448. }
  7449. scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height);
  7450. }
  7451. scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
  7452. scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
  7453. if (!window->Collapsed && !window->SkipItems)
  7454. {
  7455. scroll.x = ImMin(scroll.x, window->ScrollMax.x);
  7456. scroll.y = ImMin(scroll.y, window->ScrollMax.y);
  7457. }
  7458. return scroll;
  7459. }
  7460. void ImGui::ScrollToItem(ImGuiScrollFlags flags)
  7461. {
  7462. ImGuiContext& g = *GImGui;
  7463. ImGuiWindow* window = g.CurrentWindow;
  7464. ScrollToRectEx(window, g.LastItemData.NavRect, flags);
  7465. }
  7466. void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
  7467. {
  7468. ScrollToRectEx(window, item_rect, flags);
  7469. }
  7470. // Scroll to keep newly navigated item fully into view
  7471. ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
  7472. {
  7473. ImGuiContext& g = *GImGui;
  7474. ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
  7475. //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
  7476. // Check that only one behavior is selected per axis
  7477. IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
  7478. IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
  7479. // Defaults
  7480. ImGuiScrollFlags in_flags = flags;
  7481. if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
  7482. flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
  7483. if ((flags & ImGuiScrollFlags_MaskY_) == 0)
  7484. flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
  7485. const bool fully_visible_x = item_rect.Min.x >= window_rect.Min.x && item_rect.Max.x <= window_rect.Max.x;
  7486. const bool fully_visible_y = item_rect.Min.y >= window_rect.Min.y && item_rect.Max.y <= window_rect.Max.y;
  7487. const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= window_rect.GetWidth();
  7488. const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= window_rect.GetHeight();
  7489. if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
  7490. {
  7491. if (item_rect.Min.x < window_rect.Min.x || !can_be_fully_visible_x)
  7492. SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
  7493. else if (item_rect.Max.x >= window_rect.Max.x)
  7494. SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
  7495. }
  7496. else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
  7497. {
  7498. float target_x = can_be_fully_visible_x ? ImFloor((item_rect.Min.x + item_rect.Max.x - window->InnerRect.GetWidth()) * 0.5f) : item_rect.Min.x;
  7499. SetScrollFromPosX(window, target_x - window->Pos.x, 0.0f);
  7500. }
  7501. if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
  7502. {
  7503. if (item_rect.Min.y < window_rect.Min.y || !can_be_fully_visible_y)
  7504. SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
  7505. else if (item_rect.Max.y >= window_rect.Max.y)
  7506. SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
  7507. }
  7508. else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
  7509. {
  7510. float target_y = can_be_fully_visible_y ? ImFloor((item_rect.Min.y + item_rect.Max.y - window->InnerRect.GetHeight()) * 0.5f) : item_rect.Min.y;
  7511. SetScrollFromPosY(window, target_y - window->Pos.y, 0.0f);
  7512. }
  7513. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  7514. ImVec2 delta_scroll = next_scroll - window->Scroll;
  7515. // Also scroll parent window to keep us into view if necessary
  7516. if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
  7517. {
  7518. // FIXME-SCROLL: May be an option?
  7519. if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
  7520. in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
  7521. if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
  7522. in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
  7523. delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
  7524. }
  7525. return delta_scroll;
  7526. }
  7527. float ImGui::GetScrollX()
  7528. {
  7529. ImGuiWindow* window = GImGui->CurrentWindow;
  7530. return window->Scroll.x;
  7531. }
  7532. float ImGui::GetScrollY()
  7533. {
  7534. ImGuiWindow* window = GImGui->CurrentWindow;
  7535. return window->Scroll.y;
  7536. }
  7537. float ImGui::GetScrollMaxX()
  7538. {
  7539. ImGuiWindow* window = GImGui->CurrentWindow;
  7540. return window->ScrollMax.x;
  7541. }
  7542. float ImGui::GetScrollMaxY()
  7543. {
  7544. ImGuiWindow* window = GImGui->CurrentWindow;
  7545. return window->ScrollMax.y;
  7546. }
  7547. void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
  7548. {
  7549. window->ScrollTarget.x = scroll_x;
  7550. window->ScrollTargetCenterRatio.x = 0.0f;
  7551. window->ScrollTargetEdgeSnapDist.x = 0.0f;
  7552. }
  7553. void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
  7554. {
  7555. window->ScrollTarget.y = scroll_y;
  7556. window->ScrollTargetCenterRatio.y = 0.0f;
  7557. window->ScrollTargetEdgeSnapDist.y = 0.0f;
  7558. }
  7559. void ImGui::SetScrollX(float scroll_x)
  7560. {
  7561. ImGuiContext& g = *GImGui;
  7562. SetScrollX(g.CurrentWindow, scroll_x);
  7563. }
  7564. void ImGui::SetScrollY(float scroll_y)
  7565. {
  7566. ImGuiContext& g = *GImGui;
  7567. SetScrollY(g.CurrentWindow, scroll_y);
  7568. }
  7569. // Note that a local position will vary depending on initial scroll value,
  7570. // This is a little bit confusing so bear with us:
  7571. // - local_pos = (absolution_pos - window->Pos)
  7572. // - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
  7573. // and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
  7574. // - They mostly exists because of legacy API.
  7575. // Following the rules above, when trying to work with scrolling code, consider that:
  7576. // - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
  7577. // - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
  7578. // We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
  7579. void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
  7580. {
  7581. IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
  7582. window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset
  7583. window->ScrollTargetCenterRatio.x = center_x_ratio;
  7584. window->ScrollTargetEdgeSnapDist.x = 0.0f;
  7585. }
  7586. void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
  7587. {
  7588. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  7589. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect;
  7590. local_y -= decoration_up_height;
  7591. window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset
  7592. window->ScrollTargetCenterRatio.y = center_y_ratio;
  7593. window->ScrollTargetEdgeSnapDist.y = 0.0f;
  7594. }
  7595. void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
  7596. {
  7597. ImGuiContext& g = *GImGui;
  7598. SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
  7599. }
  7600. void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
  7601. {
  7602. ImGuiContext& g = *GImGui;
  7603. SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
  7604. }
  7605. // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
  7606. void ImGui::SetScrollHereX(float center_x_ratio)
  7607. {
  7608. ImGuiContext& g = *GImGui;
  7609. ImGuiWindow* window = g.CurrentWindow;
  7610. float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
  7611. float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
  7612. SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
  7613. // Tweak: snap on edges when aiming at an item very close to the edge
  7614. window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
  7615. }
  7616. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  7617. void ImGui::SetScrollHereY(float center_y_ratio)
  7618. {
  7619. ImGuiContext& g = *GImGui;
  7620. ImGuiWindow* window = g.CurrentWindow;
  7621. float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
  7622. float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
  7623. SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
  7624. // Tweak: snap on edges when aiming at an item very close to the edge
  7625. window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
  7626. }
  7627. //-----------------------------------------------------------------------------
  7628. // [SECTION] TOOLTIPS
  7629. //-----------------------------------------------------------------------------
  7630. void ImGui::BeginTooltip()
  7631. {
  7632. BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
  7633. }
  7634. void ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
  7635. {
  7636. ImGuiContext& g = *GImGui;
  7637. if (g.DragDropWithinSource || g.DragDropWithinTarget)
  7638. {
  7639. // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
  7640. // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
  7641. // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
  7642. //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
  7643. ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
  7644. SetNextWindowPos(tooltip_pos);
  7645. SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
  7646. //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
  7647. tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
  7648. }
  7649. char window_name[16];
  7650. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
  7651. if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
  7652. if (ImGuiWindow* window = FindWindowByName(window_name))
  7653. if (window->Active)
  7654. {
  7655. // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
  7656. window->Hidden = true;
  7657. window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
  7658. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
  7659. }
  7660. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
  7661. Begin(window_name, NULL, flags | extra_window_flags);
  7662. }
  7663. void ImGui::EndTooltip()
  7664. {
  7665. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  7666. End();
  7667. }
  7668. void ImGui::SetTooltipV(const char* fmt, va_list args)
  7669. {
  7670. BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);
  7671. TextV(fmt, args);
  7672. EndTooltip();
  7673. }
  7674. void ImGui::SetTooltip(const char* fmt, ...)
  7675. {
  7676. va_list args;
  7677. va_start(args, fmt);
  7678. SetTooltipV(fmt, args);
  7679. va_end(args);
  7680. }
  7681. //-----------------------------------------------------------------------------
  7682. // [SECTION] POPUPS
  7683. //-----------------------------------------------------------------------------
  7684. // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
  7685. bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
  7686. {
  7687. ImGuiContext& g = *GImGui;
  7688. if (popup_flags & ImGuiPopupFlags_AnyPopupId)
  7689. {
  7690. // Return true if any popup is open at the current BeginPopup() level of the popup stack
  7691. // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
  7692. IM_ASSERT(id == 0);
  7693. if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
  7694. return g.OpenPopupStack.Size > 0;
  7695. else
  7696. return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
  7697. }
  7698. else
  7699. {
  7700. if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
  7701. {
  7702. // Return true if the popup is open anywhere in the popup stack
  7703. for (int n = 0; n < g.OpenPopupStack.Size; n++)
  7704. if (g.OpenPopupStack[n].PopupId == id)
  7705. return true;
  7706. return false;
  7707. }
  7708. else
  7709. {
  7710. // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
  7711. return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
  7712. }
  7713. }
  7714. }
  7715. bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
  7716. {
  7717. ImGuiContext& g = *GImGui;
  7718. ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
  7719. if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
  7720. IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
  7721. return IsPopupOpen(id, popup_flags);
  7722. }
  7723. ImGuiWindow* ImGui::GetTopMostPopupModal()
  7724. {
  7725. ImGuiContext& g = *GImGui;
  7726. for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
  7727. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  7728. if (popup->Flags & ImGuiWindowFlags_Modal)
  7729. return popup;
  7730. return NULL;
  7731. }
  7732. ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
  7733. {
  7734. ImGuiContext& g = *GImGui;
  7735. for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
  7736. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  7737. if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
  7738. return popup;
  7739. return NULL;
  7740. }
  7741. void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
  7742. {
  7743. ImGuiContext& g = *GImGui;
  7744. OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags);
  7745. }
  7746. void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
  7747. {
  7748. OpenPopupEx(id, popup_flags);
  7749. }
  7750. // Mark popup as open (toggle toward open state).
  7751. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  7752. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  7753. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  7754. void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
  7755. {
  7756. ImGuiContext& g = *GImGui;
  7757. ImGuiWindow* parent_window = g.CurrentWindow;
  7758. const int current_stack_size = g.BeginPopupStack.Size;
  7759. if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
  7760. if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
  7761. return;
  7762. ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
  7763. popup_ref.PopupId = id;
  7764. popup_ref.Window = NULL;
  7765. popup_ref.SourceWindow = g.NavWindow;
  7766. popup_ref.OpenFrameCount = g.FrameCount;
  7767. popup_ref.OpenParentId = parent_window->IDStack.back();
  7768. popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
  7769. popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
  7770. IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id);
  7771. if (g.OpenPopupStack.Size < current_stack_size + 1)
  7772. {
  7773. g.OpenPopupStack.push_back(popup_ref);
  7774. }
  7775. else
  7776. {
  7777. // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
  7778. // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
  7779. // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
  7780. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
  7781. {
  7782. g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
  7783. }
  7784. else
  7785. {
  7786. // Close child popups if any, then flag popup for open/reopen
  7787. ClosePopupToLevel(current_stack_size, false);
  7788. g.OpenPopupStack.push_back(popup_ref);
  7789. }
  7790. // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
  7791. // This is equivalent to what ClosePopupToLevel() does.
  7792. //if (g.OpenPopupStack[current_stack_size].PopupId == id)
  7793. // FocusWindow(parent_window);
  7794. }
  7795. }
  7796. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  7797. // This function closes any popups that are over 'ref_window'.
  7798. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
  7799. {
  7800. ImGuiContext& g = *GImGui;
  7801. if (g.OpenPopupStack.Size == 0)
  7802. return;
  7803. // Don't close our own child popup windows.
  7804. int popup_count_to_keep = 0;
  7805. if (ref_window)
  7806. {
  7807. // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
  7808. for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
  7809. {
  7810. ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
  7811. if (!popup.Window)
  7812. continue;
  7813. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  7814. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  7815. continue;
  7816. // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
  7817. // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
  7818. // Window -> Popup1 -> Popup2 -> Popup3
  7819. // - Each popups may contain child windows, which is why we compare ->RootWindow!
  7820. // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
  7821. bool ref_window_is_descendent_of_popup = false;
  7822. for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
  7823. if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
  7824. if (IsWindowWithinBeginStackOf(ref_window, popup_window))
  7825. {
  7826. ref_window_is_descendent_of_popup = true;
  7827. break;
  7828. }
  7829. if (!ref_window_is_descendent_of_popup)
  7830. break;
  7831. }
  7832. }
  7833. if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
  7834. {
  7835. IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
  7836. ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
  7837. }
  7838. }
  7839. void ImGui::ClosePopupsExceptModals()
  7840. {
  7841. ImGuiContext& g = *GImGui;
  7842. int popup_count_to_keep;
  7843. for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
  7844. {
  7845. ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
  7846. if (!window || window->Flags & ImGuiWindowFlags_Modal)
  7847. break;
  7848. }
  7849. if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
  7850. ClosePopupToLevel(popup_count_to_keep, true);
  7851. }
  7852. void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
  7853. {
  7854. ImGuiContext& g = *GImGui;
  7855. IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
  7856. IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
  7857. // Trim open popup stack
  7858. ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
  7859. ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
  7860. g.OpenPopupStack.resize(remaining);
  7861. if (restore_focus_to_window_under_popup)
  7862. {
  7863. if (focus_window && !focus_window->WasActive && popup_window)
  7864. {
  7865. // Fallback
  7866. FocusTopMostWindowUnderOne(popup_window, NULL);
  7867. }
  7868. else
  7869. {
  7870. if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
  7871. focus_window = NavRestoreLastChildNavWindow(focus_window);
  7872. FocusWindow(focus_window);
  7873. }
  7874. }
  7875. }
  7876. // Close the popup we have begin-ed into.
  7877. void ImGui::CloseCurrentPopup()
  7878. {
  7879. ImGuiContext& g = *GImGui;
  7880. int popup_idx = g.BeginPopupStack.Size - 1;
  7881. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  7882. return;
  7883. // Closing a menu closes its top-most parent popup (unless a modal)
  7884. while (popup_idx > 0)
  7885. {
  7886. ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
  7887. ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
  7888. bool close_parent = false;
  7889. if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
  7890. if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
  7891. close_parent = true;
  7892. if (!close_parent)
  7893. break;
  7894. popup_idx--;
  7895. }
  7896. IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
  7897. ClosePopupToLevel(popup_idx, true);
  7898. // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
  7899. // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
  7900. // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
  7901. if (ImGuiWindow* window = g.NavWindow)
  7902. window->DC.NavHideHighlightOneFrame = true;
  7903. }
  7904. // Attention! BeginPopup() adds default flags which BeginPopupEx()!
  7905. bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
  7906. {
  7907. ImGuiContext& g = *GImGui;
  7908. if (!IsPopupOpen(id, ImGuiPopupFlags_None))
  7909. {
  7910. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7911. return false;
  7912. }
  7913. char name[20];
  7914. if (flags & ImGuiWindowFlags_ChildMenu)
  7915. ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
  7916. else
  7917. ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
  7918. flags |= ImGuiWindowFlags_Popup;
  7919. bool is_open = Begin(name, NULL, flags);
  7920. if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
  7921. EndPopup();
  7922. return is_open;
  7923. }
  7924. bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
  7925. {
  7926. ImGuiContext& g = *GImGui;
  7927. if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
  7928. {
  7929. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7930. return false;
  7931. }
  7932. flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
  7933. return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
  7934. }
  7935. // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
  7936. // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
  7937. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
  7938. {
  7939. ImGuiContext& g = *GImGui;
  7940. ImGuiWindow* window = g.CurrentWindow;
  7941. const ImGuiID id = window->GetID(name);
  7942. if (!IsPopupOpen(id, ImGuiPopupFlags_None))
  7943. {
  7944. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7945. return false;
  7946. }
  7947. // Center modal windows by default for increased visibility
  7948. // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
  7949. // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
  7950. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
  7951. {
  7952. const ImGuiViewport* viewport = GetMainViewport();
  7953. SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
  7954. }
  7955. flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
  7956. const bool is_open = Begin(name, p_open, flags);
  7957. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  7958. {
  7959. EndPopup();
  7960. if (is_open)
  7961. ClosePopupToLevel(g.BeginPopupStack.Size, true);
  7962. return false;
  7963. }
  7964. return is_open;
  7965. }
  7966. void ImGui::EndPopup()
  7967. {
  7968. ImGuiContext& g = *GImGui;
  7969. ImGuiWindow* window = g.CurrentWindow;
  7970. IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  7971. IM_ASSERT(g.BeginPopupStack.Size > 0);
  7972. // 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)
  7973. if (g.NavWindow == window)
  7974. NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
  7975. // Child-popups don't need to be laid out
  7976. IM_ASSERT(g.WithinEndChild == false);
  7977. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  7978. g.WithinEndChild = true;
  7979. End();
  7980. g.WithinEndChild = false;
  7981. }
  7982. // Helper to open a popup if mouse button is released over the item
  7983. // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
  7984. void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
  7985. {
  7986. ImGuiContext& g = *GImGui;
  7987. ImGuiWindow* window = g.CurrentWindow;
  7988. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  7989. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  7990. {
  7991. 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!
  7992. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  7993. OpenPopupEx(id, popup_flags);
  7994. }
  7995. }
  7996. // This is a helper to handle the simplest case of associating one named popup to one given widget.
  7997. // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
  7998. // - To create a popup with a specific identifier, pass it in str_id.
  7999. // - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
  8000. // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
  8001. // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
  8002. // This is essentially the same as:
  8003. // id = str_id ? GetID(str_id) : GetItemID();
  8004. // OpenPopupOnItemClick(str_id);
  8005. // return BeginPopup(id);
  8006. // Which is essentially the same as:
  8007. // id = str_id ? GetID(str_id) : GetItemID();
  8008. // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
  8009. // OpenPopup(id);
  8010. // return BeginPopup(id);
  8011. // The main difference being that this is tweaked to avoid computing the ID twice.
  8012. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
  8013. {
  8014. ImGuiContext& g = *GImGui;
  8015. ImGuiWindow* window = g.CurrentWindow;
  8016. if (window->SkipItems)
  8017. return false;
  8018. 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!
  8019. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  8020. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8021. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8022. OpenPopupEx(id, popup_flags);
  8023. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8024. }
  8025. bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
  8026. {
  8027. ImGuiContext& g = *GImGui;
  8028. ImGuiWindow* window = g.CurrentWindow;
  8029. if (!str_id)
  8030. str_id = "window_context";
  8031. ImGuiID id = window->GetID(str_id);
  8032. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8033. if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8034. if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
  8035. OpenPopupEx(id, popup_flags);
  8036. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8037. }
  8038. bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
  8039. {
  8040. ImGuiContext& g = *GImGui;
  8041. ImGuiWindow* window = g.CurrentWindow;
  8042. if (!str_id)
  8043. str_id = "void_context";
  8044. ImGuiID id = window->GetID(str_id);
  8045. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8046. if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
  8047. if (GetTopMostPopupModal() == NULL)
  8048. OpenPopupEx(id, popup_flags);
  8049. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8050. }
  8051. // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
  8052. // r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
  8053. // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
  8054. // information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
  8055. // this allows us to have tooltips/popups displayed out of the parent viewport.)
  8056. ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
  8057. {
  8058. ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
  8059. //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
  8060. //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
  8061. // Combo Box policy (we want a connecting edge)
  8062. if (policy == ImGuiPopupPositionPolicy_ComboBox)
  8063. {
  8064. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
  8065. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  8066. {
  8067. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  8068. if (n != -1 && dir == *last_dir) // Already tried this direction?
  8069. continue;
  8070. ImVec2 pos;
  8071. if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
  8072. if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
  8073. if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
  8074. if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
  8075. if (!r_outer.Contains(ImRect(pos, pos + size)))
  8076. continue;
  8077. *last_dir = dir;
  8078. return pos;
  8079. }
  8080. }
  8081. // Tooltip and Default popup policy
  8082. // (Always first try the direction we used on the last frame, if any)
  8083. if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
  8084. {
  8085. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
  8086. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  8087. {
  8088. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  8089. if (n != -1 && dir == *last_dir) // Already tried this direction?
  8090. continue;
  8091. const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
  8092. const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
  8093. // If there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
  8094. if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
  8095. continue;
  8096. if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
  8097. continue;
  8098. ImVec2 pos;
  8099. pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
  8100. pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
  8101. // Clamp top-left corner of popup
  8102. pos.x = ImMax(pos.x, r_outer.Min.x);
  8103. pos.y = ImMax(pos.y, r_outer.Min.y);
  8104. *last_dir = dir;
  8105. return pos;
  8106. }
  8107. }
  8108. // Fallback when not enough room:
  8109. *last_dir = ImGuiDir_None;
  8110. // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  8111. if (policy == ImGuiPopupPositionPolicy_Tooltip)
  8112. return ref_pos + ImVec2(2, 2);
  8113. // Otherwise try to keep within display
  8114. ImVec2 pos = ref_pos;
  8115. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  8116. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  8117. return pos;
  8118. }
  8119. // Note that this is used for popups, which can overlap the non work-area of individual viewports.
  8120. ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
  8121. {
  8122. ImGuiContext& g = *GImGui;
  8123. IM_UNUSED(window);
  8124. ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();
  8125. ImVec2 padding = g.Style.DisplaySafeAreaPadding;
  8126. r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
  8127. return r_screen;
  8128. }
  8129. ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
  8130. {
  8131. ImGuiContext& g = *GImGui;
  8132. ImRect r_outer = GetPopupAllowedExtentRect(window);
  8133. if (window->Flags & ImGuiWindowFlags_ChildMenu)
  8134. {
  8135. // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
  8136. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  8137. IM_ASSERT(g.CurrentWindow == window);
  8138. ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window;
  8139. float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
  8140. ImRect r_avoid;
  8141. if (parent_window->DC.MenuBarAppending)
  8142. r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
  8143. else
  8144. r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
  8145. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
  8146. }
  8147. if (window->Flags & ImGuiWindowFlags_Popup)
  8148. {
  8149. ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
  8150. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
  8151. }
  8152. if (window->Flags & ImGuiWindowFlags_Tooltip)
  8153. {
  8154. // Position tooltip (always follows mouse)
  8155. float sc = g.Style.MouseCursorScale;
  8156. ImVec2 ref_pos = NavCalcPreferredRefPos();
  8157. ImRect r_avoid;
  8158. if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
  8159. r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
  8160. else
  8161. r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
  8162. return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
  8163. }
  8164. IM_ASSERT(0);
  8165. return window->Pos;
  8166. }
  8167. //-----------------------------------------------------------------------------
  8168. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  8169. //-----------------------------------------------------------------------------
  8170. // FIXME-NAV: The existence of SetNavID vs SetFocusID properly needs to be clarified/reworked.
  8171. // In our terminology those should be interchangeable. Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
  8172. void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
  8173. {
  8174. ImGuiContext& g = *GImGui;
  8175. IM_ASSERT(g.NavWindow != NULL);
  8176. IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
  8177. g.NavId = id;
  8178. g.NavLayer = nav_layer;
  8179. g.NavFocusScopeId = focus_scope_id;
  8180. g.NavWindow->NavLastIds[nav_layer] = id;
  8181. g.NavWindow->NavRectRel[nav_layer] = rect_rel;
  8182. }
  8183. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
  8184. {
  8185. ImGuiContext& g = *GImGui;
  8186. IM_ASSERT(id != 0);
  8187. // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
  8188. // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
  8189. const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
  8190. if (g.NavWindow != window)
  8191. g.NavInitRequest = false;
  8192. g.NavWindow = window;
  8193. g.NavId = id;
  8194. g.NavLayer = nav_layer;
  8195. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  8196. window->NavLastIds[nav_layer] = id;
  8197. if (g.LastItemData.ID == id)
  8198. window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
  8199. if (g.ActiveIdSource == ImGuiInputSource_Nav)
  8200. g.NavDisableMouseHover = true;
  8201. else
  8202. g.NavDisableHighlight = true;
  8203. }
  8204. ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
  8205. {
  8206. if (ImFabs(dx) > ImFabs(dy))
  8207. return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
  8208. return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
  8209. }
  8210. static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
  8211. {
  8212. if (a1 < b0)
  8213. return a1 - b0;
  8214. if (b1 < a0)
  8215. return a0 - b1;
  8216. return 0.0f;
  8217. }
  8218. static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
  8219. {
  8220. if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
  8221. {
  8222. r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
  8223. r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
  8224. }
  8225. else // FIXME: PageUp/PageDown are leaving move_dir == None
  8226. {
  8227. r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
  8228. r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
  8229. }
  8230. }
  8231. // Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
  8232. static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
  8233. {
  8234. ImGuiContext& g = *GImGui;
  8235. ImGuiWindow* window = g.CurrentWindow;
  8236. if (g.NavLayer != window->DC.NavLayerCurrent)
  8237. return false;
  8238. // FIXME: Those are not good variables names
  8239. ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle
  8240. 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)
  8241. g.NavScoringDebugCount++;
  8242. // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
  8243. if (window->ParentWindow == g.NavWindow)
  8244. {
  8245. IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
  8246. if (!window->ClipRect.Overlaps(cand))
  8247. return false;
  8248. cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
  8249. }
  8250. // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
  8251. // For example, this ensure that items in one column are not reached when moving vertically from items in another column.
  8252. NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
  8253. // Compute distance between boxes
  8254. // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
  8255. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
  8256. float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
  8257. if (dby != 0.0f && dbx != 0.0f)
  8258. dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
  8259. float dist_box = ImFabs(dbx) + ImFabs(dby);
  8260. // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
  8261. float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
  8262. float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
  8263. float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
  8264. // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
  8265. ImGuiDir quadrant;
  8266. float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
  8267. if (dbx != 0.0f || dby != 0.0f)
  8268. {
  8269. // For non-overlapping boxes, use distance between boxes
  8270. dax = dbx;
  8271. day = dby;
  8272. dist_axial = dist_box;
  8273. quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
  8274. }
  8275. else if (dcx != 0.0f || dcy != 0.0f)
  8276. {
  8277. // For overlapping boxes with different centers, use distance between centers
  8278. dax = dcx;
  8279. day = dcy;
  8280. dist_axial = dist_center;
  8281. quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
  8282. }
  8283. else
  8284. {
  8285. // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
  8286. quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
  8287. }
  8288. #if IMGUI_DEBUG_NAV_SCORING
  8289. char buf[128];
  8290. if (IsMouseHoveringRect(cand.Min, cand.Max))
  8291. {
  8292. ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
  8293. ImDrawList* draw_list = GetForegroundDrawList(window);
  8294. draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
  8295. draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
  8296. draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
  8297. draw_list->AddText(cand.Max, ~0U, buf);
  8298. }
  8299. else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
  8300. {
  8301. if (quadrant == g.NavMoveDir)
  8302. {
  8303. ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
  8304. ImDrawList* draw_list = GetForegroundDrawList(window);
  8305. draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
  8306. draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
  8307. }
  8308. }
  8309. #endif
  8310. // Is it in the quadrant we're interesting in moving to?
  8311. bool new_best = false;
  8312. const ImGuiDir move_dir = g.NavMoveDir;
  8313. if (quadrant == move_dir)
  8314. {
  8315. // Does it beat the current best candidate?
  8316. if (dist_box < result->DistBox)
  8317. {
  8318. result->DistBox = dist_box;
  8319. result->DistCenter = dist_center;
  8320. return true;
  8321. }
  8322. if (dist_box == result->DistBox)
  8323. {
  8324. // Try using distance between center points to break ties
  8325. if (dist_center < result->DistCenter)
  8326. {
  8327. result->DistCenter = dist_center;
  8328. new_best = true;
  8329. }
  8330. else if (dist_center == result->DistCenter)
  8331. {
  8332. // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
  8333. // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
  8334. // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
  8335. if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
  8336. new_best = true;
  8337. }
  8338. }
  8339. }
  8340. // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
  8341. // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
  8342. // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
  8343. // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
  8344. // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
  8345. if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
  8346. if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
  8347. if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
  8348. {
  8349. result->DistAxial = dist_axial;
  8350. new_best = true;
  8351. }
  8352. return new_best;
  8353. }
  8354. static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
  8355. {
  8356. ImGuiContext& g = *GImGui;
  8357. ImGuiWindow* window = g.CurrentWindow;
  8358. result->Window = window;
  8359. result->ID = g.LastItemData.ID;
  8360. result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
  8361. result->InFlags = g.LastItemData.InFlags;
  8362. result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
  8363. }
  8364. // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
  8365. // This is called after LastItemData is set.
  8366. static void ImGui::NavProcessItem()
  8367. {
  8368. ImGuiContext& g = *GImGui;
  8369. ImGuiWindow* window = g.CurrentWindow;
  8370. const ImGuiID id = g.LastItemData.ID;
  8371. const ImRect nav_bb = g.LastItemData.NavRect;
  8372. const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
  8373. // Process Init Request
  8374. if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
  8375. {
  8376. // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
  8377. const bool candidate_for_nav_default_focus = (item_flags & (ImGuiItemFlags_NoNavDefaultFocus | ImGuiItemFlags_Disabled)) == 0;
  8378. if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
  8379. {
  8380. g.NavInitResultId = id;
  8381. g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
  8382. }
  8383. if (candidate_for_nav_default_focus)
  8384. {
  8385. g.NavInitRequest = false; // Found a match, clear request
  8386. NavUpdateAnyRequestFlag();
  8387. }
  8388. }
  8389. // Process Move Request (scoring for navigation)
  8390. // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
  8391. if (g.NavMoveScoringItems)
  8392. {
  8393. const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
  8394. const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
  8395. if (is_tabbing)
  8396. {
  8397. if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi))
  8398. NavProcessItemForTabbingRequest(id);
  8399. }
  8400. else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))
  8401. {
  8402. ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  8403. if (!is_tabbing)
  8404. {
  8405. if (NavScoreItem(result))
  8406. NavApplyItemToResult(result);
  8407. // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
  8408. const float VISIBLE_RATIO = 0.70f;
  8409. if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
  8410. 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)
  8411. if (NavScoreItem(&g.NavMoveResultLocalVisible))
  8412. NavApplyItemToResult(&g.NavMoveResultLocalVisible);
  8413. }
  8414. }
  8415. }
  8416. // Update window-relative bounding box of navigated item
  8417. if (g.NavId == id)
  8418. {
  8419. g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
  8420. g.NavLayer = window->DC.NavLayerCurrent;
  8421. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  8422. g.NavIdIsAlive = true;
  8423. window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
  8424. }
  8425. }
  8426. // Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
  8427. // Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
  8428. // - Case 1: no nav/active id: set result to first eligible item, stop storing.
  8429. // - Case 2: tab forward: on ref id set counter, on counter elapse store result
  8430. // - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
  8431. // - Case 4: tab backward: store all results, on ref id pick prev, stop storing
  8432. // - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
  8433. void ImGui::NavProcessItemForTabbingRequest(ImGuiID id)
  8434. {
  8435. ImGuiContext& g = *GImGui;
  8436. // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
  8437. ImGuiNavItemData* result = &g.NavMoveResultLocal;
  8438. if (g.NavTabbingDir == +1)
  8439. {
  8440. // Tab Forward or SetKeyboardFocusHere() with >= 0
  8441. if (g.NavTabbingResultFirst.ID == 0)
  8442. NavApplyItemToResult(&g.NavTabbingResultFirst);
  8443. if (--g.NavTabbingCounter == 0)
  8444. NavMoveRequestResolveWithLastItem(result);
  8445. else if (g.NavId == id)
  8446. g.NavTabbingCounter = 1;
  8447. }
  8448. else if (g.NavTabbingDir == -1)
  8449. {
  8450. // Tab Backward
  8451. if (g.NavId == id)
  8452. {
  8453. if (result->ID)
  8454. {
  8455. g.NavMoveScoringItems = false;
  8456. NavUpdateAnyRequestFlag();
  8457. }
  8458. }
  8459. else
  8460. {
  8461. NavApplyItemToResult(result);
  8462. }
  8463. }
  8464. else if (g.NavTabbingDir == 0)
  8465. {
  8466. // Tab Init
  8467. if (g.NavTabbingResultFirst.ID == 0)
  8468. NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst);
  8469. }
  8470. }
  8471. bool ImGui::NavMoveRequestButNoResultYet()
  8472. {
  8473. ImGuiContext& g = *GImGui;
  8474. return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
  8475. }
  8476. // FIXME: ScoringRect is not set
  8477. void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
  8478. {
  8479. ImGuiContext& g = *GImGui;
  8480. IM_ASSERT(g.NavWindow != NULL);
  8481. if (move_flags & ImGuiNavMoveFlags_Tabbing)
  8482. move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
  8483. g.NavMoveSubmitted = g.NavMoveScoringItems = true;
  8484. g.NavMoveDir = move_dir;
  8485. g.NavMoveDirForDebug = move_dir;
  8486. g.NavMoveClipDir = clip_dir;
  8487. g.NavMoveFlags = move_flags;
  8488. g.NavMoveScrollFlags = scroll_flags;
  8489. g.NavMoveForwardToNextFrame = false;
  8490. g.NavMoveKeyMods = g.IO.KeyMods;
  8491. g.NavTabbingCounter = 0;
  8492. g.NavMoveResultLocal.Clear();
  8493. g.NavMoveResultLocalVisible.Clear();
  8494. g.NavMoveResultOther.Clear();
  8495. NavUpdateAnyRequestFlag();
  8496. }
  8497. void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
  8498. {
  8499. ImGuiContext& g = *GImGui;
  8500. g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
  8501. NavApplyItemToResult(result);
  8502. NavUpdateAnyRequestFlag();
  8503. }
  8504. void ImGui::NavMoveRequestCancel()
  8505. {
  8506. ImGuiContext& g = *GImGui;
  8507. g.NavMoveSubmitted = g.NavMoveScoringItems = false;
  8508. NavUpdateAnyRequestFlag();
  8509. }
  8510. // Forward will reuse the move request again on the next frame (generally with modifications done to it)
  8511. void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
  8512. {
  8513. ImGuiContext& g = *GImGui;
  8514. IM_ASSERT(g.NavMoveForwardToNextFrame == false);
  8515. NavMoveRequestCancel();
  8516. g.NavMoveForwardToNextFrame = true;
  8517. g.NavMoveDir = move_dir;
  8518. g.NavMoveClipDir = clip_dir;
  8519. g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
  8520. g.NavMoveScrollFlags = scroll_flags;
  8521. }
  8522. // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
  8523. // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
  8524. void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
  8525. {
  8526. ImGuiContext& g = *GImGui;
  8527. IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
  8528. // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
  8529. if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
  8530. g.NavMoveFlags |= wrap_flags;
  8531. }
  8532. // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
  8533. // This way we could find the last focused window among our children. It would be much less confusing this way?
  8534. static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
  8535. {
  8536. ImGuiWindow* parent = nav_window;
  8537. while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  8538. parent = parent->ParentWindow;
  8539. if (parent && parent != nav_window)
  8540. parent->NavLastChildNavWindow = nav_window;
  8541. }
  8542. // Restore the last focused child.
  8543. // Call when we are expected to land on the Main Layer (0) after FocusWindow()
  8544. static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
  8545. {
  8546. if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
  8547. return window->NavLastChildNavWindow;
  8548. return window;
  8549. }
  8550. void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
  8551. {
  8552. ImGuiContext& g = *GImGui;
  8553. if (layer == ImGuiNavLayer_Main)
  8554. g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);
  8555. ImGuiWindow* window = g.NavWindow;
  8556. if (window->NavLastIds[layer] != 0)
  8557. {
  8558. SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
  8559. }
  8560. else
  8561. {
  8562. g.NavLayer = layer;
  8563. NavInitWindow(window, true);
  8564. }
  8565. }
  8566. void ImGui::NavRestoreHighlightAfterMove()
  8567. {
  8568. ImGuiContext& g = *GImGui;
  8569. g.NavDisableHighlight = false;
  8570. g.NavDisableMouseHover = g.NavMousePosDirty = true;
  8571. }
  8572. static inline void ImGui::NavUpdateAnyRequestFlag()
  8573. {
  8574. ImGuiContext& g = *GImGui;
  8575. g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
  8576. if (g.NavAnyRequest)
  8577. IM_ASSERT(g.NavWindow != NULL);
  8578. }
  8579. // This needs to be called before we submit any widget (aka in or before Begin)
  8580. void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
  8581. {
  8582. ImGuiContext& g = *GImGui;
  8583. IM_ASSERT(window == g.NavWindow);
  8584. if (window->Flags & ImGuiWindowFlags_NoNavInputs)
  8585. {
  8586. g.NavId = g.NavFocusScopeId = 0;
  8587. return;
  8588. }
  8589. bool init_for_nav = false;
  8590. if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
  8591. init_for_nav = true;
  8592. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
  8593. if (init_for_nav)
  8594. {
  8595. SetNavID(0, g.NavLayer, 0, ImRect());
  8596. g.NavInitRequest = true;
  8597. g.NavInitRequestFromMove = false;
  8598. g.NavInitResultId = 0;
  8599. g.NavInitResultRectRel = ImRect();
  8600. NavUpdateAnyRequestFlag();
  8601. }
  8602. else
  8603. {
  8604. g.NavId = window->NavLastIds[0];
  8605. g.NavFocusScopeId = 0;
  8606. }
  8607. }
  8608. static ImVec2 ImGui::NavCalcPreferredRefPos()
  8609. {
  8610. ImGuiContext& g = *GImGui;
  8611. ImGuiWindow* window = g.NavWindow;
  8612. if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
  8613. {
  8614. // Mouse (we need a fallback in case the mouse becomes invalid after being used)
  8615. if (IsMousePosValid(&g.IO.MousePos))
  8616. return g.IO.MousePos;
  8617. return g.MouseLastValidPos;
  8618. }
  8619. else
  8620. {
  8621. // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
  8622. // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
  8623. ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
  8624. if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
  8625. {
  8626. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  8627. rect_rel.Translate(window->Scroll - next_scroll);
  8628. }
  8629. ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
  8630. ImGuiViewport* viewport = GetMainViewport();
  8631. return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
  8632. }
  8633. }
  8634. float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
  8635. {
  8636. ImGuiContext& g = *GImGui;
  8637. if (mode == ImGuiInputReadMode_Down)
  8638. return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
  8639. const float t = g.IO.NavInputsDownDuration[n];
  8640. if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
  8641. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
  8642. if (t < 0.0f)
  8643. return 0.0f;
  8644. if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
  8645. return (t == 0.0f) ? 1.0f : 0.0f;
  8646. if (mode == ImGuiInputReadMode_Repeat)
  8647. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
  8648. if (mode == ImGuiInputReadMode_RepeatSlow)
  8649. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
  8650. if (mode == ImGuiInputReadMode_RepeatFast)
  8651. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
  8652. return 0.0f;
  8653. }
  8654. ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
  8655. {
  8656. ImVec2 delta(0.0f, 0.0f);
  8657. if (dir_sources & ImGuiNavDirSourceFlags_RawKeyboard)
  8658. delta += ImVec2((float)IsKeyDown(ImGuiKey_RightArrow) - (float)IsKeyDown(ImGuiKey_LeftArrow), (float)IsKeyDown(ImGuiKey_DownArrow) - (float)IsKeyDown(ImGuiKey_UpArrow));
  8659. if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
  8660. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
  8661. if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
  8662. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
  8663. if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
  8664. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
  8665. if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
  8666. delta *= slow_factor;
  8667. if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
  8668. delta *= fast_factor;
  8669. return delta;
  8670. }
  8671. static void ImGui::NavUpdate()
  8672. {
  8673. ImGuiContext& g = *GImGui;
  8674. ImGuiIO& io = g.IO;
  8675. io.WantSetMousePos = false;
  8676. //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG("NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
  8677. // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
  8678. // (do it before we map Keyboard input!)
  8679. const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  8680. const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  8681. if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_Gamepad)
  8682. {
  8683. if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f
  8684. || io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f)
  8685. g.NavInputSource = ImGuiInputSource_Gamepad;
  8686. }
  8687. // Update Keyboard->Nav inputs mapping
  8688. if (nav_keyboard_active)
  8689. {
  8690. #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(_KEY)) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_Keyboard; } } while (0)
  8691. NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
  8692. NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
  8693. NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
  8694. NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
  8695. NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
  8696. NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
  8697. NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
  8698. if (io.KeyCtrl)
  8699. io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
  8700. if (io.KeyShift)
  8701. io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
  8702. #undef NAV_MAP_KEY
  8703. }
  8704. memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration));
  8705. for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
  8706. io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f;
  8707. // Process navigation init request (select first/default focus)
  8708. if (g.NavInitResultId != 0)
  8709. NavInitRequestApplyResult();
  8710. g.NavInitRequest = false;
  8711. g.NavInitRequestFromMove = false;
  8712. g.NavInitResultId = 0;
  8713. g.NavJustMovedToId = 0;
  8714. // Process navigation move request
  8715. if (g.NavMoveSubmitted)
  8716. NavMoveRequestApplyResult();
  8717. g.NavTabbingCounter = 0;
  8718. g.NavMoveSubmitted = g.NavMoveScoringItems = false;
  8719. // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
  8720. bool set_mouse_pos = false;
  8721. if (g.NavMousePosDirty && g.NavIdIsAlive)
  8722. if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
  8723. set_mouse_pos = true;
  8724. g.NavMousePosDirty = false;
  8725. IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
  8726. // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
  8727. if (g.NavWindow)
  8728. NavSaveLastChildNavWindowIntoParent(g.NavWindow);
  8729. if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
  8730. g.NavWindow->NavLastChildNavWindow = NULL;
  8731. // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
  8732. NavUpdateWindowing();
  8733. // Set output flags for user application
  8734. io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
  8735. io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
  8736. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  8737. NavUpdateCancelRequest();
  8738. // Process manual activation request
  8739. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;
  8740. g.NavActivateFlags = ImGuiActivateFlags_None;
  8741. if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8742. {
  8743. bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
  8744. bool input_down = IsNavInputDown(ImGuiNavInput_Input);
  8745. bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
  8746. bool input_pressed = input_down && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed);
  8747. if (g.ActiveId == 0 && activate_pressed)
  8748. {
  8749. g.NavActivateId = g.NavId;
  8750. g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
  8751. }
  8752. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
  8753. {
  8754. g.NavActivateInputId = g.NavId;
  8755. g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
  8756. }
  8757. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
  8758. g.NavActivateDownId = g.NavId;
  8759. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
  8760. g.NavActivatePressedId = g.NavId;
  8761. }
  8762. if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8763. g.NavDisableHighlight = true;
  8764. if (g.NavActivateId != 0)
  8765. IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
  8766. // Process programmatic activation request
  8767. // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
  8768. if (g.NavNextActivateId != 0)
  8769. {
  8770. if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)
  8771. g.NavActivateInputId = g.NavNextActivateId;
  8772. else
  8773. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
  8774. g.NavActivateFlags = g.NavNextActivateFlags;
  8775. }
  8776. g.NavNextActivateId = 0;
  8777. // Process move requests
  8778. NavUpdateCreateMoveRequest();
  8779. if (g.NavMoveDir == ImGuiDir_None)
  8780. NavUpdateCreateTabbingRequest();
  8781. NavUpdateAnyRequestFlag();
  8782. g.NavIdIsAlive = false;
  8783. // Scrolling
  8784. if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
  8785. {
  8786. // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
  8787. ImGuiWindow* window = g.NavWindow;
  8788. 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.
  8789. const ImGuiDir move_dir = g.NavMoveDir;
  8790. if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
  8791. {
  8792. if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
  8793. SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
  8794. if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
  8795. SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
  8796. }
  8797. // *Normal* Manual scroll with NavScrollXXX keys
  8798. // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
  8799. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f);
  8800. if (scroll_dir.x != 0.0f && window->ScrollbarX)
  8801. SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
  8802. if (scroll_dir.y != 0.0f)
  8803. SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
  8804. }
  8805. // Always prioritize mouse highlight if navigation is disabled
  8806. if (!nav_keyboard_active && !nav_gamepad_active)
  8807. {
  8808. g.NavDisableHighlight = true;
  8809. g.NavDisableMouseHover = set_mouse_pos = false;
  8810. }
  8811. // Update mouse position if requested
  8812. // (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)
  8813. if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
  8814. {
  8815. io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
  8816. io.WantSetMousePos = true;
  8817. //IMGUI_DEBUG_LOG("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
  8818. }
  8819. // [DEBUG]
  8820. g.NavScoringDebugCount = 0;
  8821. #if IMGUI_DEBUG_NAV_RECTS
  8822. if (g.NavWindow)
  8823. {
  8824. ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
  8825. if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]
  8826. if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
  8827. }
  8828. #endif
  8829. }
  8830. void ImGui::NavInitRequestApplyResult()
  8831. {
  8832. // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
  8833. ImGuiContext& g = *GImGui;
  8834. if (!g.NavWindow)
  8835. return;
  8836. // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
  8837. // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
  8838. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
  8839. SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
  8840. g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
  8841. if (g.NavInitRequestFromMove)
  8842. NavRestoreHighlightAfterMove();
  8843. }
  8844. void ImGui::NavUpdateCreateMoveRequest()
  8845. {
  8846. ImGuiContext& g = *GImGui;
  8847. ImGuiIO& io = g.IO;
  8848. ImGuiWindow* window = g.NavWindow;
  8849. if (g.NavMoveForwardToNextFrame && window != NULL)
  8850. {
  8851. // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
  8852. // (preserve most state, which were already set by the NavMoveRequestForward() function)
  8853. IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
  8854. IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
  8855. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
  8856. }
  8857. else
  8858. {
  8859. // Initiate directional inputs request
  8860. g.NavMoveDir = ImGuiDir_None;
  8861. g.NavMoveFlags = ImGuiNavMoveFlags_None;
  8862. g.NavMoveScrollFlags = ImGuiScrollFlags_None;
  8863. if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
  8864. {
  8865. const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
  8866. if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
  8867. if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
  8868. if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
  8869. if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
  8870. }
  8871. g.NavMoveClipDir = g.NavMoveDir;
  8872. g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
  8873. }
  8874. // Update PageUp/PageDown/Home/End scroll
  8875. // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
  8876. const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  8877. float scoring_rect_offset_y = 0.0f;
  8878. if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
  8879. scoring_rect_offset_y = NavUpdatePageUpPageDown();
  8880. if (scoring_rect_offset_y != 0.0f)
  8881. {
  8882. g.NavScoringNoClipRect = window->InnerRect;
  8883. g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
  8884. }
  8885. // [DEBUG] Always send a request
  8886. #if IMGUI_DEBUG_NAV_SCORING
  8887. if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
  8888. g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
  8889. if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
  8890. {
  8891. g.NavMoveDir = g.NavMoveDirForDebug;
  8892. g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
  8893. }
  8894. #endif
  8895. // Submit
  8896. g.NavMoveForwardToNextFrame = false;
  8897. if (g.NavMoveDir != ImGuiDir_None)
  8898. NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
  8899. // Moving with no reference triggers a init request (will be used as a fallback if the direction fails to find a match)
  8900. if (g.NavMoveSubmitted && g.NavId == 0)
  8901. {
  8902. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
  8903. g.NavInitRequest = g.NavInitRequestFromMove = true;
  8904. g.NavInitResultId = 0;
  8905. g.NavDisableHighlight = false;
  8906. }
  8907. // When using gamepad, we project the reference nav bounding box into window visible area.
  8908. // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative
  8909. // (can't focus a visible object like we can with the mouse).
  8910. if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)
  8911. {
  8912. ImRect window_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
  8913. if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
  8914. {
  8915. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel\n");
  8916. float pad = window->CalcFontSize() * 0.5f;
  8917. window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
  8918. window->NavRectRel[g.NavLayer].ClipWithFull(window_rect_rel);
  8919. g.NavId = g.NavFocusScopeId = 0;
  8920. }
  8921. }
  8922. // 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)
  8923. ImRect scoring_rect;
  8924. if (window != NULL)
  8925. {
  8926. ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
  8927. scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
  8928. scoring_rect.TranslateY(scoring_rect_offset_y);
  8929. scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
  8930. scoring_rect.Max.x = scoring_rect.Min.x;
  8931. IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
  8932. //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
  8933. //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
  8934. }
  8935. g.NavScoringRect = scoring_rect;
  8936. g.NavScoringNoClipRect.Add(scoring_rect);
  8937. }
  8938. void ImGui::NavUpdateCreateTabbingRequest()
  8939. {
  8940. ImGuiContext& g = *GImGui;
  8941. ImGuiWindow* window = g.NavWindow;
  8942. IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
  8943. if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
  8944. return;
  8945. const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, true) && !IsActiveIdUsingKey(ImGuiKey_Tab) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
  8946. if (!tab_pressed)
  8947. return;
  8948. // Initiate tabbing request
  8949. // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
  8950. // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
  8951. // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
  8952. //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything
  8953. g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
  8954. ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
  8955. ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
  8956. NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
  8957. g.NavTabbingResultFirst.Clear();
  8958. g.NavTabbingCounter = -1;
  8959. }
  8960. // Apply result from previous frame navigation directional move request. Always called from NavUpdate()
  8961. void ImGui::NavMoveRequestApplyResult()
  8962. {
  8963. ImGuiContext& g = *GImGui;
  8964. #if IMGUI_DEBUG_NAV_SCORING
  8965. if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
  8966. return;
  8967. #endif
  8968. // Select which result to use
  8969. ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
  8970. // Tabbing forward wrap
  8971. if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
  8972. if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
  8973. result = &g.NavTabbingResultFirst;
  8974. // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
  8975. if (result == NULL)
  8976. {
  8977. if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
  8978. g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
  8979. if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
  8980. NavRestoreHighlightAfterMove();
  8981. return;
  8982. }
  8983. // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
  8984. if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
  8985. if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
  8986. result = &g.NavMoveResultLocalVisible;
  8987. // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
  8988. if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
  8989. if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
  8990. result = &g.NavMoveResultOther;
  8991. IM_ASSERT(g.NavWindow && result->Window);
  8992. // Scroll to keep newly navigated item fully into view.
  8993. if (g.NavLayer == ImGuiNavLayer_Main)
  8994. {
  8995. if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
  8996. {
  8997. // FIXME: Should remove this
  8998. float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
  8999. SetScrollY(result->Window, scroll_target);
  9000. }
  9001. else
  9002. {
  9003. ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
  9004. ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
  9005. }
  9006. }
  9007. g.NavWindow = result->Window;
  9008. if (g.ActiveId != result->ID)
  9009. ClearActiveID();
  9010. if (g.NavId != result->ID)
  9011. {
  9012. // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
  9013. g.NavJustMovedToId = result->ID;
  9014. g.NavJustMovedToFocusScopeId = result->FocusScopeId;
  9015. g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
  9016. }
  9017. // Focus
  9018. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
  9019. SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
  9020. // Tabbing: Activates Inputable or Focus non-Inputable
  9021. if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
  9022. {
  9023. g.NavNextActivateId = result->ID;
  9024. g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
  9025. g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
  9026. }
  9027. // Activate
  9028. if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
  9029. {
  9030. g.NavNextActivateId = result->ID;
  9031. g.NavNextActivateFlags = ImGuiActivateFlags_None;
  9032. }
  9033. // Enable nav highlight
  9034. if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
  9035. NavRestoreHighlightAfterMove();
  9036. }
  9037. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  9038. // FIXME: In order to support e.g. Escape to clear a selection we'll need:
  9039. // - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
  9040. // - 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
  9041. static void ImGui::NavUpdateCancelRequest()
  9042. {
  9043. ImGuiContext& g = *GImGui;
  9044. if (!IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
  9045. return;
  9046. IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n");
  9047. if (g.ActiveId != 0)
  9048. {
  9049. if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
  9050. ClearActiveID();
  9051. }
  9052. else if (g.NavLayer != ImGuiNavLayer_Main)
  9053. {
  9054. // Leave the "menu" layer
  9055. NavRestoreLayer(ImGuiNavLayer_Main);
  9056. NavRestoreHighlightAfterMove();
  9057. }
  9058. else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
  9059. {
  9060. // Exit child window
  9061. ImGuiWindow* child_window = g.NavWindow;
  9062. ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
  9063. IM_ASSERT(child_window->ChildId != 0);
  9064. ImRect child_rect = child_window->Rect();
  9065. FocusWindow(parent_window);
  9066. SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
  9067. NavRestoreHighlightAfterMove();
  9068. }
  9069. else if (g.OpenPopupStack.Size > 0)
  9070. {
  9071. // Close open popup/menu
  9072. if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
  9073. ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
  9074. }
  9075. else
  9076. {
  9077. // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
  9078. if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
  9079. g.NavWindow->NavLastIds[0] = 0;
  9080. g.NavId = g.NavFocusScopeId = 0;
  9081. }
  9082. }
  9083. // Handle PageUp/PageDown/Home/End keys
  9084. // Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
  9085. // FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
  9086. // FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
  9087. static float ImGui::NavUpdatePageUpPageDown()
  9088. {
  9089. ImGuiContext& g = *GImGui;
  9090. ImGuiWindow* window = g.NavWindow;
  9091. if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
  9092. return 0.0f;
  9093. const bool page_up_held = IsKeyDown(ImGuiKey_PageUp) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
  9094. const bool page_down_held = IsKeyDown(ImGuiKey_PageDown) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
  9095. const bool home_pressed = IsKeyPressed(ImGuiKey_Home) && !IsActiveIdUsingKey(ImGuiKey_Home);
  9096. const bool end_pressed = IsKeyPressed(ImGuiKey_End) && !IsActiveIdUsingKey(ImGuiKey_End);
  9097. if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
  9098. return 0.0f;
  9099. if (g.NavLayer != ImGuiNavLayer_Main)
  9100. NavRestoreLayer(ImGuiNavLayer_Main);
  9101. if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
  9102. {
  9103. // Fallback manual-scroll when window has no navigable item
  9104. if (IsKeyPressed(ImGuiKey_PageUp, true))
  9105. SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
  9106. else if (IsKeyPressed(ImGuiKey_PageDown, true))
  9107. SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
  9108. else if (home_pressed)
  9109. SetScrollY(window, 0.0f);
  9110. else if (end_pressed)
  9111. SetScrollY(window, window->ScrollMax.y);
  9112. }
  9113. else
  9114. {
  9115. ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
  9116. const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
  9117. float nav_scoring_rect_offset_y = 0.0f;
  9118. if (IsKeyPressed(ImGuiKey_PageUp, true))
  9119. {
  9120. nav_scoring_rect_offset_y = -page_offset_y;
  9121. 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)
  9122. g.NavMoveClipDir = ImGuiDir_Up;
  9123. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  9124. }
  9125. else if (IsKeyPressed(ImGuiKey_PageDown, true))
  9126. {
  9127. nav_scoring_rect_offset_y = +page_offset_y;
  9128. 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)
  9129. g.NavMoveClipDir = ImGuiDir_Down;
  9130. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  9131. }
  9132. else if (home_pressed)
  9133. {
  9134. // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
  9135. // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
  9136. // Preserve current horizontal position if we have any.
  9137. nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
  9138. if (nav_rect_rel.IsInverted())
  9139. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  9140. g.NavMoveDir = ImGuiDir_Down;
  9141. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
  9142. // FIXME-NAV: MoveClipDir left to _None, intentional?
  9143. }
  9144. else if (end_pressed)
  9145. {
  9146. nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
  9147. if (nav_rect_rel.IsInverted())
  9148. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  9149. g.NavMoveDir = ImGuiDir_Up;
  9150. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
  9151. // FIXME-NAV: MoveClipDir left to _None, intentional?
  9152. }
  9153. return nav_scoring_rect_offset_y;
  9154. }
  9155. return 0.0f;
  9156. }
  9157. static void ImGui::NavEndFrame()
  9158. {
  9159. ImGuiContext& g = *GImGui;
  9160. // Show CTRL+TAB list window
  9161. if (g.NavWindowingTarget != NULL)
  9162. NavUpdateWindowingOverlay();
  9163. // Perform wrap-around in menus
  9164. // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
  9165. // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
  9166. const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
  9167. if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
  9168. NavUpdateCreateWrappingRequest();
  9169. }
  9170. static void ImGui::NavUpdateCreateWrappingRequest()
  9171. {
  9172. ImGuiContext& g = *GImGui;
  9173. ImGuiWindow* window = g.NavWindow;
  9174. bool do_forward = false;
  9175. ImRect bb_rel = window->NavRectRel[g.NavLayer];
  9176. ImGuiDir clip_dir = g.NavMoveDir;
  9177. const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
  9178. if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  9179. {
  9180. bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
  9181. if (move_flags & ImGuiNavMoveFlags_WrapX)
  9182. {
  9183. bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
  9184. clip_dir = ImGuiDir_Up;
  9185. }
  9186. do_forward = true;
  9187. }
  9188. if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  9189. {
  9190. bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
  9191. if (move_flags & ImGuiNavMoveFlags_WrapX)
  9192. {
  9193. bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
  9194. clip_dir = ImGuiDir_Down;
  9195. }
  9196. do_forward = true;
  9197. }
  9198. if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  9199. {
  9200. bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
  9201. if (move_flags & ImGuiNavMoveFlags_WrapY)
  9202. {
  9203. bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
  9204. clip_dir = ImGuiDir_Left;
  9205. }
  9206. do_forward = true;
  9207. }
  9208. if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  9209. {
  9210. bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
  9211. if (move_flags & ImGuiNavMoveFlags_WrapY)
  9212. {
  9213. bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
  9214. clip_dir = ImGuiDir_Right;
  9215. }
  9216. do_forward = true;
  9217. }
  9218. if (!do_forward)
  9219. return;
  9220. window->NavRectRel[g.NavLayer] = bb_rel;
  9221. NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
  9222. }
  9223. static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
  9224. {
  9225. ImGuiContext& g = *GImGui;
  9226. IM_UNUSED(g);
  9227. int order = window->FocusOrder;
  9228. IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
  9229. IM_ASSERT(g.WindowsFocusOrder[order] == window);
  9230. return order;
  9231. }
  9232. static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
  9233. {
  9234. ImGuiContext& g = *GImGui;
  9235. for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
  9236. if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
  9237. return g.WindowsFocusOrder[i];
  9238. return NULL;
  9239. }
  9240. static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
  9241. {
  9242. ImGuiContext& g = *GImGui;
  9243. IM_ASSERT(g.NavWindowingTarget);
  9244. if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
  9245. return;
  9246. const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
  9247. ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
  9248. if (!window_target)
  9249. window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
  9250. if (window_target) // Don't reset windowing target if there's a single window in the list
  9251. g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
  9252. g.NavWindowingToggleLayer = false;
  9253. }
  9254. // Windowing management mode
  9255. // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
  9256. // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
  9257. static void ImGui::NavUpdateWindowing()
  9258. {
  9259. ImGuiContext& g = *GImGui;
  9260. ImGuiIO& io = g.IO;
  9261. ImGuiWindow* apply_focus_window = NULL;
  9262. bool apply_toggle_layer = false;
  9263. ImGuiWindow* modal_window = GetTopMostPopupModal();
  9264. bool allow_windowing = (modal_window == NULL);
  9265. if (!allow_windowing)
  9266. g.NavWindowingTarget = NULL;
  9267. // Fade out
  9268. if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
  9269. {
  9270. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
  9271. if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
  9272. g.NavWindowingTargetAnim = NULL;
  9273. }
  9274. // Start CTRL+Tab or Square+L/R window selection
  9275. const bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
  9276. const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && io.KeyCtrl && IsKeyPressed(ImGuiKey_Tab);
  9277. if (start_windowing_with_gamepad || start_windowing_with_keyboard)
  9278. if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
  9279. {
  9280. g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
  9281. g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
  9282. g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
  9283. g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
  9284. }
  9285. // Gamepad update
  9286. g.NavWindowingTimer += io.DeltaTime;
  9287. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
  9288. {
  9289. // 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
  9290. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
  9291. // Select window to focus
  9292. const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
  9293. if (focus_change_dir != 0)
  9294. {
  9295. NavUpdateWindowingHighlightWindow(focus_change_dir);
  9296. g.NavWindowingHighlightAlpha = 1.0f;
  9297. }
  9298. // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
  9299. if (!IsNavInputDown(ImGuiNavInput_Menu))
  9300. {
  9301. g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
  9302. if (g.NavWindowingToggleLayer && g.NavWindow)
  9303. apply_toggle_layer = true;
  9304. else if (!g.NavWindowingToggleLayer)
  9305. apply_focus_window = g.NavWindowingTarget;
  9306. g.NavWindowingTarget = NULL;
  9307. }
  9308. }
  9309. // Keyboard: Focus
  9310. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
  9311. {
  9312. // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
  9313. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
  9314. if (IsKeyPressed(ImGuiKey_Tab, true))
  9315. NavUpdateWindowingHighlightWindow(io.KeyShift ? +1 : -1);
  9316. if (!io.KeyCtrl)
  9317. apply_focus_window = g.NavWindowingTarget;
  9318. }
  9319. // Keyboard: Press and Release ALT to toggle menu layer
  9320. // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
  9321. // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
  9322. const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  9323. if (nav_keyboard_active && io.KeyMods == ImGuiKeyModFlags_Alt && (io.KeyModsPrev & ImGuiKeyModFlags_Alt) == 0)
  9324. {
  9325. g.NavWindowingToggleLayer = true;
  9326. g.NavInputSource = ImGuiInputSource_Keyboard;
  9327. }
  9328. if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
  9329. {
  9330. // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
  9331. // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
  9332. if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
  9333. g.NavWindowingToggleLayer = false;
  9334. // Apply layer toggle on release
  9335. // Important: we don't assume that Alt was previously held in order to handle loss of focus when backend calls io.AddFocusEvent(false)
  9336. // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
  9337. if (!(io.KeyMods & ImGuiKeyModFlags_Alt) && (io.KeyModsPrev & ImGuiKeyModFlags_Alt) && g.NavWindowingToggleLayer)
  9338. if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
  9339. if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
  9340. apply_toggle_layer = true;
  9341. if (!io.KeyAlt)
  9342. g.NavWindowingToggleLayer = false;
  9343. }
  9344. // Move window
  9345. if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
  9346. {
  9347. ImVec2 move_delta;
  9348. if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
  9349. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_RawKeyboard, ImGuiInputReadMode_Down);
  9350. if (g.NavInputSource == ImGuiInputSource_Gamepad)
  9351. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
  9352. if (move_delta.x != 0.0f || move_delta.y != 0.0f)
  9353. {
  9354. const float NAV_MOVE_SPEED = 800.0f;
  9355. const float move_speed = ImFloor(NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well
  9356. ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
  9357. SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always);
  9358. MarkIniSettingsDirty(moving_window);
  9359. g.NavDisableMouseHover = true;
  9360. }
  9361. }
  9362. // Apply final focus
  9363. if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
  9364. {
  9365. ClearActiveID();
  9366. NavRestoreHighlightAfterMove();
  9367. apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
  9368. ClosePopupsOverWindow(apply_focus_window, false);
  9369. FocusWindow(apply_focus_window);
  9370. if (apply_focus_window->NavLastIds[0] == 0)
  9371. NavInitWindow(apply_focus_window, false);
  9372. // If the window has ONLY a menu layer (no main layer), select it directly
  9373. // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
  9374. // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
  9375. // the target window as already been previewed once.
  9376. // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
  9377. // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
  9378. // won't be valid.
  9379. if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
  9380. g.NavLayer = ImGuiNavLayer_Menu;
  9381. }
  9382. if (apply_focus_window)
  9383. g.NavWindowingTarget = NULL;
  9384. // Apply menu/layer toggle
  9385. if (apply_toggle_layer && g.NavWindow)
  9386. {
  9387. ClearActiveID();
  9388. // Move to parent menu if necessary
  9389. ImGuiWindow* new_nav_window = g.NavWindow;
  9390. while (new_nav_window->ParentWindow
  9391. && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
  9392. && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
  9393. && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  9394. new_nav_window = new_nav_window->ParentWindow;
  9395. if (new_nav_window != g.NavWindow)
  9396. {
  9397. ImGuiWindow* old_nav_window = g.NavWindow;
  9398. FocusWindow(new_nav_window);
  9399. new_nav_window->NavLastChildNavWindow = old_nav_window;
  9400. }
  9401. // Toggle layer
  9402. const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
  9403. if (new_nav_layer != g.NavLayer)
  9404. {
  9405. // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
  9406. if (new_nav_layer == ImGuiNavLayer_Menu)
  9407. g.NavWindow->NavLastIds[new_nav_layer] = 0;
  9408. NavRestoreLayer(new_nav_layer);
  9409. NavRestoreHighlightAfterMove();
  9410. }
  9411. }
  9412. }
  9413. // Window has already passed the IsWindowNavFocusable()
  9414. static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
  9415. {
  9416. if (window->Flags & ImGuiWindowFlags_Popup)
  9417. return "(Popup)";
  9418. if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
  9419. return "(Main menu bar)";
  9420. return "(Untitled)";
  9421. }
  9422. // Overlay displayed when using CTRL+TAB. Called by EndFrame().
  9423. void ImGui::NavUpdateWindowingOverlay()
  9424. {
  9425. ImGuiContext& g = *GImGui;
  9426. IM_ASSERT(g.NavWindowingTarget != NULL);
  9427. if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
  9428. return;
  9429. if (g.NavWindowingListWindow == NULL)
  9430. g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
  9431. const ImGuiViewport* viewport = GetMainViewport();
  9432. SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
  9433. SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
  9434. PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
  9435. Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
  9436. for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
  9437. {
  9438. ImGuiWindow* window = g.WindowsFocusOrder[n];
  9439. IM_ASSERT(window != NULL); // Fix static analyzers
  9440. if (!IsWindowNavFocusable(window))
  9441. continue;
  9442. const char* label = window->Name;
  9443. if (label == FindRenderedTextEnd(label))
  9444. label = GetFallbackWindowNameForWindowingList(window);
  9445. Selectable(label, g.NavWindowingTarget == window);
  9446. }
  9447. End();
  9448. PopStyleVar();
  9449. }
  9450. //-----------------------------------------------------------------------------
  9451. // [SECTION] DRAG AND DROP
  9452. //-----------------------------------------------------------------------------
  9453. void ImGui::ClearDragDrop()
  9454. {
  9455. ImGuiContext& g = *GImGui;
  9456. g.DragDropActive = false;
  9457. g.DragDropPayload.Clear();
  9458. g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
  9459. g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
  9460. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  9461. g.DragDropAcceptFrameCount = -1;
  9462. g.DragDropPayloadBufHeap.clear();
  9463. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  9464. }
  9465. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
  9466. // If the item has an identifier:
  9467. // - This assume/require the item to be activated (typically via ButtonBehavior).
  9468. // - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
  9469. // - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
  9470. // If the item has no identifier:
  9471. // - Currently always assume left mouse button.
  9472. bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
  9473. {
  9474. ImGuiContext& g = *GImGui;
  9475. ImGuiWindow* window = g.CurrentWindow;
  9476. // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
  9477. // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
  9478. ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
  9479. bool source_drag_active = false;
  9480. ImGuiID source_id = 0;
  9481. ImGuiID source_parent_id = 0;
  9482. if (!(flags & ImGuiDragDropFlags_SourceExtern))
  9483. {
  9484. source_id = g.LastItemData.ID;
  9485. if (source_id != 0)
  9486. {
  9487. // Common path: items with ID
  9488. if (g.ActiveId != source_id)
  9489. return false;
  9490. if (g.ActiveIdMouseButton != -1)
  9491. mouse_button = g.ActiveIdMouseButton;
  9492. if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
  9493. return false;
  9494. g.ActiveIdAllowOverlap = false;
  9495. }
  9496. else
  9497. {
  9498. // Uncommon path: items without ID
  9499. if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
  9500. return false;
  9501. if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
  9502. return false;
  9503. // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
  9504. // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
  9505. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
  9506. {
  9507. IM_ASSERT(0);
  9508. return false;
  9509. }
  9510. // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
  9511. // We build a throwaway ID based on current ID stack + relative AABB of items in window.
  9512. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
  9513. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
  9514. // Rely on keeping other window->LastItemXXX fields intact.
  9515. source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
  9516. bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
  9517. if (is_hovered && g.IO.MouseClicked[mouse_button])
  9518. {
  9519. SetActiveID(source_id, window);
  9520. FocusWindow(window);
  9521. }
  9522. if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
  9523. g.ActiveIdAllowOverlap = is_hovered;
  9524. }
  9525. if (g.ActiveId != source_id)
  9526. return false;
  9527. source_parent_id = window->IDStack.back();
  9528. source_drag_active = IsMouseDragging(mouse_button);
  9529. // Disable navigation and key inputs while dragging + cancel existing request if any
  9530. SetActiveIdUsingNavAndKeys();
  9531. }
  9532. else
  9533. {
  9534. window = NULL;
  9535. source_id = ImHashStr("#SourceExtern");
  9536. source_drag_active = true;
  9537. }
  9538. if (source_drag_active)
  9539. {
  9540. if (!g.DragDropActive)
  9541. {
  9542. IM_ASSERT(source_id != 0);
  9543. ClearDragDrop();
  9544. ImGuiPayload& payload = g.DragDropPayload;
  9545. payload.SourceId = source_id;
  9546. payload.SourceParentId = source_parent_id;
  9547. g.DragDropActive = true;
  9548. g.DragDropSourceFlags = flags;
  9549. g.DragDropMouseButton = mouse_button;
  9550. if (payload.SourceId == g.ActiveId)
  9551. g.ActiveIdNoClearOnFocusLoss = true;
  9552. }
  9553. g.DragDropSourceFrameCount = g.FrameCount;
  9554. g.DragDropWithinSource = true;
  9555. if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  9556. {
  9557. // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
  9558. // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
  9559. BeginTooltip();
  9560. if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
  9561. {
  9562. ImGuiWindow* tooltip_window = g.CurrentWindow;
  9563. tooltip_window->Hidden = tooltip_window->SkipItems = true;
  9564. tooltip_window->HiddenFramesCanSkipItems = 1;
  9565. }
  9566. }
  9567. if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
  9568. g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
  9569. return true;
  9570. }
  9571. return false;
  9572. }
  9573. void ImGui::EndDragDropSource()
  9574. {
  9575. ImGuiContext& g = *GImGui;
  9576. IM_ASSERT(g.DragDropActive);
  9577. IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
  9578. if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  9579. EndTooltip();
  9580. // Discard the drag if have not called SetDragDropPayload()
  9581. if (g.DragDropPayload.DataFrameCount == -1)
  9582. ClearDragDrop();
  9583. g.DragDropWithinSource = false;
  9584. }
  9585. // Use 'cond' to choose to submit payload on drag start or every frame
  9586. bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
  9587. {
  9588. ImGuiContext& g = *GImGui;
  9589. ImGuiPayload& payload = g.DragDropPayload;
  9590. if (cond == 0)
  9591. cond = ImGuiCond_Always;
  9592. IM_ASSERT(type != NULL);
  9593. IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
  9594. IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
  9595. IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
  9596. IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
  9597. if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
  9598. {
  9599. // Copy payload
  9600. ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
  9601. g.DragDropPayloadBufHeap.resize(0);
  9602. if (data_size > sizeof(g.DragDropPayloadBufLocal))
  9603. {
  9604. // Store in heap
  9605. g.DragDropPayloadBufHeap.resize((int)data_size);
  9606. payload.Data = g.DragDropPayloadBufHeap.Data;
  9607. memcpy(payload.Data, data, data_size);
  9608. }
  9609. else if (data_size > 0)
  9610. {
  9611. // Store locally
  9612. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  9613. payload.Data = g.DragDropPayloadBufLocal;
  9614. memcpy(payload.Data, data, data_size);
  9615. }
  9616. else
  9617. {
  9618. payload.Data = NULL;
  9619. }
  9620. payload.DataSize = (int)data_size;
  9621. }
  9622. payload.DataFrameCount = g.FrameCount;
  9623. // Return whether the payload has been accepted
  9624. return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
  9625. }
  9626. bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
  9627. {
  9628. ImGuiContext& g = *GImGui;
  9629. if (!g.DragDropActive)
  9630. return false;
  9631. ImGuiWindow* window = g.CurrentWindow;
  9632. ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
  9633. if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
  9634. return false;
  9635. IM_ASSERT(id != 0);
  9636. if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
  9637. return false;
  9638. if (window->SkipItems)
  9639. return false;
  9640. IM_ASSERT(g.DragDropWithinTarget == false);
  9641. g.DragDropTargetRect = bb;
  9642. g.DragDropTargetId = id;
  9643. g.DragDropWithinTarget = true;
  9644. return true;
  9645. }
  9646. // We don't use BeginDragDropTargetCustom() and duplicate its code because:
  9647. // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
  9648. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
  9649. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
  9650. bool ImGui::BeginDragDropTarget()
  9651. {
  9652. ImGuiContext& g = *GImGui;
  9653. if (!g.DragDropActive)
  9654. return false;
  9655. ImGuiWindow* window = g.CurrentWindow;
  9656. if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
  9657. return false;
  9658. ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
  9659. if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems)
  9660. return false;
  9661. const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
  9662. ImGuiID id = g.LastItemData.ID;
  9663. if (id == 0)
  9664. id = window->GetIDFromRectangle(display_rect);
  9665. if (g.DragDropPayload.SourceId == id)
  9666. return false;
  9667. IM_ASSERT(g.DragDropWithinTarget == false);
  9668. g.DragDropTargetRect = display_rect;
  9669. g.DragDropTargetId = id;
  9670. g.DragDropWithinTarget = true;
  9671. return true;
  9672. }
  9673. bool ImGui::IsDragDropPayloadBeingAccepted()
  9674. {
  9675. ImGuiContext& g = *GImGui;
  9676. return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
  9677. }
  9678. const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
  9679. {
  9680. ImGuiContext& g = *GImGui;
  9681. ImGuiWindow* window = g.CurrentWindow;
  9682. ImGuiPayload& payload = g.DragDropPayload;
  9683. IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
  9684. IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
  9685. if (type != NULL && !payload.IsDataType(type))
  9686. return NULL;
  9687. // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
  9688. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
  9689. const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
  9690. ImRect r = g.DragDropTargetRect;
  9691. float r_surface = r.GetWidth() * r.GetHeight();
  9692. if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
  9693. {
  9694. g.DragDropAcceptFlags = flags;
  9695. g.DragDropAcceptIdCurr = g.DragDropTargetId;
  9696. g.DragDropAcceptIdCurrRectSurface = r_surface;
  9697. }
  9698. // Render default drop visuals
  9699. // FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
  9700. payload.Preview = was_accepted_previously;
  9701. flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
  9702. if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
  9703. window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
  9704. g.DragDropAcceptFrameCount = g.FrameCount;
  9705. 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()
  9706. if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
  9707. return NULL;
  9708. return &payload;
  9709. }
  9710. const ImGuiPayload* ImGui::GetDragDropPayload()
  9711. {
  9712. ImGuiContext& g = *GImGui;
  9713. return g.DragDropActive ? &g.DragDropPayload : NULL;
  9714. }
  9715. // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
  9716. void ImGui::EndDragDropTarget()
  9717. {
  9718. ImGuiContext& g = *GImGui;
  9719. IM_ASSERT(g.DragDropActive);
  9720. IM_ASSERT(g.DragDropWithinTarget);
  9721. g.DragDropWithinTarget = false;
  9722. }
  9723. //-----------------------------------------------------------------------------
  9724. // [SECTION] LOGGING/CAPTURING
  9725. //-----------------------------------------------------------------------------
  9726. // All text output from the interface can be captured into tty/file/clipboard.
  9727. // By default, tree nodes are automatically opened during logging.
  9728. //-----------------------------------------------------------------------------
  9729. // Pass text data straight to log (without being displayed)
  9730. static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
  9731. {
  9732. if (g.LogFile)
  9733. {
  9734. g.LogBuffer.Buf.resize(0);
  9735. g.LogBuffer.appendfv(fmt, args);
  9736. ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
  9737. }
  9738. else
  9739. {
  9740. g.LogBuffer.appendfv(fmt, args);
  9741. }
  9742. }
  9743. void ImGui::LogText(const char* fmt, ...)
  9744. {
  9745. ImGuiContext& g = *GImGui;
  9746. if (!g.LogEnabled)
  9747. return;
  9748. va_list args;
  9749. va_start(args, fmt);
  9750. LogTextV(g, fmt, args);
  9751. va_end(args);
  9752. }
  9753. void ImGui::LogTextV(const char* fmt, va_list args)
  9754. {
  9755. ImGuiContext& g = *GImGui;
  9756. if (!g.LogEnabled)
  9757. return;
  9758. LogTextV(g, fmt, args);
  9759. }
  9760. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  9761. // We split text into individual lines to add current tree level padding
  9762. // FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
  9763. void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
  9764. {
  9765. ImGuiContext& g = *GImGui;
  9766. ImGuiWindow* window = g.CurrentWindow;
  9767. const char* prefix = g.LogNextPrefix;
  9768. const char* suffix = g.LogNextSuffix;
  9769. g.LogNextPrefix = g.LogNextSuffix = NULL;
  9770. if (!text_end)
  9771. text_end = FindRenderedTextEnd(text, text_end);
  9772. const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
  9773. if (ref_pos)
  9774. g.LogLinePosY = ref_pos->y;
  9775. if (log_new_line)
  9776. {
  9777. LogText(IM_NEWLINE);
  9778. g.LogLineFirstItem = true;
  9779. }
  9780. if (prefix)
  9781. LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
  9782. // Re-adjust padding if we have popped out of our starting depth
  9783. if (g.LogDepthRef > window->DC.TreeDepth)
  9784. g.LogDepthRef = window->DC.TreeDepth;
  9785. const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
  9786. const char* text_remaining = text;
  9787. for (;;)
  9788. {
  9789. // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
  9790. // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
  9791. const char* line_start = text_remaining;
  9792. const char* line_end = ImStreolRange(line_start, text_end);
  9793. const bool is_last_line = (line_end == text_end);
  9794. if (line_start != line_end || !is_last_line)
  9795. {
  9796. const int line_length = (int)(line_end - line_start);
  9797. const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
  9798. LogText("%*s%.*s", indentation, "", line_length, line_start);
  9799. g.LogLineFirstItem = false;
  9800. if (*line_end == '\n')
  9801. {
  9802. LogText(IM_NEWLINE);
  9803. g.LogLineFirstItem = true;
  9804. }
  9805. }
  9806. if (is_last_line)
  9807. break;
  9808. text_remaining = line_end + 1;
  9809. }
  9810. if (suffix)
  9811. LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
  9812. }
  9813. // Start logging/capturing text output
  9814. void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
  9815. {
  9816. ImGuiContext& g = *GImGui;
  9817. ImGuiWindow* window = g.CurrentWindow;
  9818. IM_ASSERT(g.LogEnabled == false);
  9819. IM_ASSERT(g.LogFile == NULL);
  9820. IM_ASSERT(g.LogBuffer.empty());
  9821. g.LogEnabled = true;
  9822. g.LogType = type;
  9823. g.LogNextPrefix = g.LogNextSuffix = NULL;
  9824. g.LogDepthRef = window->DC.TreeDepth;
  9825. g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
  9826. g.LogLinePosY = FLT_MAX;
  9827. g.LogLineFirstItem = true;
  9828. }
  9829. // Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
  9830. void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
  9831. {
  9832. ImGuiContext& g = *GImGui;
  9833. g.LogNextPrefix = prefix;
  9834. g.LogNextSuffix = suffix;
  9835. }
  9836. void ImGui::LogToTTY(int auto_open_depth)
  9837. {
  9838. ImGuiContext& g = *GImGui;
  9839. if (g.LogEnabled)
  9840. return;
  9841. IM_UNUSED(auto_open_depth);
  9842. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9843. LogBegin(ImGuiLogType_TTY, auto_open_depth);
  9844. g.LogFile = stdout;
  9845. #endif
  9846. }
  9847. // Start logging/capturing text output to given file
  9848. void ImGui::LogToFile(int auto_open_depth, const char* filename)
  9849. {
  9850. ImGuiContext& g = *GImGui;
  9851. if (g.LogEnabled)
  9852. return;
  9853. // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
  9854. // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
  9855. // By opening the file in binary mode "ab" we have consistent output everywhere.
  9856. if (!filename)
  9857. filename = g.IO.LogFilename;
  9858. if (!filename || !filename[0])
  9859. return;
  9860. ImFileHandle f = ImFileOpen(filename, "ab");
  9861. if (!f)
  9862. {
  9863. IM_ASSERT(0);
  9864. return;
  9865. }
  9866. LogBegin(ImGuiLogType_File, auto_open_depth);
  9867. g.LogFile = f;
  9868. }
  9869. // Start logging/capturing text output to clipboard
  9870. void ImGui::LogToClipboard(int auto_open_depth)
  9871. {
  9872. ImGuiContext& g = *GImGui;
  9873. if (g.LogEnabled)
  9874. return;
  9875. LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
  9876. }
  9877. void ImGui::LogToBuffer(int auto_open_depth)
  9878. {
  9879. ImGuiContext& g = *GImGui;
  9880. if (g.LogEnabled)
  9881. return;
  9882. LogBegin(ImGuiLogType_Buffer, auto_open_depth);
  9883. }
  9884. void ImGui::LogFinish()
  9885. {
  9886. ImGuiContext& g = *GImGui;
  9887. if (!g.LogEnabled)
  9888. return;
  9889. LogText(IM_NEWLINE);
  9890. switch (g.LogType)
  9891. {
  9892. case ImGuiLogType_TTY:
  9893. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9894. fflush(g.LogFile);
  9895. #endif
  9896. break;
  9897. case ImGuiLogType_File:
  9898. ImFileClose(g.LogFile);
  9899. break;
  9900. case ImGuiLogType_Buffer:
  9901. break;
  9902. case ImGuiLogType_Clipboard:
  9903. if (!g.LogBuffer.empty())
  9904. SetClipboardText(g.LogBuffer.begin());
  9905. break;
  9906. case ImGuiLogType_None:
  9907. IM_ASSERT(0);
  9908. break;
  9909. }
  9910. g.LogEnabled = false;
  9911. g.LogType = ImGuiLogType_None;
  9912. g.LogFile = NULL;
  9913. g.LogBuffer.clear();
  9914. }
  9915. // Helper to display logging buttons
  9916. // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
  9917. void ImGui::LogButtons()
  9918. {
  9919. ImGuiContext& g = *GImGui;
  9920. PushID("LogButtons");
  9921. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9922. const bool log_to_tty = Button("Log To TTY"); SameLine();
  9923. #else
  9924. const bool log_to_tty = false;
  9925. #endif
  9926. const bool log_to_file = Button("Log To File"); SameLine();
  9927. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  9928. PushAllowKeyboardFocus(false);
  9929. SetNextItemWidth(80.0f);
  9930. SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
  9931. PopAllowKeyboardFocus();
  9932. PopID();
  9933. // Start logging at the end of the function so that the buttons don't appear in the log
  9934. if (log_to_tty)
  9935. LogToTTY();
  9936. if (log_to_file)
  9937. LogToFile();
  9938. if (log_to_clipboard)
  9939. LogToClipboard();
  9940. }
  9941. //-----------------------------------------------------------------------------
  9942. // [SECTION] SETTINGS
  9943. //-----------------------------------------------------------------------------
  9944. // - UpdateSettings() [Internal]
  9945. // - MarkIniSettingsDirty() [Internal]
  9946. // - CreateNewWindowSettings() [Internal]
  9947. // - FindWindowSettings() [Internal]
  9948. // - FindOrCreateWindowSettings() [Internal]
  9949. // - FindSettingsHandler() [Internal]
  9950. // - ClearIniSettings() [Internal]
  9951. // - LoadIniSettingsFromDisk()
  9952. // - LoadIniSettingsFromMemory()
  9953. // - SaveIniSettingsToDisk()
  9954. // - SaveIniSettingsToMemory()
  9955. // - WindowSettingsHandler_***() [Internal]
  9956. //-----------------------------------------------------------------------------
  9957. // Called by NewFrame()
  9958. void ImGui::UpdateSettings()
  9959. {
  9960. // Load settings on first frame (if not explicitly loaded manually before)
  9961. ImGuiContext& g = *GImGui;
  9962. if (!g.SettingsLoaded)
  9963. {
  9964. IM_ASSERT(g.SettingsWindows.empty());
  9965. if (g.IO.IniFilename)
  9966. LoadIniSettingsFromDisk(g.IO.IniFilename);
  9967. g.SettingsLoaded = true;
  9968. }
  9969. // Save settings (with a delay after the last modification, so we don't spam disk too much)
  9970. if (g.SettingsDirtyTimer > 0.0f)
  9971. {
  9972. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  9973. if (g.SettingsDirtyTimer <= 0.0f)
  9974. {
  9975. if (g.IO.IniFilename != NULL)
  9976. SaveIniSettingsToDisk(g.IO.IniFilename);
  9977. else
  9978. g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
  9979. g.SettingsDirtyTimer = 0.0f;
  9980. }
  9981. }
  9982. }
  9983. void ImGui::MarkIniSettingsDirty()
  9984. {
  9985. ImGuiContext& g = *GImGui;
  9986. if (g.SettingsDirtyTimer <= 0.0f)
  9987. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  9988. }
  9989. void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
  9990. {
  9991. ImGuiContext& g = *GImGui;
  9992. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  9993. if (g.SettingsDirtyTimer <= 0.0f)
  9994. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  9995. }
  9996. ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
  9997. {
  9998. ImGuiContext& g = *GImGui;
  9999. #if !IMGUI_DEBUG_INI_SETTINGS
  10000. // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  10001. // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
  10002. if (const char* p = strstr(name, "###"))
  10003. name = p;
  10004. #endif
  10005. const size_t name_len = strlen(name);
  10006. // Allocate chunk
  10007. const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
  10008. ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
  10009. IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
  10010. settings->ID = ImHashStr(name, name_len);
  10011. memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
  10012. return settings;
  10013. }
  10014. ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
  10015. {
  10016. ImGuiContext& g = *GImGui;
  10017. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10018. if (settings->ID == id)
  10019. return settings;
  10020. return NULL;
  10021. }
  10022. ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
  10023. {
  10024. if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
  10025. return settings;
  10026. return CreateNewWindowSettings(name);
  10027. }
  10028. ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
  10029. {
  10030. ImGuiContext& g = *GImGui;
  10031. const ImGuiID type_hash = ImHashStr(type_name);
  10032. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10033. if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
  10034. return &g.SettingsHandlers[handler_n];
  10035. return NULL;
  10036. }
  10037. void ImGui::ClearIniSettings()
  10038. {
  10039. ImGuiContext& g = *GImGui;
  10040. g.SettingsIniData.clear();
  10041. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10042. if (g.SettingsHandlers[handler_n].ClearAllFn)
  10043. g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
  10044. }
  10045. void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
  10046. {
  10047. size_t file_data_size = 0;
  10048. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
  10049. if (!file_data)
  10050. return;
  10051. LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
  10052. IM_FREE(file_data);
  10053. }
  10054. // Zero-tolerance, no error reporting, cheap .ini parsing
  10055. void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
  10056. {
  10057. ImGuiContext& g = *GImGui;
  10058. IM_ASSERT(g.Initialized);
  10059. //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
  10060. //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
  10061. // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
  10062. // 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..
  10063. if (ini_size == 0)
  10064. ini_size = strlen(ini_data);
  10065. g.SettingsIniData.Buf.resize((int)ini_size + 1);
  10066. char* const buf = g.SettingsIniData.Buf.Data;
  10067. char* const buf_end = buf + ini_size;
  10068. memcpy(buf, ini_data, ini_size);
  10069. buf_end[0] = 0;
  10070. // Call pre-read handlers
  10071. // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
  10072. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10073. if (g.SettingsHandlers[handler_n].ReadInitFn)
  10074. g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
  10075. void* entry_data = NULL;
  10076. ImGuiSettingsHandler* entry_handler = NULL;
  10077. char* line_end = NULL;
  10078. for (char* line = buf; line < buf_end; line = line_end + 1)
  10079. {
  10080. // Skip new lines markers, then find end of the line
  10081. while (*line == '\n' || *line == '\r')
  10082. line++;
  10083. line_end = line;
  10084. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  10085. line_end++;
  10086. line_end[0] = 0;
  10087. if (line[0] == ';')
  10088. continue;
  10089. if (line[0] == '[' && line_end > line && line_end[-1] == ']')
  10090. {
  10091. // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
  10092. line_end[-1] = 0;
  10093. const char* name_end = line_end - 1;
  10094. const char* type_start = line + 1;
  10095. char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
  10096. const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
  10097. if (!type_end || !name_start)
  10098. continue;
  10099. *type_end = 0; // Overwrite first ']'
  10100. name_start++; // Skip second '['
  10101. entry_handler = FindSettingsHandler(type_start);
  10102. entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
  10103. }
  10104. else if (entry_handler != NULL && entry_data != NULL)
  10105. {
  10106. // Let type handler parse the line
  10107. entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
  10108. }
  10109. }
  10110. g.SettingsLoaded = true;
  10111. // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
  10112. memcpy(buf, ini_data, ini_size);
  10113. // Call post-read handlers
  10114. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10115. if (g.SettingsHandlers[handler_n].ApplyAllFn)
  10116. g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
  10117. }
  10118. void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
  10119. {
  10120. ImGuiContext& g = *GImGui;
  10121. g.SettingsDirtyTimer = 0.0f;
  10122. if (!ini_filename)
  10123. return;
  10124. size_t ini_data_size = 0;
  10125. const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
  10126. ImFileHandle f = ImFileOpen(ini_filename, "wt");
  10127. if (!f)
  10128. return;
  10129. ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
  10130. ImFileClose(f);
  10131. }
  10132. // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
  10133. const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
  10134. {
  10135. ImGuiContext& g = *GImGui;
  10136. g.SettingsDirtyTimer = 0.0f;
  10137. g.SettingsIniData.Buf.resize(0);
  10138. g.SettingsIniData.Buf.push_back(0);
  10139. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10140. {
  10141. ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
  10142. handler->WriteAllFn(&g, handler, &g.SettingsIniData);
  10143. }
  10144. if (out_size)
  10145. *out_size = (size_t)g.SettingsIniData.size();
  10146. return g.SettingsIniData.c_str();
  10147. }
  10148. static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  10149. {
  10150. ImGuiContext& g = *ctx;
  10151. for (int i = 0; i != g.Windows.Size; i++)
  10152. g.Windows[i]->SettingsOffset = -1;
  10153. g.SettingsWindows.clear();
  10154. }
  10155. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  10156. {
  10157. ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
  10158. ImGuiID id = settings->ID;
  10159. *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
  10160. settings->ID = id;
  10161. settings->WantApply = true;
  10162. return (void*)settings;
  10163. }
  10164. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  10165. {
  10166. ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
  10167. int x, y;
  10168. int i;
  10169. if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
  10170. else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
  10171. else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
  10172. }
  10173. // Apply to existing windows (if any)
  10174. static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  10175. {
  10176. ImGuiContext& g = *ctx;
  10177. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10178. if (settings->WantApply)
  10179. {
  10180. if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
  10181. ApplyWindowSettings(window, settings);
  10182. settings->WantApply = false;
  10183. }
  10184. }
  10185. static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  10186. {
  10187. // Gather data from windows that were active during this session
  10188. // (if a window wasn't opened in this session we preserve its settings)
  10189. ImGuiContext& g = *ctx;
  10190. for (int i = 0; i != g.Windows.Size; i++)
  10191. {
  10192. ImGuiWindow* window = g.Windows[i];
  10193. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  10194. continue;
  10195. ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
  10196. if (!settings)
  10197. {
  10198. settings = ImGui::CreateNewWindowSettings(window->Name);
  10199. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  10200. }
  10201. IM_ASSERT(settings->ID == window->ID);
  10202. settings->Pos = ImVec2ih(window->Pos);
  10203. settings->Size = ImVec2ih(window->SizeFull);
  10204. settings->Collapsed = window->Collapsed;
  10205. }
  10206. // Write to text buffer
  10207. buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
  10208. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10209. {
  10210. const char* settings_name = settings->GetName();
  10211. buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
  10212. buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
  10213. buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
  10214. buf->appendf("Collapsed=%d\n", settings->Collapsed);
  10215. buf->append("\n");
  10216. }
  10217. }
  10218. //-----------------------------------------------------------------------------
  10219. // [SECTION] VIEWPORTS, PLATFORM WINDOWS
  10220. //-----------------------------------------------------------------------------
  10221. // - GetMainViewport()
  10222. // - UpdateViewportsNewFrame() [Internal]
  10223. // (this section is more complete in the 'docking' branch)
  10224. //-----------------------------------------------------------------------------
  10225. ImGuiViewport* ImGui::GetMainViewport()
  10226. {
  10227. ImGuiContext& g = *GImGui;
  10228. return g.Viewports[0];
  10229. }
  10230. // Update viewports and monitor infos
  10231. static void ImGui::UpdateViewportsNewFrame()
  10232. {
  10233. ImGuiContext& g = *GImGui;
  10234. IM_ASSERT(g.Viewports.Size == 1);
  10235. // Update main viewport with current platform position.
  10236. // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
  10237. ImGuiViewportP* main_viewport = g.Viewports[0];
  10238. main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;
  10239. main_viewport->Pos = ImVec2(0.0f, 0.0f);
  10240. main_viewport->Size = g.IO.DisplaySize;
  10241. for (int n = 0; n < g.Viewports.Size; n++)
  10242. {
  10243. ImGuiViewportP* viewport = g.Viewports[n];
  10244. // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again.
  10245. viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
  10246. viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
  10247. viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
  10248. viewport->UpdateWorkRect();
  10249. }
  10250. }
  10251. //-----------------------------------------------------------------------------
  10252. // [SECTION] DOCKING
  10253. //-----------------------------------------------------------------------------
  10254. // (this section is filled in the 'docking' branch)
  10255. //-----------------------------------------------------------------------------
  10256. // [SECTION] PLATFORM DEPENDENT HELPERS
  10257. //-----------------------------------------------------------------------------
  10258. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
  10259. #ifdef _MSC_VER
  10260. #pragma comment(lib, "user32")
  10261. #pragma comment(lib, "kernel32")
  10262. #endif
  10263. // Win32 clipboard implementation
  10264. // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
  10265. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10266. {
  10267. ImGuiContext& g = *GImGui;
  10268. g.ClipboardHandlerData.clear();
  10269. if (!::OpenClipboard(NULL))
  10270. return NULL;
  10271. HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
  10272. if (wbuf_handle == NULL)
  10273. {
  10274. ::CloseClipboard();
  10275. return NULL;
  10276. }
  10277. if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
  10278. {
  10279. int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
  10280. g.ClipboardHandlerData.resize(buf_len);
  10281. ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
  10282. }
  10283. ::GlobalUnlock(wbuf_handle);
  10284. ::CloseClipboard();
  10285. return g.ClipboardHandlerData.Data;
  10286. }
  10287. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10288. {
  10289. if (!::OpenClipboard(NULL))
  10290. return;
  10291. const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
  10292. HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
  10293. if (wbuf_handle == NULL)
  10294. {
  10295. ::CloseClipboard();
  10296. return;
  10297. }
  10298. WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
  10299. ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
  10300. ::GlobalUnlock(wbuf_handle);
  10301. ::EmptyClipboard();
  10302. if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
  10303. ::GlobalFree(wbuf_handle);
  10304. ::CloseClipboard();
  10305. }
  10306. #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
  10307. #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
  10308. static PasteboardRef main_clipboard = 0;
  10309. // OSX clipboard implementation
  10310. // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
  10311. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10312. {
  10313. if (!main_clipboard)
  10314. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  10315. PasteboardClear(main_clipboard);
  10316. CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
  10317. if (cf_data)
  10318. {
  10319. PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
  10320. CFRelease(cf_data);
  10321. }
  10322. }
  10323. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10324. {
  10325. if (!main_clipboard)
  10326. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  10327. PasteboardSynchronize(main_clipboard);
  10328. ItemCount item_count = 0;
  10329. PasteboardGetItemCount(main_clipboard, &item_count);
  10330. for (ItemCount i = 0; i < item_count; i++)
  10331. {
  10332. PasteboardItemID item_id = 0;
  10333. PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
  10334. CFArrayRef flavor_type_array = 0;
  10335. PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
  10336. for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
  10337. {
  10338. CFDataRef cf_data;
  10339. if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
  10340. {
  10341. ImGuiContext& g = *GImGui;
  10342. g.ClipboardHandlerData.clear();
  10343. int length = (int)CFDataGetLength(cf_data);
  10344. g.ClipboardHandlerData.resize(length + 1);
  10345. CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
  10346. g.ClipboardHandlerData[length] = 0;
  10347. CFRelease(cf_data);
  10348. return g.ClipboardHandlerData.Data;
  10349. }
  10350. }
  10351. }
  10352. return NULL;
  10353. }
  10354. #else
  10355. // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
  10356. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10357. {
  10358. ImGuiContext& g = *GImGui;
  10359. return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
  10360. }
  10361. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10362. {
  10363. ImGuiContext& g = *GImGui;
  10364. g.ClipboardHandlerData.clear();
  10365. const char* text_end = text + strlen(text);
  10366. g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
  10367. memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
  10368. g.ClipboardHandlerData[(int)(text_end - text)] = 0;
  10369. }
  10370. #endif
  10371. // Win32 API IME support (for Asian languages, etc.)
  10372. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  10373. #include <imm.h>
  10374. #ifdef _MSC_VER
  10375. #pragma comment(lib, "imm32")
  10376. #endif
  10377. static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
  10378. {
  10379. // Notify OS Input Method Editor of text input position
  10380. HWND hwnd = (HWND)viewport->PlatformHandleRaw;
  10381. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  10382. if (hwnd == 0)
  10383. hwnd = (HWND)ImGui::GetIO().ImeWindowHandle;
  10384. #endif
  10385. if (hwnd == 0)
  10386. return;
  10387. ::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
  10388. if (HIMC himc = ::ImmGetContext(hwnd))
  10389. {
  10390. COMPOSITIONFORM composition_form = {};
  10391. composition_form.ptCurrentPos.x = (LONG)data->InputPos.x;
  10392. composition_form.ptCurrentPos.y = (LONG)data->InputPos.y;
  10393. composition_form.dwStyle = CFS_FORCE_POSITION;
  10394. ::ImmSetCompositionWindow(himc, &composition_form);
  10395. CANDIDATEFORM candidate_form = {};
  10396. candidate_form.dwStyle = CFS_CANDIDATEPOS;
  10397. candidate_form.ptCurrentPos.x = (LONG)data->InputPos.x;
  10398. candidate_form.ptCurrentPos.y = (LONG)data->InputPos.y;
  10399. ::ImmSetCandidateWindow(himc, &candidate_form);
  10400. ::ImmReleaseContext(hwnd, himc);
  10401. }
  10402. }
  10403. #else
  10404. static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
  10405. #endif
  10406. //-----------------------------------------------------------------------------
  10407. // [SECTION] METRICS/DEBUGGER WINDOW
  10408. //-----------------------------------------------------------------------------
  10409. // - RenderViewportThumbnail() [Internal]
  10410. // - RenderViewportsThumbnails() [Internal]
  10411. // - MetricsHelpMarker() [Internal]
  10412. // - ShowMetricsWindow()
  10413. // - DebugNodeColumns() [Internal]
  10414. // - DebugNodeDrawList() [Internal]
  10415. // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
  10416. // - DebugNodeStorage() [Internal]
  10417. // - DebugNodeTabBar() [Internal]
  10418. // - DebugNodeViewport() [Internal]
  10419. // - DebugNodeWindow() [Internal]
  10420. // - DebugNodeWindowSettings() [Internal]
  10421. // - DebugNodeWindowsList() [Internal]
  10422. // - DebugNodeWindowsListByBeginStackParent() [Internal]
  10423. //-----------------------------------------------------------------------------
  10424. #ifndef IMGUI_DISABLE_METRICS_WINDOW
  10425. void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
  10426. {
  10427. ImGuiContext& g = *GImGui;
  10428. ImGuiWindow* window = g.CurrentWindow;
  10429. ImVec2 scale = bb.GetSize() / viewport->Size;
  10430. ImVec2 off = bb.Min - viewport->Pos * scale;
  10431. float alpha_mul = 1.0f;
  10432. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
  10433. for (int i = 0; i != g.Windows.Size; i++)
  10434. {
  10435. ImGuiWindow* thumb_window = g.Windows[i];
  10436. if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
  10437. continue;
  10438. ImRect thumb_r = thumb_window->Rect();
  10439. ImRect title_r = thumb_window->TitleBarRect();
  10440. thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale));
  10441. title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off + ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
  10442. thumb_r.ClipWithFull(bb);
  10443. title_r.ClipWithFull(bb);
  10444. const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
  10445. window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
  10446. window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
  10447. window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
  10448. window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
  10449. }
  10450. draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
  10451. }
  10452. static void RenderViewportsThumbnails()
  10453. {
  10454. ImGuiContext& g = *GImGui;
  10455. ImGuiWindow* window = g.CurrentWindow;
  10456. // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
  10457. float SCALE = 1.0f / 8.0f;
  10458. ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  10459. for (int n = 0; n < g.Viewports.Size; n++)
  10460. bb_full.Add(g.Viewports[n]->GetMainRect());
  10461. ImVec2 p = window->DC.CursorPos;
  10462. ImVec2 off = p - bb_full.Min * SCALE;
  10463. for (int n = 0; n < g.Viewports.Size; n++)
  10464. {
  10465. ImGuiViewportP* viewport = g.Viewports[n];
  10466. ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
  10467. ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
  10468. }
  10469. ImGui::Dummy(bb_full.GetSize() * SCALE);
  10470. }
  10471. // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
  10472. static void MetricsHelpMarker(const char* desc)
  10473. {
  10474. ImGui::TextDisabled("(?)");
  10475. if (ImGui::IsItemHovered())
  10476. {
  10477. ImGui::BeginTooltip();
  10478. ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
  10479. ImGui::TextUnformatted(desc);
  10480. ImGui::PopTextWrapPos();
  10481. ImGui::EndTooltip();
  10482. }
  10483. }
  10484. #ifndef IMGUI_DISABLE_DEMO_WINDOWS
  10485. namespace ImGui { void ShowFontAtlas(ImFontAtlas* atlas); }
  10486. #endif
  10487. void ImGui::ShowMetricsWindow(bool* p_open)
  10488. {
  10489. ImGuiContext& g = *GImGui;
  10490. ImGuiIO& io = g.IO;
  10491. ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
  10492. if (cfg->ShowStackTool)
  10493. ShowStackToolWindow(&cfg->ShowStackTool);
  10494. if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
  10495. {
  10496. End();
  10497. return;
  10498. }
  10499. // Basic info
  10500. Text("Dear ImGui %s", GetVersion());
  10501. Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  10502. Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
  10503. Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
  10504. //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
  10505. Separator();
  10506. // Debugging enums
  10507. enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
  10508. const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
  10509. enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
  10510. const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
  10511. if (cfg->ShowWindowsRectsType < 0)
  10512. cfg->ShowWindowsRectsType = WRT_WorkRect;
  10513. if (cfg->ShowTablesRectsType < 0)
  10514. cfg->ShowTablesRectsType = TRT_WorkRect;
  10515. struct Funcs
  10516. {
  10517. static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
  10518. {
  10519. if (rect_type == TRT_OuterRect) { return table->OuterRect; }
  10520. else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
  10521. else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
  10522. else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
  10523. else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
  10524. else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
  10525. else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); }
  10526. else if (rect_type == TRT_ColumnsWorkRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
  10527. else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
  10528. else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate
  10529. else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
  10530. else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
  10531. else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
  10532. IM_ASSERT(0);
  10533. return ImRect();
  10534. }
  10535. static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
  10536. {
  10537. if (rect_type == WRT_OuterRect) { return window->Rect(); }
  10538. else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
  10539. else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
  10540. else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
  10541. else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
  10542. else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
  10543. else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
  10544. else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
  10545. IM_ASSERT(0);
  10546. return ImRect();
  10547. }
  10548. };
  10549. // Tools
  10550. if (TreeNode("Tools"))
  10551. {
  10552. // Stack Tool is your best friend!
  10553. Checkbox("Show stack tool", &cfg->ShowStackTool);
  10554. SameLine();
  10555. MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
  10556. Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
  10557. Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
  10558. SameLine();
  10559. SetNextItemWidth(GetFontSize() * 12);
  10560. cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
  10561. if (cfg->ShowWindowsRects && g.NavWindow != NULL)
  10562. {
  10563. BulletText("'%s':", g.NavWindow->Name);
  10564. Indent();
  10565. for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
  10566. {
  10567. ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
  10568. Text("(%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(), wrt_rects_names[rect_n]);
  10569. }
  10570. Unindent();
  10571. }
  10572. Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
  10573. SameLine();
  10574. SetNextItemWidth(GetFontSize() * 12);
  10575. cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
  10576. if (cfg->ShowTablesRects && g.NavWindow != NULL)
  10577. {
  10578. for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
  10579. {
  10580. ImGuiTable* table = g.Tables.TryGetMapData(table_n);
  10581. if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
  10582. continue;
  10583. BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
  10584. if (IsItemHovered())
  10585. 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);
  10586. Indent();
  10587. char buf[128];
  10588. for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
  10589. {
  10590. if (rect_n >= TRT_ColumnsRect)
  10591. {
  10592. if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
  10593. continue;
  10594. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  10595. {
  10596. ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
  10597. 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]);
  10598. Selectable(buf);
  10599. if (IsItemHovered())
  10600. GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
  10601. }
  10602. }
  10603. else
  10604. {
  10605. ImRect r = Funcs::GetTableRect(table, rect_n, -1);
  10606. 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]);
  10607. Selectable(buf);
  10608. if (IsItemHovered())
  10609. GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
  10610. }
  10611. }
  10612. Unindent();
  10613. }
  10614. }
  10615. // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
  10616. if (Button("Item Picker.."))
  10617. DebugStartItemPicker();
  10618. SameLine();
  10619. MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
  10620. TreePop();
  10621. }
  10622. // Windows
  10623. if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
  10624. {
  10625. //SetNextItemOpen(true, ImGuiCond_Once);
  10626. DebugNodeWindowsList(&g.Windows, "By display order");
  10627. DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
  10628. if (TreeNode("By submission order (begin stack)"))
  10629. {
  10630. // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
  10631. ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
  10632. temp_buffer.resize(0);
  10633. for (int i = 0; i < g.Windows.Size; i++)
  10634. if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
  10635. temp_buffer.push_back(g.Windows[i]);
  10636. struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
  10637. ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
  10638. DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
  10639. TreePop();
  10640. }
  10641. TreePop();
  10642. }
  10643. // DrawLists
  10644. int drawlist_count = 0;
  10645. for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
  10646. drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
  10647. if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
  10648. {
  10649. Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
  10650. Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
  10651. for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
  10652. {
  10653. ImGuiViewportP* viewport = g.Viewports[viewport_i];
  10654. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  10655. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  10656. DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  10657. }
  10658. TreePop();
  10659. }
  10660. // Viewports
  10661. if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
  10662. {
  10663. Indent(GetTreeNodeToLabelSpacing());
  10664. RenderViewportsThumbnails();
  10665. Unindent(GetTreeNodeToLabelSpacing());
  10666. for (int i = 0; i < g.Viewports.Size; i++)
  10667. DebugNodeViewport(g.Viewports[i]);
  10668. TreePop();
  10669. }
  10670. // Details for Popups
  10671. if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
  10672. {
  10673. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  10674. {
  10675. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  10676. BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
  10677. }
  10678. TreePop();
  10679. }
  10680. // Details for TabBars
  10681. if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
  10682. {
  10683. for (int n = 0; n < g.TabBars.GetMapSize(); n++)
  10684. if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
  10685. {
  10686. PushID(tab_bar);
  10687. DebugNodeTabBar(tab_bar, "TabBar");
  10688. PopID();
  10689. }
  10690. TreePop();
  10691. }
  10692. // Details for Tables
  10693. if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
  10694. {
  10695. for (int n = 0; n < g.Tables.GetMapSize(); n++)
  10696. if (ImGuiTable* table = g.Tables.TryGetMapData(n))
  10697. DebugNodeTable(table);
  10698. TreePop();
  10699. }
  10700. // Details for Fonts
  10701. #ifndef IMGUI_DISABLE_DEMO_WINDOWS
  10702. ImFontAtlas* atlas = g.IO.Fonts;
  10703. if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
  10704. {
  10705. ShowFontAtlas(atlas);
  10706. TreePop();
  10707. }
  10708. #endif
  10709. // Details for Docking
  10710. #ifdef IMGUI_HAS_DOCK
  10711. if (TreeNode("Docking"))
  10712. {
  10713. TreePop();
  10714. }
  10715. #endif // #ifdef IMGUI_HAS_DOCK
  10716. // Settings
  10717. if (TreeNode("Settings"))
  10718. {
  10719. if (SmallButton("Clear"))
  10720. ClearIniSettings();
  10721. SameLine();
  10722. if (SmallButton("Save to memory"))
  10723. SaveIniSettingsToMemory();
  10724. SameLine();
  10725. if (SmallButton("Save to disk"))
  10726. SaveIniSettingsToDisk(g.IO.IniFilename);
  10727. SameLine();
  10728. if (g.IO.IniFilename)
  10729. Text("\"%s\"", g.IO.IniFilename);
  10730. else
  10731. TextUnformatted("<NULL>");
  10732. Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
  10733. if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
  10734. {
  10735. for (int n = 0; n < g.SettingsHandlers.Size; n++)
  10736. BulletText("%s", g.SettingsHandlers[n].TypeName);
  10737. TreePop();
  10738. }
  10739. if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
  10740. {
  10741. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10742. DebugNodeWindowSettings(settings);
  10743. TreePop();
  10744. }
  10745. if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
  10746. {
  10747. for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
  10748. DebugNodeTableSettings(settings);
  10749. TreePop();
  10750. }
  10751. #ifdef IMGUI_HAS_DOCK
  10752. #endif // #ifdef IMGUI_HAS_DOCK
  10753. if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
  10754. {
  10755. InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
  10756. TreePop();
  10757. }
  10758. TreePop();
  10759. }
  10760. // Misc Details
  10761. if (TreeNode("Internal state"))
  10762. {
  10763. const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
  10764. Text("WINDOWING");
  10765. Indent();
  10766. Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  10767. Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL");
  10768. Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
  10769. Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
  10770. Unindent();
  10771. Text("ITEMS");
  10772. Indent();
  10773. Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
  10774. Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  10775. int active_id_using_key_input_count = 0;
  10776. for (int n = 0; n < g.ActiveIdUsingKeyInputMask.Size; n++)
  10777. active_id_using_key_input_count += g.ActiveIdUsingKeyInputMask.TestBit(n) ? 1 : 0;
  10778. Text("ActiveIdUsing: Wheel: %d, NavDirMask: %X, NavInputMask: %X, KeyInputMask: %d key(s)", g.ActiveIdUsingMouseWheel, g.ActiveIdUsingNavDirMask, g.ActiveIdUsingNavInputMask, active_id_using_key_input_count);
  10779. Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
  10780. Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
  10781. Unindent();
  10782. Text("NAV,FOCUS");
  10783. Indent();
  10784. Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  10785. Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
  10786. Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
  10787. Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
  10788. Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);
  10789. Text("NavActivateFlags: %04X", g.NavActivateFlags);
  10790. Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
  10791. Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
  10792. Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
  10793. Unindent();
  10794. TreePop();
  10795. }
  10796. // Overlay: Display windows Rectangles and Begin Order
  10797. if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
  10798. {
  10799. for (int n = 0; n < g.Windows.Size; n++)
  10800. {
  10801. ImGuiWindow* window = g.Windows[n];
  10802. if (!window->WasActive)
  10803. continue;
  10804. ImDrawList* draw_list = GetForegroundDrawList(window);
  10805. if (cfg->ShowWindowsRects)
  10806. {
  10807. ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
  10808. draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
  10809. }
  10810. if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
  10811. {
  10812. char buf[32];
  10813. ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
  10814. float font_size = GetFontSize();
  10815. draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
  10816. draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
  10817. }
  10818. }
  10819. }
  10820. // Overlay: Display Tables Rectangles
  10821. if (cfg->ShowTablesRects)
  10822. {
  10823. for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
  10824. {
  10825. ImGuiTable* table = g.Tables.TryGetMapData(table_n);
  10826. if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
  10827. continue;
  10828. ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
  10829. if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
  10830. {
  10831. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  10832. {
  10833. ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
  10834. ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
  10835. float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
  10836. draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
  10837. }
  10838. }
  10839. else
  10840. {
  10841. ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
  10842. draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
  10843. }
  10844. }
  10845. }
  10846. #ifdef IMGUI_HAS_DOCK
  10847. // Overlay: Display Docking info
  10848. if (show_docking_nodes && g.IO.KeyCtrl)
  10849. {
  10850. }
  10851. #endif // #ifdef IMGUI_HAS_DOCK
  10852. End();
  10853. }
  10854. // [DEBUG] List fonts in a font atlas and display its texture
  10855. void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
  10856. {
  10857. for (int i = 0; i < atlas->Fonts.Size; i++)
  10858. {
  10859. ImFont* font = atlas->Fonts[i];
  10860. PushID(font);
  10861. DebugNodeFont(font);
  10862. PopID();
  10863. }
  10864. if (TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
  10865. {
  10866. ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
  10867. ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
  10868. Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
  10869. TreePop();
  10870. }
  10871. }
  10872. // [DEBUG] Display contents of Columns
  10873. void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
  10874. {
  10875. if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
  10876. return;
  10877. BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
  10878. for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
  10879. BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
  10880. TreePop();
  10881. }
  10882. // [DEBUG] Display contents of ImDrawList
  10883. void ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label)
  10884. {
  10885. ImGuiContext& g = *GImGui;
  10886. ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
  10887. int cmd_count = draw_list->CmdBuffer.Size;
  10888. if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
  10889. cmd_count--;
  10890. bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
  10891. if (draw_list == GetWindowDrawList())
  10892. {
  10893. SameLine();
  10894. TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  10895. if (node_open)
  10896. TreePop();
  10897. return;
  10898. }
  10899. ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
  10900. if (window && IsItemHovered() && fg_draw_list)
  10901. fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  10902. if (!node_open)
  10903. return;
  10904. if (window && !window->WasActive)
  10905. TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
  10906. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
  10907. {
  10908. if (pcmd->UserCallback)
  10909. {
  10910. BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  10911. continue;
  10912. }
  10913. char buf[300];
  10914. ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
  10915. pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
  10916. pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  10917. bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
  10918. if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
  10919. DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
  10920. if (!pcmd_node_open)
  10921. continue;
  10922. // Calculate approximate coverage area (touched pixel count)
  10923. // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
  10924. const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  10925. const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
  10926. float total_area = 0.0f;
  10927. for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
  10928. {
  10929. ImVec2 triangle[3];
  10930. for (int n = 0; n < 3; n++, idx_n++)
  10931. triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
  10932. total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
  10933. }
  10934. // Display vertex information summary. Hover to get all triangles drawn in wire-frame
  10935. ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
  10936. Selectable(buf);
  10937. if (IsItemHovered() && fg_draw_list)
  10938. DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
  10939. // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
  10940. ImGuiListClipper clipper;
  10941. clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  10942. while (clipper.Step())
  10943. for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
  10944. {
  10945. char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
  10946. ImVec2 triangle[3];
  10947. for (int n = 0; n < 3; n++, idx_i++)
  10948. {
  10949. const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
  10950. triangle[n] = v.pos;
  10951. buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
  10952. (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  10953. }
  10954. Selectable(buf, false);
  10955. if (fg_draw_list && IsItemHovered())
  10956. {
  10957. ImDrawListFlags backup_flags = fg_draw_list->Flags;
  10958. fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  10959. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
  10960. fg_draw_list->Flags = backup_flags;
  10961. }
  10962. }
  10963. TreePop();
  10964. }
  10965. TreePop();
  10966. }
  10967. // [DEBUG] Display mesh/aabb of a ImDrawCmd
  10968. void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
  10969. {
  10970. IM_ASSERT(show_mesh || show_aabb);
  10971. // Draw wire-frame version of all triangles
  10972. ImRect clip_rect = draw_cmd->ClipRect;
  10973. ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  10974. ImDrawListFlags backup_flags = out_draw_list->Flags;
  10975. out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  10976. for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
  10977. {
  10978. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
  10979. ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
  10980. ImVec2 triangle[3];
  10981. for (int n = 0; n < 3; n++, idx_n++)
  10982. vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
  10983. if (show_mesh)
  10984. out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
  10985. }
  10986. // Draw bounding boxes
  10987. if (show_aabb)
  10988. {
  10989. out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
  10990. out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
  10991. }
  10992. out_draw_list->Flags = backup_flags;
  10993. }
  10994. // [DEBUG] Display details for a single font, called by ShowStyleEditor().
  10995. void ImGui::DebugNodeFont(ImFont* font)
  10996. {
  10997. bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
  10998. font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
  10999. SameLine();
  11000. if (SmallButton("Set as default"))
  11001. GetIO().FontDefault = font;
  11002. if (!opened)
  11003. return;
  11004. // Display preview text
  11005. PushFont(font);
  11006. Text("The quick brown fox jumps over the lazy dog");
  11007. PopFont();
  11008. // Display details
  11009. SetNextItemWidth(GetFontSize() * 8);
  11010. DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
  11011. SameLine(); MetricsHelpMarker(
  11012. "Note than the default embedded font is NOT meant to be scaled.\n\n"
  11013. "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
  11014. "You may oversample them to get some flexibility with scaling. "
  11015. "You can also render at multiple sizes and select which one to use at runtime.\n\n"
  11016. "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
  11017. Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
  11018. char c_str[5];
  11019. Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
  11020. Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
  11021. const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
  11022. Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
  11023. for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
  11024. if (font->ConfigData)
  11025. if (const ImFontConfig* cfg = &font->ConfigData[config_i])
  11026. BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
  11027. config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
  11028. // Display all glyphs of the fonts in separate pages of 256 characters
  11029. if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
  11030. {
  11031. ImDrawList* draw_list = GetWindowDrawList();
  11032. const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
  11033. const float cell_size = font->FontSize * 1;
  11034. const float cell_spacing = GetStyle().ItemSpacing.y;
  11035. for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
  11036. {
  11037. // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
  11038. // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
  11039. // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
  11040. if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
  11041. {
  11042. base += 4096 - 256;
  11043. continue;
  11044. }
  11045. int count = 0;
  11046. for (unsigned int n = 0; n < 256; n++)
  11047. if (font->FindGlyphNoFallback((ImWchar)(base + n)))
  11048. count++;
  11049. if (count <= 0)
  11050. continue;
  11051. if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
  11052. continue;
  11053. // Draw a 16x16 grid of glyphs
  11054. ImVec2 base_pos = GetCursorScreenPos();
  11055. for (unsigned int n = 0; n < 256; n++)
  11056. {
  11057. // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
  11058. // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
  11059. ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
  11060. ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
  11061. const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
  11062. draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
  11063. if (glyph)
  11064. font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
  11065. if (glyph && IsMouseHoveringRect(cell_p1, cell_p2))
  11066. {
  11067. BeginTooltip();
  11068. Text("Codepoint: U+%04X", base + n);
  11069. Separator();
  11070. Text("Visible: %d", glyph->Visible);
  11071. Text("AdvanceX: %.1f", glyph->AdvanceX);
  11072. Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
  11073. Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
  11074. EndTooltip();
  11075. }
  11076. }
  11077. Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
  11078. TreePop();
  11079. }
  11080. TreePop();
  11081. }
  11082. TreePop();
  11083. }
  11084. // [DEBUG] Display contents of ImGuiStorage
  11085. void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
  11086. {
  11087. if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
  11088. return;
  11089. for (int n = 0; n < storage->Data.Size; n++)
  11090. {
  11091. const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
  11092. 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.
  11093. }
  11094. TreePop();
  11095. }
  11096. // [DEBUG] Display contents of ImGuiTabBar
  11097. void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
  11098. {
  11099. // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
  11100. char buf[256];
  11101. char* p = buf;
  11102. const char* buf_end = buf + IM_ARRAYSIZE(buf);
  11103. const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
  11104. p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
  11105. p += ImFormatString(p, buf_end - p, " { ");
  11106. for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
  11107. {
  11108. ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  11109. p += ImFormatString(p, buf_end - p, "%s'%s'",
  11110. tab_n > 0 ? ", " : "", (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???");
  11111. }
  11112. p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
  11113. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  11114. bool open = TreeNode(label, "%s", buf);
  11115. if (!is_active) { PopStyleColor(); }
  11116. if (is_active && IsItemHovered())
  11117. {
  11118. ImDrawList* draw_list = GetForegroundDrawList();
  11119. draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
  11120. 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));
  11121. 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));
  11122. }
  11123. if (open)
  11124. {
  11125. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
  11126. {
  11127. const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  11128. PushID(tab);
  11129. if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
  11130. if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
  11131. Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f",
  11132. tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth);
  11133. PopID();
  11134. }
  11135. TreePop();
  11136. }
  11137. }
  11138. void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
  11139. {
  11140. SetNextItemOpen(true, ImGuiCond_Once);
  11141. if (TreeNode("viewport0", "Viewport #%d", 0))
  11142. {
  11143. ImGuiWindowFlags flags = viewport->Flags;
  11144. BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f",
  11145. viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
  11146. viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y);
  11147. BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags,
  11148. (flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "",
  11149. (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
  11150. (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "");
  11151. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  11152. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  11153. DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  11154. TreePop();
  11155. }
  11156. }
  11157. void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
  11158. {
  11159. if (window == NULL)
  11160. {
  11161. BulletText("%s: NULL", label);
  11162. return;
  11163. }
  11164. ImGuiContext& g = *GImGui;
  11165. const bool is_active = window->WasActive;
  11166. ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
  11167. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  11168. const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
  11169. if (!is_active) { PopStyleColor(); }
  11170. if (IsItemHovered() && is_active)
  11171. GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  11172. if (!open)
  11173. return;
  11174. if (window->MemoryCompacted)
  11175. TextDisabled("Note: some memory buffers have been compacted/freed.");
  11176. ImGuiWindowFlags flags = window->Flags;
  11177. DebugNodeDrawList(window, window->DrawList, "DrawList");
  11178. BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
  11179. BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
  11180. (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
  11181. (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
  11182. (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
  11183. 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" : "");
  11184. BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
  11185. BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
  11186. for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
  11187. {
  11188. ImRect r = window->NavRectRel[layer];
  11189. if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
  11190. {
  11191. BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
  11192. continue;
  11193. }
  11194. 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);
  11195. if (IsItemHovered())
  11196. GetForegroundDrawList(window)->AddRect(r.Min + window->Pos, r.Max + window->Pos, IM_COL32(255, 255, 0, 255));
  11197. }
  11198. BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
  11199. if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
  11200. if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
  11201. if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
  11202. if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
  11203. {
  11204. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  11205. DebugNodeColumns(&window->ColumnsStorage[n]);
  11206. TreePop();
  11207. }
  11208. DebugNodeStorage(&window->StateStorage, "Storage");
  11209. TreePop();
  11210. }
  11211. void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
  11212. {
  11213. Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
  11214. settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
  11215. }
  11216. void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
  11217. {
  11218. if (!TreeNode(label, "%s (%d)", label, windows->Size))
  11219. return;
  11220. for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
  11221. {
  11222. PushID((*windows)[i]);
  11223. DebugNodeWindow((*windows)[i], "Window");
  11224. PopID();
  11225. }
  11226. TreePop();
  11227. }
  11228. // FIXME-OPT: This is technically suboptimal, but it is simpler this way.
  11229. void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
  11230. {
  11231. for (int i = 0; i < windows_size; i++)
  11232. {
  11233. ImGuiWindow* window = windows[i];
  11234. if (window->ParentWindowInBeginStack != parent_in_begin_stack)
  11235. continue;
  11236. char buf[20];
  11237. ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
  11238. //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
  11239. DebugNodeWindow(window, buf);
  11240. Indent();
  11241. DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
  11242. Unindent();
  11243. }
  11244. }
  11245. //-----------------------------------------------------------------------------
  11246. // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
  11247. //-----------------------------------------------------------------------------
  11248. // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
  11249. void ImGui::UpdateDebugToolItemPicker()
  11250. {
  11251. ImGuiContext& g = *GImGui;
  11252. g.DebugItemPickerBreakId = 0;
  11253. if (!g.DebugItemPickerActive)
  11254. return;
  11255. const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
  11256. SetMouseCursor(ImGuiMouseCursor_Hand);
  11257. if (IsKeyPressed(ImGuiKey_Escape))
  11258. g.DebugItemPickerActive = false;
  11259. if (IsMouseClicked(0) && hovered_id)
  11260. {
  11261. g.DebugItemPickerBreakId = hovered_id;
  11262. g.DebugItemPickerActive = false;
  11263. }
  11264. SetNextWindowBgAlpha(0.60f);
  11265. BeginTooltip();
  11266. Text("HoveredId: 0x%08X", hovered_id);
  11267. Text("Press ESC to abort picking.");
  11268. TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
  11269. EndTooltip();
  11270. }
  11271. // [DEBUG] Stack Tool: update queries. Called by NewFrame()
  11272. void ImGui::UpdateDebugToolStackQueries()
  11273. {
  11274. ImGuiContext& g = *GImGui;
  11275. ImGuiStackTool* tool = &g.DebugStackTool;
  11276. // Clear hook when stack tool is not visible
  11277. g.DebugHookIdInfo = 0;
  11278. if (g.FrameCount != tool->LastActiveFrame + 1)
  11279. return;
  11280. // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
  11281. // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
  11282. const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
  11283. if (tool->QueryId != query_id)
  11284. {
  11285. tool->QueryId = query_id;
  11286. tool->StackLevel = -1;
  11287. tool->Results.resize(0);
  11288. }
  11289. if (query_id == 0)
  11290. return;
  11291. // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
  11292. int stack_level = tool->StackLevel;
  11293. if (stack_level >= 0 && stack_level < tool->Results.Size)
  11294. if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
  11295. tool->StackLevel++;
  11296. // Update hook
  11297. stack_level = tool->StackLevel;
  11298. if (stack_level == -1)
  11299. g.DebugHookIdInfo = query_id;
  11300. if (stack_level >= 0 && stack_level < tool->Results.Size)
  11301. {
  11302. g.DebugHookIdInfo = tool->Results[stack_level].ID;
  11303. tool->Results[stack_level].QueryFrameCount++;
  11304. }
  11305. }
  11306. // [DEBUG] Stack tool: hooks called by GetID() family functions
  11307. void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
  11308. {
  11309. ImGuiContext& g = *GImGui;
  11310. ImGuiWindow* window = g.CurrentWindow;
  11311. ImGuiStackTool* tool = &g.DebugStackTool;
  11312. // Step 0: stack query
  11313. // This assume that the ID was computed with the current ID stack, which tends to be the case for our widget.
  11314. if (tool->StackLevel == -1)
  11315. {
  11316. tool->StackLevel++;
  11317. tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
  11318. for (int n = 0; n < window->IDStack.Size + 1; n++)
  11319. tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
  11320. return;
  11321. }
  11322. // Step 1+: query for individual level
  11323. IM_ASSERT(tool->StackLevel >= 0);
  11324. if (tool->StackLevel != window->IDStack.Size)
  11325. return;
  11326. ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
  11327. IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
  11328. int data_len;
  11329. switch (data_type)
  11330. {
  11331. case ImGuiDataType_S32:
  11332. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
  11333. break;
  11334. case ImGuiDataType_String:
  11335. data_len = data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id);
  11336. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "\"%.*s\"", data_len, (const char*)data_id);
  11337. break;
  11338. case ImGuiDataType_Pointer:
  11339. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
  11340. break;
  11341. case ImGuiDataType_ID:
  11342. 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.
  11343. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
  11344. break;
  11345. default:
  11346. IM_ASSERT(0);
  11347. }
  11348. info->QuerySuccess = true;
  11349. }
  11350. // Stack Tool: Display UI
  11351. void ImGui::ShowStackToolWindow(bool* p_open)
  11352. {
  11353. ImGuiContext& g = *GImGui;
  11354. if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
  11355. SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
  11356. if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
  11357. {
  11358. End();
  11359. return;
  11360. }
  11361. // Display hovered/active status
  11362. const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
  11363. const ImGuiID active_id = g.ActiveId;
  11364. #ifdef IMGUI_ENABLE_TEST_ENGINE
  11365. 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) : "");
  11366. #else
  11367. Text("HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id);
  11368. #endif
  11369. SameLine();
  11370. 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.");
  11371. // Display decorated stack
  11372. ImGuiStackTool* tool = &g.DebugStackTool;
  11373. tool->LastActiveFrame = g.FrameCount;
  11374. if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
  11375. {
  11376. const float id_width = CalcTextSize("0xDDDDDDDD").x;
  11377. TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
  11378. TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
  11379. TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
  11380. TableHeadersRow();
  11381. for (int n = 0; n < tool->Results.Size; n++)
  11382. {
  11383. ImGuiStackLevelInfo* info = &tool->Results[n];
  11384. TableNextColumn();
  11385. Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
  11386. TableNextColumn();
  11387. ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? FindWindowByID(info->ID) : NULL;
  11388. if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
  11389. Text("\"%s\" [window]", window->Name);
  11390. else if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
  11391. TextUnformatted(info->Desc);
  11392. else if (tool->StackLevel >= tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
  11393. {
  11394. #ifdef IMGUI_ENABLE_TEST_ENGINE
  11395. if (const char* label = ImGuiTestEngine_FindItemDebugLabel(&g, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
  11396. Text("??? \"%s\"", label);
  11397. else
  11398. #endif
  11399. TextUnformatted("???");
  11400. }
  11401. TableNextColumn();
  11402. Text("0x%08X", info->ID);
  11403. if (n == tool->Results.Size - 1)
  11404. TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
  11405. }
  11406. EndTable();
  11407. }
  11408. End();
  11409. }
  11410. #else
  11411. void ImGui::ShowMetricsWindow(bool*) {}
  11412. void ImGui::ShowFontAtlas(ImFontAtlas*) {}
  11413. void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
  11414. void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {}
  11415. void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
  11416. void ImGui::DebugNodeFont(ImFont*) {}
  11417. void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
  11418. void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
  11419. void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
  11420. void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
  11421. void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
  11422. void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
  11423. void ImGui::ShowStackToolWindow(bool*) {}
  11424. void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
  11425. void ImGui::UpdateDebugToolItemPicker() {}
  11426. void ImGui::UpdateDebugToolStackQueries() {}
  11427. #endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW
  11428. //-----------------------------------------------------------------------------
  11429. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  11430. // Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
  11431. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  11432. #include "imgui_user.inl"
  11433. #endif
  11434. //-----------------------------------------------------------------------------
  11435. #endif // #ifndef IMGUI_DISABLE