imgui.cpp 443 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311
  1. // dear imgui, v1.67 WIP
  2. // (main code and documentation)
  3. // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
  4. // Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
  5. // Get latest version at https://github.com/ocornut/imgui
  6. // Releases change-log at https://github.com/ocornut/imgui/releases
  7. // Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
  8. // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
  9. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  10. // See LICENSE.txt for copyright and licensing details (standard MIT License).
  11. // This library is free but I need your support to sustain development and maintenance.
  12. // Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README.
  13. // Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui.
  14. // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
  15. // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
  16. // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
  17. // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
  18. // to a better solution or official support for them.
  19. /*
  20. Index of this file:
  21. DOCUMENTATION
  22. - MISSION STATEMENT
  23. - END-USER GUIDE
  24. - PROGRAMMER GUIDE (read me!)
  25. - Read first.
  26. - How to update to a newer version of Dear ImGui.
  27. - Getting started with integrating Dear ImGui in your code/engine.
  28. - This is how a simple application may look like (2 variations).
  29. - This is how a simple rendering function may look like.
  30. - Using gamepad/keyboard navigation controls.
  31. - API BREAKING CHANGES (read me when you update!)
  32. - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  33. - How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
  34. - How can I display an image? What is ImTextureID, how does it works?
  35. - How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack.
  36. - How can I use my own math types instead of ImVec2/ImVec4?
  37. - How can I load a different font than the default?
  38. - How can I easily use icons in my application?
  39. - How can I load multiple fonts?
  40. - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
  41. - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  42. - How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad)
  43. - I integrated Dear ImGui in my engine and the text or lines are blurry..
  44. - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  45. - How can I help?
  46. CODE
  47. (search for "[SECTION]" in the code to find them)
  48. // [SECTION] FORWARD DECLARATIONS
  49. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  50. // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  51. // [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
  52. // [SECTION] MISC HELPER/UTILITIES (ImText* functions)
  53. // [SECTION] MISC HELPER/UTILITIES (Color functions)
  54. // [SECTION] ImGuiStorage
  55. // [SECTION] ImGuiTextFilter
  56. // [SECTION] ImGuiTextBuffer
  57. // [SECTION] ImGuiListClipper
  58. // [SECTION] RENDER HELPERS
  59. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  60. // [SECTION] TOOLTIPS
  61. // [SECTION] POPUPS
  62. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  63. // [SECTION] COLUMNS
  64. // [SECTION] DRAG AND DROP
  65. // [SECTION] LOGGING/CAPTURING
  66. // [SECTION] SETTINGS
  67. // [SECTION] PLATFORM DEPENDENT HELPERS
  68. // [SECTION] METRICS/DEBUG WINDOW
  69. */
  70. //-----------------------------------------------------------------------------
  71. // DOCUMENTATION
  72. //-----------------------------------------------------------------------------
  73. /*
  74. MISSION STATEMENT
  75. =================
  76. - Easy to use to create code-driven and data-driven tools.
  77. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
  78. - Easy to hack and improve.
  79. - Minimize screen real-estate usage.
  80. - Minimize setup and maintenance.
  81. - Minimize state storage on user side.
  82. - Portable, minimize dependencies, run on target (consoles, phones, etc.).
  83. - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
  84. opening a tree node for the first time, etc. but a typical frame should not allocate anything).
  85. Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
  86. - Doesn't look fancy, doesn't animate.
  87. - Limited layout features, intricate layouts are typically crafted in code.
  88. END-USER GUIDE
  89. ==============
  90. - Double-click on title bar to collapse window.
  91. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
  92. - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
  93. - Click and drag on any empty space to move window.
  94. - TAB/SHIFT+TAB to cycle through keyboard editable fields.
  95. - CTRL+Click on a slider or drag box to input value as text.
  96. - Use mouse wheel to scroll.
  97. - Text editor:
  98. - Hold SHIFT or use mouse to select text.
  99. - CTRL+Left/Right to word jump.
  100. - CTRL+Shift+Left/Right to select words.
  101. - CTRL+A our Double-Click to select all.
  102. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
  103. - CTRL+Z,CTRL+Y to undo/redo.
  104. - ESCAPE to revert text to its original value.
  105. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  106. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  107. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
  108. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
  109. PROGRAMMER GUIDE
  110. ================
  111. READ FIRST:
  112. - Read the FAQ below this section!
  113. - 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
  114. or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
  115. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
  116. - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
  117. - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
  118. You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
  119. - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
  120. For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
  121. where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
  122. - Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
  123. - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
  124. - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
  125. If you get an assert, read the messages and comments around the assert.
  126. - 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.
  127. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
  128. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
  129. However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
  130. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
  131. HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI:
  132. - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
  133. - Or maintain your own branch where you have imconfig.h modified.
  134. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  135. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
  136. from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
  137. likely be a comment about it. Please report any issue to the GitHub page!
  138. - Try to keep your copy of dear imgui reasonably up to date.
  139. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE:
  140. - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
  141. - Add the Dear ImGui source files to your projects or using your preferred build system.
  142. It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
  143. - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types.
  144. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
  145. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
  146. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
  147. phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render().
  148. - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
  149. - 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.
  150. HOW A SIMPLE APPLICATION MAY LOOK LIKE:
  151. EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
  152. // Application init: create a dear imgui context, setup some options, load fonts
  153. ImGui::CreateContext();
  154. ImGuiIO& io = ImGui::GetIO();
  155. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  156. // TODO: Fill optional fields of the io structure later.
  157. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  158. // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
  159. ImGui_ImplWin32_Init(hwnd);
  160. ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
  161. // Application main loop
  162. while (true)
  163. {
  164. // Feed inputs to dear imgui, start new frame
  165. ImGui_ImplDX11_NewFrame();
  166. ImGui_ImplWin32_NewFrame();
  167. ImGui::NewFrame();
  168. // Any application code here
  169. ImGui::Text("Hello, world!");
  170. // Render dear imgui into screen
  171. ImGui::Render();
  172. ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
  173. g_pSwapChain->Present(1, 0);
  174. }
  175. // Shutdown
  176. ImGui_ImplDX11_Shutdown();
  177. ImGui_ImplWin32_Shutdown();
  178. ImGui::DestroyContext();
  179. HOW A SIMPLE APPLICATION MAY LOOK LIKE:
  180. EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE.
  181. // Application init: create a dear imgui context, setup some options, load fonts
  182. ImGui::CreateContext();
  183. ImGuiIO& io = ImGui::GetIO();
  184. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  185. // TODO: Fill optional fields of the io structure later.
  186. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  187. // Build and load the texture atlas into a texture
  188. // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
  189. int width, height;
  190. unsigned char* pixels = NULL;
  191. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  192. // At this point you've got the texture data and you need to upload that your your graphic system:
  193. // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
  194. // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
  195. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
  196. io.Fonts->TexID = (void*)texture;
  197. // Application main loop
  198. while (true)
  199. {
  200. // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
  201. // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
  202. io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
  203. io.DisplaySize.x = 1920.0f; // set the current display width
  204. io.DisplaySize.y = 1280.0f; // set the current display height here
  205. io.MousePos = my_mouse_pos; // set the mouse position
  206. io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
  207. io.MouseDown[1] = my_mouse_buttons[1];
  208. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  209. // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere)
  210. ImGui::NewFrame();
  211. // Most of your application code here
  212. ImGui::Text("Hello, world!");
  213. MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  214. MyGameRender(); // may use any ImGui functions as well!
  215. // Render imgui, swap buffers
  216. // (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code)
  217. ImGui::EndFrame();
  218. ImGui::Render();
  219. ImDrawData* draw_data = ImGui::GetDrawData();
  220. MyImGuiRenderFunction(draw_data);
  221. SwapBuffers();
  222. }
  223. // Shutdown
  224. ImGui::DestroyContext();
  225. HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE:
  226. void void MyImGuiRenderFunction(ImDrawData* draw_data)
  227. {
  228. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  229. // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  230. // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  231. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  232. for (int n = 0; n < draw_data->CmdListsCount; n++)
  233. {
  234. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  235. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
  236. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
  237. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  238. {
  239. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  240. if (pcmd->UserCallback)
  241. {
  242. pcmd->UserCallback(cmd_list, pcmd);
  243. }
  244. else
  245. {
  246. // The texture for the draw call is specified by pcmd->TextureId.
  247. // The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization.
  248. MyEngineBindTexture((MyTexture*)pcmd->TextureId);
  249. // We are using scissoring to clip some objects. All low-level graphics API should supports it.
  250. // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
  251. // (some elements visible outside their bounds) but you can fix that once everything else works!
  252. // - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
  253. // In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
  254. // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
  255. // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
  256. // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
  257. ImVec2 pos = draw_data->DisplayPos;
  258. MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
  259. // Render 'pcmd->ElemCount/3' indexed triangles.
  260. // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
  261. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
  262. }
  263. idx_buffer += pcmd->ElemCount;
  264. }
  265. }
  266. }
  267. - The examples/ folders contains many actual implementation of the pseudo-codes above.
  268. - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
  269. They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs
  270. from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information.
  271. - Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues!
  272. USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  273. - The gamepad/keyboard navigation is fairly functional and keeps being improved.
  274. - Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
  275. - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
  276. - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
  277. - Gamepad:
  278. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
  279. - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
  280. Note that io.NavInputs[] is cleared by EndFrame().
  281. - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
  282. 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
  283. - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
  284. 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.).
  285. - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
  286. - 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
  287. to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
  288. - Keyboard:
  289. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
  290. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
  291. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
  292. will be set. For more advanced uses, you may want to read from:
  293. - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
  294. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
  295. - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
  296. Please reach out if you think the game vs navigation input sharing could be improved.
  297. - Mouse:
  298. - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
  299. - 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.
  300. - 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.
  301. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
  302. 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.
  303. When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
  304. (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
  305. (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
  306. to set a boolean to ignore your other external mouse positions until the external source is moved again.)
  307. API BREAKING CHANGES
  308. ====================
  309. Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
  310. 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.
  311. When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  312. You can read releases logs https://github.com/ocornut/imgui/releases for more details.
  313. - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
  314. - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete).
  315. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
  316. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
  317. - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
  318. - 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.
  319. If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
  320. - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
  321. - 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.
  322. NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
  323. Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
  324. - 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).
  325. - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
  326. - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
  327. - 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.
  328. - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
  329. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
  330. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
  331. - 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.).
  332. old binding will still work as is, however prefer using the separated bindings as they will be updated to be multi-viewport conformant.
  333. when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
  334. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
  335. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
  336. - 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.
  337. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
  338. 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.
  339. 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.
  340. - 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",
  341. consistent with other functions. Kept redirection functions (will obsolete).
  342. - 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.
  343. - 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 binding ahead of merging the Nav branch).
  344. - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
  345. - 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.
  346. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
  347. - 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.
  348. - 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.
  349. - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
  350. - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
  351. - removed Shutdown() function, as DestroyContext() serve this purpose.
  352. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
  353. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
  354. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
  355. - 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.
  356. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
  357. - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
  358. - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
  359. - 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.
  360. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
  361. - 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
  362. - 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.
  363. - 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.
  364. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
  365. - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
  366. - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
  367. - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
  368. - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
  369. - 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.
  370. - 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.
  371. 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.
  372. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
  373. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
  374. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
  375. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
  376. - 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.
  377. - 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.
  378. - 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.
  379. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
  380. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
  381. - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
  382. - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete).
  383. - 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).
  384. - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
  385. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
  386. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  387. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  388. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  389. - 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.
  390. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
  391. - 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.
  392. - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
  393. - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
  394. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  395. - 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.
  396. - 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.
  397. - 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))'
  398. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  399. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  400. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  401. - 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().
  402. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  403. - 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.
  404. - 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.
  405. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  406. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
  407. If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
  408. 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.
  409. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
  410. {
  411. float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
  412. 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);
  413. }
  414. 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.
  415. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  416. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  417. - 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).
  418. - 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.
  419. - 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).
  420. - 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)
  421. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  422. - 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.
  423. - 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.
  424. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  425. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  426. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  427. 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.
  428. 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!
  429. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  430. - 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.
  431. - 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
  432. - 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.
  433. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  434. - 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.
  435. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  436. - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
  437. - the signature of the io.RenderDrawListsFn handler has changed!
  438. old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  439. new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  440. parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
  441. ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
  442. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
  443. - 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.
  444. - 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!
  445. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  446. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  447. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  448. - 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.
  449. - 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
  450. - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
  451. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  452. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  453. - 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.
  454. - 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.
  455. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  456. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  457. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  458. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  459. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  460. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  461. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  462. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  463. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  464. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  465. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  466. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  467. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  468. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  469. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  470. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  471. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  472. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  473. font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; }
  474. became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; }
  475. you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
  476. it is now recommended that you sample the font texture with bilinear interpolation.
  477. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
  478. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  479. (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  480. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  481. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  482. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  483. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  484. - 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)
  485. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  486. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  487. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  488. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  489. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  490. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  491. FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  492. ======================================
  493. Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
  494. A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } )
  495. - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
  496. - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
  497. - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
  498. Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
  499. This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
  500. Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
  501. It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
  502. Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
  503. perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags().
  504. Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
  505. have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
  506. were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
  507. Q: How can I display an image? What is ImTextureID, how does it works?
  508. A: Short explanation:
  509. - You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures.
  510. - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value.
  511. - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason).
  512. Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.
  513. Long explanation:
  514. - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices.
  515. At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code
  516. to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.).
  517. - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API.
  518. We carry the information to identify a "texture" in the ImTextureID type.
  519. ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice.
  520. Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function.
  521. - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying
  522. an image from the end-user perspective. This is what the _examples_ rendering functions are using:
  523. OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp)
  524. DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp)
  525. DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp)
  526. DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp)
  527. For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID.
  528. Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure
  529. tying together both the texture and information about its format and how to read it.
  530. - If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about
  531. the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase
  532. is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them.
  533. If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID
  534. representation suggested by the example bindings is probably the best choice.
  535. (Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer)
  536. User code may do:
  537. // Cast our texture type to ImTextureID / void*
  538. MyTexture* texture = g_CoffeeTableTexture;
  539. ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
  540. The renderer function called after ImGui::Render() will receive that same value that the user code passed:
  541. // Cast ImTextureID / void* stored in the draw command as our texture type
  542. MyTexture* texture = (MyTexture*)pcmd->TextureId;
  543. MyEngineBindTexture2D(texture);
  544. Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui.
  545. This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them.
  546. If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using.
  547. Here's a simplified OpenGL example using stb_image.h:
  548. // Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data:
  549. #define STB_IMAGE_IMPLEMENTATION
  550. #include <stb_image.h>
  551. [...]
  552. int my_image_width, my_image_height;
  553. unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4);
  554. // Turn the RGBA pixel data into an OpenGL texture:
  555. GLuint my_opengl_texture;
  556. glGenTextures(1, &my_opengl_texture);
  557. glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
  558. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  559. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  560. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  561. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
  562. // Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it:
  563. ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height));
  564. C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTexture / void*, and vice-versa.
  565. Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTexture / void*.
  566. Examples:
  567. GLuint my_tex = XXX;
  568. void* my_void_ptr;
  569. my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer)
  570. my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint
  571. ID3D11ShaderResourceView* my_dx11_srv = XXX;
  572. void* my_void_ptr;
  573. my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void*
  574. my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView*
  575. Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated.
  576. Q: How can I have multiple widgets with the same label or with an empty label?
  577. Q: I have multiple widgets with the same label, and only the first one works. Why is that?
  578. A: A primer on labels and the ID Stack...
  579. Dear ImGui internally need to uniquely identify UI elements.
  580. Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
  581. Interactive widgets (such as calls to Button buttons) need a unique ID.
  582. Unique ID are used internally to track active widgets and occasionally associate state to widgets.
  583. Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
  584. - Unique ID are often derived from a string label:
  585. Button("OK"); // Label = "OK", ID = hash of (..., "OK")
  586. Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
  587. - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
  588. two buttons labeled "OK" in different windows or different tree locations is fine.
  589. We used "..." above to signify whatever was already pushed to the ID stack previously:
  590. Begin("MyWindow");
  591. Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
  592. End();
  593. Begin("MyOtherWindow");
  594. Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
  595. End();
  596. - If you have a same ID twice in the same location, you'll have a conflict:
  597. Button("OK");
  598. Button("OK"); // ID collision! Interacting with either button will trigger the first one.
  599. Fear not! this is easy to solve and there are many ways to solve it!
  600. - Solving ID conflict in a simple/local context:
  601. When passing a label you can optionally specify extra ID information within string itself.
  602. Use "##" to pass a complement to the ID that won't be visible to the end-user.
  603. This helps solving the simple collision cases when you know e.g. at compilation time which items
  604. are going to be created:
  605. Begin("MyWindow");
  606. Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
  607. Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
  608. Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
  609. End();
  610. - If you want to completely hide the label, but still need an ID:
  611. Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
  612. - Occasionally/rarely you might want change a label while preserving a constant ID. This allows
  613. you to animate labels. For example you may want to include varying information in a window title bar,
  614. but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
  615. Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "ID")
  616. Button("World###ID"); // Label = "World", ID = hash of (..., "ID") // Same as above, even though the label looks different
  617. sprintf(buf, "My game (%f FPS)###MyGame", fps);
  618. Begin(buf); // Variable title, ID = hash of "MyGame"
  619. - Solving ID conflict in a more general manner:
  620. Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
  621. within the same window. This is the most convenient way of distinguishing ID when iterating and
  622. creating many UI elements programmatically.
  623. You can push a pointer, a string or an integer value into the ID stack.
  624. Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
  625. At each level of the stack we store the seed used for items at this level of the ID stack.
  626. Begin("Window");
  627. for (int i = 0; i < 100; i++)
  628. {
  629. PushID(i); // Push i to the id tack
  630. Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
  631. PopID();
  632. }
  633. for (int i = 0; i < 100; i++)
  634. {
  635. MyObject* obj = Objects[i];
  636. PushID(obj);
  637. Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
  638. PopID();
  639. }
  640. for (int i = 0; i < 100; i++)
  641. {
  642. MyObject* obj = Objects[i];
  643. PushID(obj->Name);
  644. Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
  645. PopID();
  646. }
  647. End();
  648. - You can stack multiple prefixes into the ID stack:
  649. Button("Click"); // Label = "Click", ID = hash of (..., "Click")
  650. PushID("node");
  651. Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
  652. PushID(my_ptr);
  653. Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
  654. PopID();
  655. PopID();
  656. - Tree nodes implicitly creates a scope for you by calling PushID().
  657. Button("Click"); // Label = "Click", ID = hash of (..., "Click")
  658. if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
  659. {
  660. Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
  661. TreePop();
  662. }
  663. - When working with trees, ID are used to preserve the open/close state of each tree node.
  664. Depending on your use cases you may want to use strings, indices or pointers as ID.
  665. e.g. when following a single pointer that may change over time, using a static string as ID
  666. will preserve your node open/closed state when the targeted object change.
  667. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
  668. node open/closed state differently. See what makes more sense in your situation!
  669. Q: How can I use my own math types instead of ImVec2/ImVec4?
  670. A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions.
  671. This way you'll be able to use your own types everywhere, e.g. passsing glm::vec2 to ImGui functions instead of ImVec2.
  672. Q: How can I load a different font than the default?
  673. A: Use the font atlas to load the TTF/OTF file you want:
  674. ImGuiIO& io = ImGui::GetIO();
  675. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  676. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  677. Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code.
  678. (Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.)
  679. (Read the 'misc/fonts/README.txt' file for more details about font loading.)
  680. New programmers: remember that in C/C++ and most programming languages if you want to use a
  681. backslash \ within a string literal, you need to write it double backslash "\\":
  682. io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!)
  683. io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
  684. io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
  685. Q: How can I easily use icons in my application?
  686. A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you
  687. main font. Then you can refer to icons within your strings.
  688. You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment.
  689. (Read the 'misc/fonts/README.txt' file for more details about icons font loading.)
  690. Q: How can I load multiple fonts?
  691. A: Use the font atlas to pack them into a single texture:
  692. (Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.)
  693. ImGuiIO& io = ImGui::GetIO();
  694. ImFont* font0 = io.Fonts->AddFontDefault();
  695. ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  696. ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
  697. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  698. // the first loaded font gets used by default
  699. // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
  700. // Options
  701. ImFontConfig config;
  702. config.OversampleH = 3;
  703. config.OversampleV = 1;
  704. config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up
  705. config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
  706. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config);
  707. // Combine multiple fonts into one (e.g. for icon fonts)
  708. static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
  709. ImFontConfig config;
  710. config.MergeMode = true;
  711. io.Fonts->AddFontDefault();
  712. io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
  713. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
  714. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  715. A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
  716. // Add default Japanese ranges
  717. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
  718. // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
  719. ImVector<ImWchar> ranges;
  720. ImFontGlyphRangesBuilder builder;
  721. builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
  722. builder.AddChar(0x7262); // Add a specific character
  723. builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
  724. builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
  725. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
  726. All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8
  727. by using the u8"hello" syntax. Specifying literal in your source code using a local code page
  728. (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
  729. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
  730. Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter().
  731. The applications in examples/ are doing that.
  732. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode).
  733. You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state.
  734. Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for
  735. the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly.
  736. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  737. A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags.
  738. (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse)
  739. Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
  740. - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows.
  741. - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create
  742. your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data.
  743. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
  744. A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls".
  745. (short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad)
  746. - You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy)
  747. This is the preferred solution for developer productivity.
  748. In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple
  749. and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect
  750. to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer.
  751. Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols.
  752. - You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends
  753. the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine.
  754. - For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate
  755. for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing
  756. for screen real-estate and precision.
  757. Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
  758. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
  759. Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
  760. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  761. A: You are probably mishandling the clipping rectangles in your render function.
  762. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
  763. Q: How can I help?
  764. A: - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
  765. and see how you want to help and can help!
  766. - Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui.
  767. - Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README.
  768. - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
  769. You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1902). Visuals are ideal as they inspire other programmers.
  770. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
  771. - 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).
  772. - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
  773. this is also useful to set yourself in the context of another window (to get/set other settings)
  774. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
  775. - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
  776. of a deep nested inner loop in your code.
  777. - tip: you can call Render() multiple times (e.g for VR renders).
  778. - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
  779. */
  780. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  781. #define _CRT_SECURE_NO_WARNINGS
  782. #endif
  783. #include "imgui.h"
  784. #ifndef IMGUI_DEFINE_MATH_OPERATORS
  785. #define IMGUI_DEFINE_MATH_OPERATORS
  786. #endif
  787. #include "imgui_internal.h"
  788. #include <ctype.h> // toupper, isprint
  789. #include <stdio.h> // vsnprintf, sscanf, printf
  790. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  791. #include <stddef.h> // intptr_t
  792. #else
  793. #include <stdint.h> // intptr_t
  794. #endif
  795. // Debug options
  796. #define IMGUI_DEBUG_NAV_SCORING 0
  797. #define IMGUI_DEBUG_NAV_RECTS 0
  798. // Visual Studio warnings
  799. #ifdef _MSC_VER
  800. #pragma warning (disable: 4127) // condition expression is constant
  801. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  802. #endif
  803. // Clang/GCC warnings with -Weverything
  804. #ifdef __clang__
  805. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
  806. #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
  807. #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.
  808. #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.
  809. #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.
  810. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
  811. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
  812. #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.
  813. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
  814. #elif defined(__GNUC__)
  815. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  816. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  817. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  818. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  819. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  820. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  821. #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
  822. #if __GNUC__ >= 8
  823. #pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
  824. #endif
  825. #endif
  826. // 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.
  827. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
  828. static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
  829. // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
  830. static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
  831. static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
  832. //-------------------------------------------------------------------------
  833. // [SECTION] FORWARD DECLARATIONS
  834. //-------------------------------------------------------------------------
  835. static void SetCurrentWindow(ImGuiWindow* window);
  836. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
  837. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
  838. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
  839. static void FindHoveredWindow();
  840. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
  841. static void CheckStacksSize(ImGuiWindow* window, bool write);
  842. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
  843. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
  844. static void AddWindowToDrawData(ImVector<ImDrawList*>* out_list, ImGuiWindow* window);
  845. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
  846. static ImRect GetViewportRect();
  847. // Settings
  848. static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
  849. static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
  850. static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
  851. // Platform Dependents default implementation for IO functions
  852. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  853. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  854. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
  855. namespace ImGui
  856. {
  857. static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
  858. // Navigation
  859. static void NavUpdate();
  860. static void NavUpdateWindowing();
  861. static void NavUpdateWindowingList();
  862. static void NavUpdateMoveResult();
  863. static float NavUpdatePageUpPageDown(int allowed_dir_flags);
  864. static inline void NavUpdateAnyRequestFlag();
  865. static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id);
  866. static ImVec2 NavCalcPreferredRefPos();
  867. static void NavSaveLastChildNavWindow(ImGuiWindow* nav_window);
  868. static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
  869. // Misc
  870. static void UpdateMouseInputs();
  871. static void UpdateMouseWheel();
  872. static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
  873. }
  874. //-----------------------------------------------------------------------------
  875. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  876. //-----------------------------------------------------------------------------
  877. // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
  878. // CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
  879. // If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file.
  880. // ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can:
  881. // - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  882. // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
  883. #ifndef GImGui
  884. ImGuiContext* GImGui = NULL;
  885. #endif
  886. // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
  887. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
  888. // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
  889. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
  890. static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); }
  891. static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); }
  892. #else
  893. static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; }
  894. static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); }
  895. #endif
  896. static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
  897. static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
  898. static void* GImAllocatorUserData = NULL;
  899. //-----------------------------------------------------------------------------
  900. // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  901. //-----------------------------------------------------------------------------
  902. ImGuiStyle::ImGuiStyle()
  903. {
  904. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  905. WindowPadding = ImVec2(8,8); // Padding within a window
  906. WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
  907. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  908. WindowMinSize = ImVec2(32,32); // Minimum window size
  909. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  910. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  911. ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  912. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
  913. PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  914. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  915. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  916. FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
  917. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  918. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  919. 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!
  920. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  921. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
  922. ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  923. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  924. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  925. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  926. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
  927. TabBorderSize = 0.0f; // Thickness of border around tabs.
  928. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  929. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows.
  930. 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.
  931. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
  932. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
  933. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
  934. 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.
  935. // Default theme
  936. ImGui::StyleColorsDark(this);
  937. }
  938. // 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.
  939. // 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.
  940. void ImGuiStyle::ScaleAllSizes(float scale_factor)
  941. {
  942. WindowPadding = ImFloor(WindowPadding * scale_factor);
  943. WindowRounding = ImFloor(WindowRounding * scale_factor);
  944. WindowMinSize = ImFloor(WindowMinSize * scale_factor);
  945. ChildRounding = ImFloor(ChildRounding * scale_factor);
  946. PopupRounding = ImFloor(PopupRounding * scale_factor);
  947. FramePadding = ImFloor(FramePadding * scale_factor);
  948. FrameRounding = ImFloor(FrameRounding * scale_factor);
  949. TabRounding = ImFloor(TabRounding * scale_factor);
  950. ItemSpacing = ImFloor(ItemSpacing * scale_factor);
  951. ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
  952. TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
  953. IndentSpacing = ImFloor(IndentSpacing * scale_factor);
  954. ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
  955. ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
  956. ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
  957. GrabMinSize = ImFloor(GrabMinSize * scale_factor);
  958. GrabRounding = ImFloor(GrabRounding * scale_factor);
  959. DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
  960. DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
  961. MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
  962. }
  963. ImGuiIO::ImGuiIO()
  964. {
  965. // Most fields are initialized with zero
  966. memset(this, 0, sizeof(*this));
  967. // Settings
  968. ConfigFlags = ImGuiConfigFlags_None;
  969. BackendFlags = ImGuiBackendFlags_None;
  970. DisplaySize = ImVec2(-1.0f, -1.0f);
  971. DeltaTime = 1.0f/60.0f;
  972. IniSavingRate = 5.0f;
  973. IniFilename = "imgui.ini";
  974. LogFilename = "imgui_log.txt";
  975. MouseDoubleClickTime = 0.30f;
  976. MouseDoubleClickMaxDist = 6.0f;
  977. for (int i = 0; i < ImGuiKey_COUNT; i++)
  978. KeyMap[i] = -1;
  979. KeyRepeatDelay = 0.250f;
  980. KeyRepeatRate = 0.050f;
  981. UserData = NULL;
  982. Fonts = NULL;
  983. FontGlobalScale = 1.0f;
  984. FontDefault = NULL;
  985. FontAllowUserScaling = false;
  986. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  987. DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f);
  988. // Miscellaneous configuration options
  989. #ifdef __APPLE__
  990. ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
  991. #else
  992. ConfigMacOSXBehaviors = false;
  993. #endif
  994. ConfigInputTextCursorBlink = true;
  995. ConfigWindowsResizeFromEdges = true;
  996. ConfigWindowsMoveFromTitleBarOnly = false;
  997. // Platform Functions
  998. BackendPlatformName = BackendRendererName = NULL;
  999. BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
  1000. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  1001. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  1002. ClipboardUserData = NULL;
  1003. ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
  1004. ImeWindowHandle = NULL;
  1005. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  1006. RenderDrawListsFn = NULL;
  1007. #endif
  1008. // Input (NB: we already have memset zero the entire structure!)
  1009. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  1010. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  1011. MouseDragThreshold = 6.0f;
  1012. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  1013. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  1014. for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
  1015. }
  1016. // Pass in translated ASCII characters for text input.
  1017. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  1018. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  1019. void ImGuiIO::AddInputCharacter(ImWchar c)
  1020. {
  1021. InputQueueCharacters.push_back(c);
  1022. }
  1023. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  1024. {
  1025. while (*utf8_chars != 0)
  1026. {
  1027. unsigned int c = 0;
  1028. utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
  1029. if (c > 0 && c <= 0xFFFF)
  1030. InputQueueCharacters.push_back((ImWchar)c);
  1031. }
  1032. }
  1033. void ImGuiIO::ClearInputCharacters()
  1034. {
  1035. InputQueueCharacters.resize(0);
  1036. }
  1037. //-----------------------------------------------------------------------------
  1038. // [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
  1039. //-----------------------------------------------------------------------------
  1040. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  1041. {
  1042. ImVec2 ap = p - a;
  1043. ImVec2 ab_dir = b - a;
  1044. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  1045. if (dot < 0.0f)
  1046. return a;
  1047. float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
  1048. if (dot > ab_len_sqr)
  1049. return b;
  1050. return a + ab_dir * dot / ab_len_sqr;
  1051. }
  1052. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1053. {
  1054. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  1055. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  1056. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  1057. return ((b1 == b2) && (b2 == b3));
  1058. }
  1059. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  1060. {
  1061. ImVec2 v0 = b - a;
  1062. ImVec2 v1 = c - a;
  1063. ImVec2 v2 = p - a;
  1064. const float denom = v0.x * v1.y - v1.x * v0.y;
  1065. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  1066. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  1067. out_u = 1.0f - out_v - out_w;
  1068. }
  1069. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1070. {
  1071. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  1072. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  1073. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  1074. float dist2_ab = ImLengthSqr(p - proj_ab);
  1075. float dist2_bc = ImLengthSqr(p - proj_bc);
  1076. float dist2_ca = ImLengthSqr(p - proj_ca);
  1077. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  1078. if (m == dist2_ab)
  1079. return proj_ab;
  1080. if (m == dist2_bc)
  1081. return proj_bc;
  1082. return proj_ca;
  1083. }
  1084. int ImStricmp(const char* str1, const char* str2)
  1085. {
  1086. int d;
  1087. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  1088. return d;
  1089. }
  1090. int ImStrnicmp(const char* str1, const char* str2, size_t count)
  1091. {
  1092. int d = 0;
  1093. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  1094. return d;
  1095. }
  1096. void ImStrncpy(char* dst, const char* src, size_t count)
  1097. {
  1098. if (count < 1) return;
  1099. strncpy(dst, src, count);
  1100. dst[count-1] = 0;
  1101. }
  1102. char* ImStrdup(const char* str)
  1103. {
  1104. size_t len = strlen(str);
  1105. void* buf = ImGui::MemAlloc(len + 1);
  1106. return (char*)memcpy(buf, (const void*)str, len + 1);
  1107. }
  1108. char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
  1109. {
  1110. size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
  1111. size_t src_size = strlen(src) + 1;
  1112. if (dst_buf_size < src_size)
  1113. {
  1114. ImGui::MemFree(dst);
  1115. dst = (char*)ImGui::MemAlloc(src_size);
  1116. if (p_dst_size)
  1117. *p_dst_size = src_size;
  1118. }
  1119. return (char*)memcpy(dst, (const void*)src, src_size);
  1120. }
  1121. const char* ImStrchrRange(const char* str, const char* str_end, char c)
  1122. {
  1123. const char* p = (const char*)memchr(str, (int)c, str_end - str);
  1124. return p;
  1125. }
  1126. int ImStrlenW(const ImWchar* str)
  1127. {
  1128. //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
  1129. int n = 0;
  1130. while (*str++) n++;
  1131. return n;
  1132. }
  1133. // Find end-of-line. Return pointer will point to either first \n, either str_end.
  1134. const char* ImStreolRange(const char* str, const char* str_end)
  1135. {
  1136. const char* p = (const char*)memchr(str, '\n', str_end - str);
  1137. return p ? p : str_end;
  1138. }
  1139. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  1140. {
  1141. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  1142. buf_mid_line--;
  1143. return buf_mid_line;
  1144. }
  1145. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  1146. {
  1147. if (!needle_end)
  1148. needle_end = needle + strlen(needle);
  1149. const char un0 = (char)toupper(*needle);
  1150. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  1151. {
  1152. if (toupper(*haystack) == un0)
  1153. {
  1154. const char* b = needle + 1;
  1155. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  1156. if (toupper(*a) != toupper(*b))
  1157. break;
  1158. if (b == needle_end)
  1159. return haystack;
  1160. }
  1161. haystack++;
  1162. }
  1163. return NULL;
  1164. }
  1165. // 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.
  1166. void ImStrTrimBlanks(char* buf)
  1167. {
  1168. char* p = buf;
  1169. while (p[0] == ' ' || p[0] == '\t') // Leading blanks
  1170. p++;
  1171. char* p_start = p;
  1172. while (*p != 0) // Find end of string
  1173. p++;
  1174. while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
  1175. p--;
  1176. if (p_start != buf) // Copy memory if we had leading blanks
  1177. memmove(buf, p_start, p - p_start);
  1178. buf[p - p_start] = 0; // Zero terminate
  1179. }
  1180. // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  1181. // 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.
  1182. // B) When buf==NULL vsnprintf() will return the output size.
  1183. #ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
  1184. #if defined(_MSC_VER) && !defined(vsnprintf)
  1185. #define vsnprintf _vsnprintf
  1186. #endif
  1187. int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
  1188. {
  1189. va_list args;
  1190. va_start(args, fmt);
  1191. int w = vsnprintf(buf, buf_size, fmt, args);
  1192. va_end(args);
  1193. if (buf == NULL)
  1194. return w;
  1195. if (w == -1 || w >= (int)buf_size)
  1196. w = (int)buf_size - 1;
  1197. buf[w] = 0;
  1198. return w;
  1199. }
  1200. int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
  1201. {
  1202. int w = vsnprintf(buf, buf_size, fmt, args);
  1203. if (buf == NULL)
  1204. return w;
  1205. if (w == -1 || w >= (int)buf_size)
  1206. w = (int)buf_size - 1;
  1207. buf[w] = 0;
  1208. return w;
  1209. }
  1210. #endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
  1211. // Pass data_size == 0 for zero-terminated strings, data_size > 0 for non-string data.
  1212. // Pay attention that data_size==0 will yield different results than passing strlen(data) because the zero-terminated codepath handles ###.
  1213. // This should technically be split into two distinct functions (ImHashData/ImHashStr), perhaps once we remove the silly static variable.
  1214. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1215. ImU32 ImHash(const void* data, int data_size, ImU32 seed)
  1216. {
  1217. static ImU32 crc32_lut[256] = { 0 };
  1218. if (!crc32_lut[1])
  1219. {
  1220. const ImU32 polynomial = 0xEDB88320;
  1221. for (ImU32 i = 0; i < 256; i++)
  1222. {
  1223. ImU32 crc = i;
  1224. for (ImU32 j = 0; j < 8; j++)
  1225. crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
  1226. crc32_lut[i] = crc;
  1227. }
  1228. }
  1229. seed = ~seed;
  1230. ImU32 crc = seed;
  1231. const unsigned char* current = (const unsigned char*)data;
  1232. if (data_size > 0)
  1233. {
  1234. // Known size
  1235. while (data_size--)
  1236. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
  1237. }
  1238. else
  1239. {
  1240. // Zero-terminated string
  1241. while (unsigned char c = *current++)
  1242. {
  1243. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  1244. // Because this syntax is rarely used we are optimizing for the common case.
  1245. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  1246. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
  1247. if (c == '#' && current[0] == '#' && current[1] == '#')
  1248. crc = seed;
  1249. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1250. }
  1251. }
  1252. return ~crc;
  1253. }
  1254. FILE* ImFileOpen(const char* filename, const char* mode)
  1255. {
  1256. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__)
  1257. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
  1258. const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
  1259. const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
  1260. ImVector<ImWchar> buf;
  1261. buf.resize(filename_wsize + mode_wsize);
  1262. ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
  1263. ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
  1264. return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
  1265. #else
  1266. return fopen(filename, mode);
  1267. #endif
  1268. }
  1269. // Load file content into memory
  1270. // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
  1271. void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes)
  1272. {
  1273. IM_ASSERT(filename && file_open_mode);
  1274. if (out_file_size)
  1275. *out_file_size = 0;
  1276. FILE* f;
  1277. if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
  1278. return NULL;
  1279. long file_size_signed;
  1280. if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
  1281. {
  1282. fclose(f);
  1283. return NULL;
  1284. }
  1285. size_t file_size = (size_t)file_size_signed;
  1286. void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
  1287. if (file_data == NULL)
  1288. {
  1289. fclose(f);
  1290. return NULL;
  1291. }
  1292. if (fread(file_data, 1, file_size, f) != file_size)
  1293. {
  1294. fclose(f);
  1295. ImGui::MemFree(file_data);
  1296. return NULL;
  1297. }
  1298. if (padding_bytes > 0)
  1299. memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
  1300. fclose(f);
  1301. if (out_file_size)
  1302. *out_file_size = file_size;
  1303. return file_data;
  1304. }
  1305. //-----------------------------------------------------------------------------
  1306. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  1307. //-----------------------------------------------------------------------------
  1308. // Convert UTF-8 to 32-bits character, process single character input.
  1309. // Based on stb_from_utf8() from github.com/nothings/stb/
  1310. // We handle UTF-8 decoding error by skipping forward.
  1311. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1312. {
  1313. unsigned int c = (unsigned int)-1;
  1314. const unsigned char* str = (const unsigned char*)in_text;
  1315. if (!(*str & 0x80))
  1316. {
  1317. c = (unsigned int)(*str++);
  1318. *out_char = c;
  1319. return 1;
  1320. }
  1321. if ((*str & 0xe0) == 0xc0)
  1322. {
  1323. *out_char = 0xFFFD; // will be invalid but not end of string
  1324. if (in_text_end && in_text_end - (const char*)str < 2) return 1;
  1325. if (*str < 0xc2) return 2;
  1326. c = (unsigned int)((*str++ & 0x1f) << 6);
  1327. if ((*str & 0xc0) != 0x80) return 2;
  1328. c += (*str++ & 0x3f);
  1329. *out_char = c;
  1330. return 2;
  1331. }
  1332. if ((*str & 0xf0) == 0xe0)
  1333. {
  1334. *out_char = 0xFFFD; // will be invalid but not end of string
  1335. if (in_text_end && in_text_end - (const char*)str < 3) return 1;
  1336. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
  1337. if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
  1338. c = (unsigned int)((*str++ & 0x0f) << 12);
  1339. if ((*str & 0xc0) != 0x80) return 3;
  1340. c += (unsigned int)((*str++ & 0x3f) << 6);
  1341. if ((*str & 0xc0) != 0x80) return 3;
  1342. c += (*str++ & 0x3f);
  1343. *out_char = c;
  1344. return 3;
  1345. }
  1346. if ((*str & 0xf8) == 0xf0)
  1347. {
  1348. *out_char = 0xFFFD; // will be invalid but not end of string
  1349. if (in_text_end && in_text_end - (const char*)str < 4) return 1;
  1350. if (*str > 0xf4) return 4;
  1351. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
  1352. if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
  1353. c = (unsigned int)((*str++ & 0x07) << 18);
  1354. if ((*str & 0xc0) != 0x80) return 4;
  1355. c += (unsigned int)((*str++ & 0x3f) << 12);
  1356. if ((*str & 0xc0) != 0x80) return 4;
  1357. c += (unsigned int)((*str++ & 0x3f) << 6);
  1358. if ((*str & 0xc0) != 0x80) return 4;
  1359. c += (*str++ & 0x3f);
  1360. // utf-8 encodings of values used in surrogate pairs are invalid
  1361. if ((c & 0xFFFFF800) == 0xD800) return 4;
  1362. *out_char = c;
  1363. return 4;
  1364. }
  1365. *out_char = 0;
  1366. return 0;
  1367. }
  1368. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1369. {
  1370. ImWchar* buf_out = buf;
  1371. ImWchar* buf_end = buf + buf_size;
  1372. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1373. {
  1374. unsigned int c;
  1375. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1376. if (c == 0)
  1377. break;
  1378. if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
  1379. *buf_out++ = (ImWchar)c;
  1380. }
  1381. *buf_out = 0;
  1382. if (in_text_remaining)
  1383. *in_text_remaining = in_text;
  1384. return (int)(buf_out - buf);
  1385. }
  1386. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1387. {
  1388. int char_count = 0;
  1389. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1390. {
  1391. unsigned int c;
  1392. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1393. if (c == 0)
  1394. break;
  1395. if (c < 0x10000)
  1396. char_count++;
  1397. }
  1398. return char_count;
  1399. }
  1400. // Based on stb_to_utf8() from github.com/nothings/stb/
  1401. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  1402. {
  1403. if (c < 0x80)
  1404. {
  1405. buf[0] = (char)c;
  1406. return 1;
  1407. }
  1408. if (c < 0x800)
  1409. {
  1410. if (buf_size < 2) return 0;
  1411. buf[0] = (char)(0xc0 + (c >> 6));
  1412. buf[1] = (char)(0x80 + (c & 0x3f));
  1413. return 2;
  1414. }
  1415. if (c >= 0xdc00 && c < 0xe000)
  1416. {
  1417. return 0;
  1418. }
  1419. if (c >= 0xd800 && c < 0xdc00)
  1420. {
  1421. if (buf_size < 4) return 0;
  1422. buf[0] = (char)(0xf0 + (c >> 18));
  1423. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1424. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1425. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1426. return 4;
  1427. }
  1428. //else if (c < 0x10000)
  1429. {
  1430. if (buf_size < 3) return 0;
  1431. buf[0] = (char)(0xe0 + (c >> 12));
  1432. buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
  1433. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1434. return 3;
  1435. }
  1436. }
  1437. // Not optimal but we very rarely use this function.
  1438. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
  1439. {
  1440. unsigned int dummy = 0;
  1441. return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
  1442. }
  1443. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1444. {
  1445. if (c < 0x80) return 1;
  1446. if (c < 0x800) return 2;
  1447. if (c >= 0xdc00 && c < 0xe000) return 0;
  1448. if (c >= 0xd800 && c < 0xdc00) return 4;
  1449. return 3;
  1450. }
  1451. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1452. {
  1453. char* buf_out = buf;
  1454. const char* buf_end = buf + buf_size;
  1455. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1456. {
  1457. unsigned int c = (unsigned int)(*in_text++);
  1458. if (c < 0x80)
  1459. *buf_out++ = (char)c;
  1460. else
  1461. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
  1462. }
  1463. *buf_out = 0;
  1464. return (int)(buf_out - buf);
  1465. }
  1466. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1467. {
  1468. int bytes_count = 0;
  1469. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1470. {
  1471. unsigned int c = (unsigned int)(*in_text++);
  1472. if (c < 0x80)
  1473. bytes_count++;
  1474. else
  1475. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1476. }
  1477. return bytes_count;
  1478. }
  1479. //-----------------------------------------------------------------------------
  1480. // [SECTION] MISC HELPER/UTILTIES (Color functions)
  1481. // Note: The Convert functions are early design which are not consistent with other API.
  1482. //-----------------------------------------------------------------------------
  1483. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1484. {
  1485. float s = 1.0f/255.0f;
  1486. return ImVec4(
  1487. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1488. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1489. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1490. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1491. }
  1492. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1493. {
  1494. ImU32 out;
  1495. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1496. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1497. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1498. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1499. return out;
  1500. }
  1501. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1502. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1503. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1504. {
  1505. float K = 0.f;
  1506. if (g < b)
  1507. {
  1508. ImSwap(g, b);
  1509. K = -1.f;
  1510. }
  1511. if (r < g)
  1512. {
  1513. ImSwap(r, g);
  1514. K = -2.f / 6.f - K;
  1515. }
  1516. const float chroma = r - (g < b ? g : b);
  1517. out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
  1518. out_s = chroma / (r + 1e-20f);
  1519. out_v = r;
  1520. }
  1521. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1522. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1523. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1524. {
  1525. if (s == 0.0f)
  1526. {
  1527. // gray
  1528. out_r = out_g = out_b = v;
  1529. return;
  1530. }
  1531. h = ImFmod(h, 1.0f) / (60.0f/360.0f);
  1532. int i = (int)h;
  1533. float f = h - (float)i;
  1534. float p = v * (1.0f - s);
  1535. float q = v * (1.0f - s * f);
  1536. float t = v * (1.0f - s * (1.0f - f));
  1537. switch (i)
  1538. {
  1539. case 0: out_r = v; out_g = t; out_b = p; break;
  1540. case 1: out_r = q; out_g = v; out_b = p; break;
  1541. case 2: out_r = p; out_g = v; out_b = t; break;
  1542. case 3: out_r = p; out_g = q; out_b = v; break;
  1543. case 4: out_r = t; out_g = p; out_b = v; break;
  1544. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1545. }
  1546. }
  1547. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  1548. {
  1549. ImGuiStyle& style = GImGui->Style;
  1550. ImVec4 c = style.Colors[idx];
  1551. c.w *= style.Alpha * alpha_mul;
  1552. return ColorConvertFloat4ToU32(c);
  1553. }
  1554. ImU32 ImGui::GetColorU32(const ImVec4& col)
  1555. {
  1556. ImGuiStyle& style = GImGui->Style;
  1557. ImVec4 c = col;
  1558. c.w *= style.Alpha;
  1559. return ColorConvertFloat4ToU32(c);
  1560. }
  1561. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  1562. {
  1563. ImGuiStyle& style = GImGui->Style;
  1564. return style.Colors[idx];
  1565. }
  1566. ImU32 ImGui::GetColorU32(ImU32 col)
  1567. {
  1568. float style_alpha = GImGui->Style.Alpha;
  1569. if (style_alpha >= 1.0f)
  1570. return col;
  1571. ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  1572. a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  1573. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  1574. }
  1575. //-----------------------------------------------------------------------------
  1576. // [SECTION] ImGuiStorage
  1577. // Helper: Key->value storage
  1578. //-----------------------------------------------------------------------------
  1579. // std::lower_bound but without the bullshit
  1580. static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
  1581. {
  1582. ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
  1583. ImVector<ImGuiStorage::Pair>::iterator last = data.end();
  1584. size_t count = (size_t)(last - first);
  1585. while (count > 0)
  1586. {
  1587. size_t count2 = count >> 1;
  1588. ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
  1589. if (mid->key < key)
  1590. {
  1591. first = ++mid;
  1592. count -= count2 + 1;
  1593. }
  1594. else
  1595. {
  1596. count = count2;
  1597. }
  1598. }
  1599. return first;
  1600. }
  1601. // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
  1602. void ImGuiStorage::BuildSortByKey()
  1603. {
  1604. struct StaticFunc
  1605. {
  1606. static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
  1607. {
  1608. // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
  1609. if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
  1610. if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
  1611. return 0;
  1612. }
  1613. };
  1614. if (Data.Size > 1)
  1615. ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
  1616. }
  1617. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1618. {
  1619. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1620. if (it == Data.end() || it->key != key)
  1621. return default_val;
  1622. return it->val_i;
  1623. }
  1624. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1625. {
  1626. return GetInt(key, default_val ? 1 : 0) != 0;
  1627. }
  1628. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1629. {
  1630. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1631. if (it == Data.end() || it->key != key)
  1632. return default_val;
  1633. return it->val_f;
  1634. }
  1635. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1636. {
  1637. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1638. if (it == Data.end() || it->key != key)
  1639. return NULL;
  1640. return it->val_p;
  1641. }
  1642. // 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.
  1643. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1644. {
  1645. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1646. if (it == Data.end() || it->key != key)
  1647. it = Data.insert(it, Pair(key, default_val));
  1648. return &it->val_i;
  1649. }
  1650. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1651. {
  1652. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1653. }
  1654. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1655. {
  1656. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1657. if (it == Data.end() || it->key != key)
  1658. it = Data.insert(it, Pair(key, default_val));
  1659. return &it->val_f;
  1660. }
  1661. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1662. {
  1663. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1664. if (it == Data.end() || it->key != key)
  1665. it = Data.insert(it, Pair(key, default_val));
  1666. return &it->val_p;
  1667. }
  1668. // 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)
  1669. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1670. {
  1671. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1672. if (it == Data.end() || it->key != key)
  1673. {
  1674. Data.insert(it, Pair(key, val));
  1675. return;
  1676. }
  1677. it->val_i = val;
  1678. }
  1679. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1680. {
  1681. SetInt(key, val ? 1 : 0);
  1682. }
  1683. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1684. {
  1685. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1686. if (it == Data.end() || it->key != key)
  1687. {
  1688. Data.insert(it, Pair(key, val));
  1689. return;
  1690. }
  1691. it->val_f = val;
  1692. }
  1693. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1694. {
  1695. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1696. if (it == Data.end() || it->key != key)
  1697. {
  1698. Data.insert(it, Pair(key, val));
  1699. return;
  1700. }
  1701. it->val_p = val;
  1702. }
  1703. void ImGuiStorage::SetAllInt(int v)
  1704. {
  1705. for (int i = 0; i < Data.Size; i++)
  1706. Data[i].val_i = v;
  1707. }
  1708. //-----------------------------------------------------------------------------
  1709. // [SECTION] ImGuiTextFilter
  1710. //-----------------------------------------------------------------------------
  1711. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1712. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1713. {
  1714. if (default_filter)
  1715. {
  1716. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1717. Build();
  1718. }
  1719. else
  1720. {
  1721. InputBuf[0] = 0;
  1722. CountGrep = 0;
  1723. }
  1724. }
  1725. bool ImGuiTextFilter::Draw(const char* label, float width)
  1726. {
  1727. if (width != 0.0f)
  1728. ImGui::PushItemWidth(width);
  1729. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1730. if (width != 0.0f)
  1731. ImGui::PopItemWidth();
  1732. if (value_changed)
  1733. Build();
  1734. return value_changed;
  1735. }
  1736. void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>* out) const
  1737. {
  1738. out->resize(0);
  1739. const char* wb = b;
  1740. const char* we = wb;
  1741. while (we < e)
  1742. {
  1743. if (*we == separator)
  1744. {
  1745. out->push_back(TextRange(wb, we));
  1746. wb = we + 1;
  1747. }
  1748. we++;
  1749. }
  1750. if (wb != we)
  1751. out->push_back(TextRange(wb, we));
  1752. }
  1753. void ImGuiTextFilter::Build()
  1754. {
  1755. Filters.resize(0);
  1756. TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
  1757. input_range.split(',', &Filters);
  1758. CountGrep = 0;
  1759. for (int i = 0; i != Filters.Size; i++)
  1760. {
  1761. TextRange& f = Filters[i];
  1762. while (f.b < f.e && ImCharIsBlankA(f.b[0]))
  1763. f.b++;
  1764. while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
  1765. f.e--;
  1766. if (f.empty())
  1767. continue;
  1768. if (Filters[i].b[0] != '-')
  1769. CountGrep += 1;
  1770. }
  1771. }
  1772. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1773. {
  1774. if (Filters.empty())
  1775. return true;
  1776. if (text == NULL)
  1777. text = "";
  1778. for (int i = 0; i != Filters.Size; i++)
  1779. {
  1780. const TextRange& f = Filters[i];
  1781. if (f.empty())
  1782. continue;
  1783. if (f.b[0] == '-')
  1784. {
  1785. // Subtract
  1786. if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
  1787. return false;
  1788. }
  1789. else
  1790. {
  1791. // Grep
  1792. if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
  1793. return true;
  1794. }
  1795. }
  1796. // Implicit * grep
  1797. if (CountGrep == 0)
  1798. return true;
  1799. return false;
  1800. }
  1801. //-----------------------------------------------------------------------------
  1802. // [SECTION] ImGuiTextBuffer
  1803. //-----------------------------------------------------------------------------
  1804. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1805. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1806. #ifndef va_copy
  1807. #if defined(__GNUC__) || defined(__clang__)
  1808. #define va_copy(dest, src) __builtin_va_copy(dest, src)
  1809. #else
  1810. #define va_copy(dest, src) (dest = src)
  1811. #endif
  1812. #endif
  1813. char ImGuiTextBuffer::EmptyString[1] = { 0 };
  1814. // Helper: Text buffer for logging/accumulating text
  1815. void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
  1816. {
  1817. va_list args_copy;
  1818. va_copy(args_copy, args);
  1819. int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1820. if (len <= 0)
  1821. {
  1822. va_end(args_copy);
  1823. return;
  1824. }
  1825. // Add zero-terminator the first time
  1826. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  1827. const int needed_sz = write_off + len;
  1828. if (write_off + len >= Buf.Capacity)
  1829. {
  1830. int double_capacity = Buf.Capacity * 2;
  1831. Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
  1832. }
  1833. Buf.resize(needed_sz);
  1834. ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
  1835. va_end(args_copy);
  1836. }
  1837. void ImGuiTextBuffer::appendf(const char* fmt, ...)
  1838. {
  1839. va_list args;
  1840. va_start(args, fmt);
  1841. appendfv(fmt, args);
  1842. va_end(args);
  1843. }
  1844. //-----------------------------------------------------------------------------
  1845. // [SECTION] ImGuiListClipper
  1846. // This is currently not as flexible/powerful as it should be, needs some rework (see TODO)
  1847. //-----------------------------------------------------------------------------
  1848. static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
  1849. {
  1850. // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
  1851. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
  1852. // The clipper should probably have a 4th step to display the last item in a regular manner.
  1853. ImGui::SetCursorPosY(pos_y);
  1854. ImGuiWindow* window = ImGui::GetCurrentWindow();
  1855. 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.
  1856. window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
  1857. if (window->DC.ColumnsSet)
  1858. window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  1859. }
  1860. // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
  1861. // Use case B: Begin() called from constructor with items_height>0
  1862. // 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.
  1863. void ImGuiListClipper::Begin(int count, float items_height)
  1864. {
  1865. StartPosY = ImGui::GetCursorPosY();
  1866. ItemsHeight = items_height;
  1867. ItemsCount = count;
  1868. StepNo = 0;
  1869. DisplayEnd = DisplayStart = -1;
  1870. if (ItemsHeight > 0.0f)
  1871. {
  1872. ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
  1873. if (DisplayStart > 0)
  1874. SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
  1875. StepNo = 2;
  1876. }
  1877. }
  1878. void ImGuiListClipper::End()
  1879. {
  1880. if (ItemsCount < 0)
  1881. return;
  1882. // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
  1883. if (ItemsCount < INT_MAX)
  1884. SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
  1885. ItemsCount = -1;
  1886. StepNo = 3;
  1887. }
  1888. bool ImGuiListClipper::Step()
  1889. {
  1890. if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
  1891. {
  1892. ItemsCount = -1;
  1893. return false;
  1894. }
  1895. if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
  1896. {
  1897. DisplayStart = 0;
  1898. DisplayEnd = 1;
  1899. StartPosY = ImGui::GetCursorPosY();
  1900. StepNo = 1;
  1901. return true;
  1902. }
  1903. if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
  1904. {
  1905. if (ItemsCount == 1) { ItemsCount = -1; return false; }
  1906. float items_height = ImGui::GetCursorPosY() - StartPosY;
  1907. IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
  1908. Begin(ItemsCount-1, items_height);
  1909. DisplayStart++;
  1910. DisplayEnd++;
  1911. StepNo = 3;
  1912. return true;
  1913. }
  1914. if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
  1915. {
  1916. IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
  1917. StepNo = 3;
  1918. return true;
  1919. }
  1920. if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
  1921. End();
  1922. return false;
  1923. }
  1924. //-----------------------------------------------------------------------------
  1925. // [SECTION] RENDER HELPERS
  1926. // Those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
  1927. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
  1928. //-----------------------------------------------------------------------------
  1929. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  1930. {
  1931. const char* text_display_end = text;
  1932. if (!text_end)
  1933. text_end = (const char*)-1;
  1934. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  1935. text_display_end++;
  1936. return text_display_end;
  1937. }
  1938. // Internal ImGui functions to render text
  1939. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  1940. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  1941. {
  1942. ImGuiContext& g = *GImGui;
  1943. ImGuiWindow* window = g.CurrentWindow;
  1944. // Hide anything after a '##' string
  1945. const char* text_display_end;
  1946. if (hide_text_after_hash)
  1947. {
  1948. text_display_end = FindRenderedTextEnd(text, text_end);
  1949. }
  1950. else
  1951. {
  1952. if (!text_end)
  1953. text_end = text + strlen(text); // FIXME-OPT
  1954. text_display_end = text_end;
  1955. }
  1956. if (text != text_display_end)
  1957. {
  1958. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  1959. if (g.LogEnabled)
  1960. LogRenderedText(&pos, text, text_display_end);
  1961. }
  1962. }
  1963. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  1964. {
  1965. ImGuiContext& g = *GImGui;
  1966. ImGuiWindow* window = g.CurrentWindow;
  1967. if (!text_end)
  1968. text_end = text + strlen(text); // FIXME-OPT
  1969. if (text != text_end)
  1970. {
  1971. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  1972. if (g.LogEnabled)
  1973. LogRenderedText(&pos, text, text_end);
  1974. }
  1975. }
  1976. // Default clip_rect uses (pos_min,pos_max)
  1977. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  1978. 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)
  1979. {
  1980. // Perform CPU side clipping for single clipped element to avoid using scissor state
  1981. ImVec2 pos = pos_min;
  1982. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  1983. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  1984. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  1985. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  1986. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  1987. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  1988. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  1989. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  1990. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  1991. // Render
  1992. if (need_clipping)
  1993. {
  1994. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  1995. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  1996. }
  1997. else
  1998. {
  1999. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2000. }
  2001. }
  2002. 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)
  2003. {
  2004. // Hide anything after a '##' string
  2005. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  2006. const int text_len = (int)(text_display_end - text);
  2007. if (text_len == 0)
  2008. return;
  2009. ImGuiContext& g = *GImGui;
  2010. ImGuiWindow* window = g.CurrentWindow;
  2011. RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
  2012. if (g.LogEnabled)
  2013. LogRenderedText(&pos_min, text, text_display_end);
  2014. }
  2015. // Render a rectangle shaped with optional rounding and borders
  2016. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2017. {
  2018. ImGuiContext& g = *GImGui;
  2019. ImGuiWindow* window = g.CurrentWindow;
  2020. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2021. const float border_size = g.Style.FrameBorderSize;
  2022. if (border && border_size > 0.0f)
  2023. {
  2024. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  2025. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  2026. }
  2027. }
  2028. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  2029. {
  2030. ImGuiContext& g = *GImGui;
  2031. ImGuiWindow* window = g.CurrentWindow;
  2032. const float border_size = g.Style.FrameBorderSize;
  2033. if (border_size > 0.0f)
  2034. {
  2035. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  2036. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  2037. }
  2038. }
  2039. // Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
  2040. void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
  2041. {
  2042. ImGuiContext& g = *GImGui;
  2043. const float h = g.FontSize * 1.00f;
  2044. float r = h * 0.40f * scale;
  2045. ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
  2046. ImVec2 a, b, c;
  2047. switch (dir)
  2048. {
  2049. case ImGuiDir_Up:
  2050. case ImGuiDir_Down:
  2051. if (dir == ImGuiDir_Up) r = -r;
  2052. a = ImVec2(+0.000f,+0.750f) * r;
  2053. b = ImVec2(-0.866f,-0.750f) * r;
  2054. c = ImVec2(+0.866f,-0.750f) * r;
  2055. break;
  2056. case ImGuiDir_Left:
  2057. case ImGuiDir_Right:
  2058. if (dir == ImGuiDir_Left) r = -r;
  2059. a = ImVec2(+0.750f,+0.000f) * r;
  2060. b = ImVec2(-0.750f,+0.866f) * r;
  2061. c = ImVec2(-0.750f,-0.866f) * r;
  2062. break;
  2063. case ImGuiDir_None:
  2064. case ImGuiDir_COUNT:
  2065. IM_ASSERT(0);
  2066. break;
  2067. }
  2068. g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
  2069. }
  2070. void ImGui::RenderBullet(ImVec2 pos)
  2071. {
  2072. ImGuiContext& g = *GImGui;
  2073. ImGuiWindow* window = g.CurrentWindow;
  2074. window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
  2075. }
  2076. void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
  2077. {
  2078. ImGuiContext& g = *GImGui;
  2079. ImGuiWindow* window = g.CurrentWindow;
  2080. float thickness = ImMax(sz / 5.0f, 1.0f);
  2081. sz -= thickness*0.5f;
  2082. pos += ImVec2(thickness*0.25f, thickness*0.25f);
  2083. float third = sz / 3.0f;
  2084. float bx = pos.x + third;
  2085. float by = pos.y + sz - third*0.5f;
  2086. window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
  2087. window->DrawList->PathLineTo(ImVec2(bx, by));
  2088. window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
  2089. window->DrawList->PathStroke(col, false, thickness);
  2090. }
  2091. void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
  2092. {
  2093. ImGuiContext& g = *GImGui;
  2094. if (id != g.NavId)
  2095. return;
  2096. if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
  2097. return;
  2098. ImGuiWindow* window = g.CurrentWindow;
  2099. if (window->DC.NavHideHighlightOneFrame)
  2100. return;
  2101. float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
  2102. ImRect display_rect = bb;
  2103. display_rect.ClipWith(window->ClipRect);
  2104. if (flags & ImGuiNavHighlightFlags_TypeDefault)
  2105. {
  2106. const float THICKNESS = 2.0f;
  2107. const float DISTANCE = 3.0f + THICKNESS * 0.5f;
  2108. display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
  2109. bool fully_visible = window->ClipRect.Contains(display_rect);
  2110. if (!fully_visible)
  2111. window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
  2112. 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, ImDrawCornerFlags_All, THICKNESS);
  2113. if (!fully_visible)
  2114. window->DrawList->PopClipRect();
  2115. }
  2116. if (flags & ImGuiNavHighlightFlags_TypeThin)
  2117. {
  2118. window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
  2119. }
  2120. }
  2121. //-----------------------------------------------------------------------------
  2122. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  2123. //-----------------------------------------------------------------------------
  2124. // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
  2125. ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
  2126. : DrawListInst(&context->DrawListSharedData)
  2127. {
  2128. Name = ImStrdup(name);
  2129. ID = ImHash(name, 0);
  2130. IDStack.push_back(ID);
  2131. Flags = ImGuiWindowFlags_None;
  2132. Pos = ImVec2(0.0f, 0.0f);
  2133. Size = SizeFull = ImVec2(0.0f, 0.0f);
  2134. SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  2135. WindowPadding = ImVec2(0.0f, 0.0f);
  2136. WindowRounding = 0.0f;
  2137. WindowBorderSize = 0.0f;
  2138. NameBufLen = (int)strlen(name) + 1;
  2139. MoveId = GetID("#MOVE");
  2140. ChildId = 0;
  2141. Scroll = ImVec2(0.0f, 0.0f);
  2142. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  2143. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  2144. ScrollbarSizes = ImVec2(0.0f, 0.0f);
  2145. ScrollbarX = ScrollbarY = false;
  2146. Active = WasActive = false;
  2147. WriteAccessed = false;
  2148. Collapsed = false;
  2149. WantCollapseToggle = false;
  2150. SkipItems = false;
  2151. Appearing = false;
  2152. Hidden = false;
  2153. HasCloseButton = false;
  2154. BeginCount = 0;
  2155. BeginOrderWithinParent = -1;
  2156. BeginOrderWithinContext = -1;
  2157. PopupId = 0;
  2158. AutoFitFramesX = AutoFitFramesY = -1;
  2159. AutoFitOnlyGrows = false;
  2160. AutoFitChildAxises = 0x00;
  2161. AutoPosLastDirection = ImGuiDir_None;
  2162. HiddenFramesRegular = HiddenFramesForResize = 0;
  2163. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  2164. SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
  2165. LastFrameActive = -1;
  2166. ItemWidthDefault = 0.0f;
  2167. FontWindowScale = 1.0f;
  2168. SettingsIdx = -1;
  2169. DrawList = &DrawListInst;
  2170. DrawList->_OwnerName = Name;
  2171. ParentWindow = NULL;
  2172. RootWindow = NULL;
  2173. RootWindowForTitleBarHighlight = NULL;
  2174. RootWindowForNav = NULL;
  2175. NavLastIds[0] = NavLastIds[1] = 0;
  2176. NavRectRel[0] = NavRectRel[1] = ImRect();
  2177. NavLastChildNavWindow = NULL;
  2178. FocusIdxAllCounter = FocusIdxTabCounter = -1;
  2179. FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
  2180. FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
  2181. }
  2182. ImGuiWindow::~ImGuiWindow()
  2183. {
  2184. IM_ASSERT(DrawList == &DrawListInst);
  2185. IM_DELETE(Name);
  2186. for (int i = 0; i != ColumnsStorage.Size; i++)
  2187. ColumnsStorage[i].~ImGuiColumnsSet();
  2188. }
  2189. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  2190. {
  2191. ImGuiID seed = IDStack.back();
  2192. ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  2193. ImGui::KeepAliveID(id);
  2194. return id;
  2195. }
  2196. ImGuiID ImGuiWindow::GetID(const void* ptr)
  2197. {
  2198. ImGuiID seed = IDStack.back();
  2199. ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
  2200. ImGui::KeepAliveID(id);
  2201. return id;
  2202. }
  2203. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  2204. {
  2205. ImGuiID seed = IDStack.back();
  2206. return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  2207. }
  2208. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
  2209. {
  2210. ImGuiID seed = IDStack.back();
  2211. return ImHash(&ptr, sizeof(void*), seed);
  2212. }
  2213. // This is only used in rare/specific situations to manufacture an ID out of nowhere.
  2214. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
  2215. {
  2216. ImGuiID seed = IDStack.back();
  2217. const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
  2218. ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed);
  2219. ImGui::KeepAliveID(id);
  2220. return id;
  2221. }
  2222. static void SetCurrentWindow(ImGuiWindow* window)
  2223. {
  2224. ImGuiContext& g = *GImGui;
  2225. g.CurrentWindow = window;
  2226. if (window)
  2227. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  2228. }
  2229. void ImGui::SetNavID(ImGuiID id, int nav_layer)
  2230. {
  2231. ImGuiContext& g = *GImGui;
  2232. IM_ASSERT(g.NavWindow);
  2233. IM_ASSERT(nav_layer == 0 || nav_layer == 1);
  2234. g.NavId = id;
  2235. g.NavWindow->NavLastIds[nav_layer] = id;
  2236. }
  2237. void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
  2238. {
  2239. ImGuiContext& g = *GImGui;
  2240. SetNavID(id, nav_layer);
  2241. g.NavWindow->NavRectRel[nav_layer] = rect_rel;
  2242. g.NavMousePosDirty = true;
  2243. g.NavDisableHighlight = false;
  2244. g.NavDisableMouseHover = true;
  2245. }
  2246. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  2247. {
  2248. ImGuiContext& g = *GImGui;
  2249. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  2250. if (g.ActiveIdIsJustActivated)
  2251. {
  2252. g.ActiveIdTimer = 0.0f;
  2253. g.ActiveIdHasBeenEdited = false;
  2254. if (id != 0)
  2255. {
  2256. g.LastActiveId = id;
  2257. g.LastActiveIdTimer = 0.0f;
  2258. }
  2259. }
  2260. g.ActiveId = id;
  2261. g.ActiveIdAllowNavDirFlags = 0;
  2262. g.ActiveIdAllowOverlap = false;
  2263. g.ActiveIdWindow = window;
  2264. if (id)
  2265. {
  2266. g.ActiveIdIsAlive = id;
  2267. g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
  2268. }
  2269. }
  2270. // FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring.
  2271. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
  2272. {
  2273. ImGuiContext& g = *GImGui;
  2274. IM_ASSERT(id != 0);
  2275. // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
  2276. const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
  2277. if (g.NavWindow != window)
  2278. g.NavInitRequest = false;
  2279. g.NavId = id;
  2280. g.NavWindow = window;
  2281. g.NavLayer = nav_layer;
  2282. window->NavLastIds[nav_layer] = id;
  2283. if (window->DC.LastItemId == id)
  2284. window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
  2285. if (g.ActiveIdSource == ImGuiInputSource_Nav)
  2286. g.NavDisableMouseHover = true;
  2287. else
  2288. g.NavDisableHighlight = true;
  2289. }
  2290. void ImGui::ClearActiveID()
  2291. {
  2292. SetActiveID(0, NULL);
  2293. }
  2294. void ImGui::SetHoveredID(ImGuiID id)
  2295. {
  2296. ImGuiContext& g = *GImGui;
  2297. g.HoveredId = id;
  2298. g.HoveredIdAllowOverlap = false;
  2299. if (id != 0 && g.HoveredIdPreviousFrame != id)
  2300. g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
  2301. }
  2302. ImGuiID ImGui::GetHoveredID()
  2303. {
  2304. ImGuiContext& g = *GImGui;
  2305. return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
  2306. }
  2307. void ImGui::KeepAliveID(ImGuiID id)
  2308. {
  2309. ImGuiContext& g = *GImGui;
  2310. if (g.ActiveId == id)
  2311. g.ActiveIdIsAlive = id;
  2312. if (g.ActiveIdPreviousFrame == id)
  2313. g.ActiveIdPreviousFrameIsAlive = true;
  2314. }
  2315. void ImGui::MarkItemEdited(ImGuiID id)
  2316. {
  2317. // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
  2318. // 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.
  2319. (void)id; // Avoid unused variable warnings when asserts are compiled out.
  2320. ImGuiContext& g = *GImGui;
  2321. IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
  2322. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
  2323. g.ActiveIdHasBeenEdited = true;
  2324. g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
  2325. }
  2326. static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
  2327. {
  2328. // An active popup disable hovering on other windows (apart from its own children)
  2329. // FIXME-OPT: This could be cached/stored within the window.
  2330. ImGuiContext& g = *GImGui;
  2331. if (g.NavWindow)
  2332. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
  2333. if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
  2334. {
  2335. // For the purpose of those flags we differentiate "standard popup" from "modal popup"
  2336. // NB: The order of those two tests is important because Modal windows are also Popups.
  2337. if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
  2338. return false;
  2339. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  2340. return false;
  2341. }
  2342. return true;
  2343. }
  2344. // Advance cursor given item size for layout.
  2345. void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
  2346. {
  2347. ImGuiContext& g = *GImGui;
  2348. ImGuiWindow* window = g.CurrentWindow;
  2349. if (window->SkipItems)
  2350. return;
  2351. // Always align ourselves on pixel boundaries
  2352. const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y);
  2353. const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
  2354. //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]
  2355. window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
  2356. window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y));
  2357. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  2358. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
  2359. //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
  2360. window->DC.PrevLineSize.y = line_height;
  2361. window->DC.PrevLineTextBaseOffset = text_base_offset;
  2362. window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f;
  2363. // Horizontal layout mode
  2364. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  2365. SameLine();
  2366. }
  2367. void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
  2368. {
  2369. ItemSize(bb.GetSize(), text_offset_y);
  2370. }
  2371. // Declare item bounding box for clipping and interaction.
  2372. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  2373. // declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
  2374. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
  2375. {
  2376. ImGuiContext& g = *GImGui;
  2377. ImGuiWindow* window = g.CurrentWindow;
  2378. if (id != 0)
  2379. {
  2380. // Navigation processing runs prior to clipping early-out
  2381. // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
  2382. // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
  2383. // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
  2384. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
  2385. window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
  2386. if (g.NavId == id || g.NavAnyRequest)
  2387. if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
  2388. if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
  2389. NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
  2390. }
  2391. window->DC.LastItemId = id;
  2392. window->DC.LastItemRect = bb;
  2393. window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
  2394. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2395. if (id != 0)
  2396. ImGuiTestEngineHook_ItemAdd(&g, bb, id);
  2397. #endif
  2398. // Clipping test
  2399. const bool is_clipped = IsClippedEx(bb, id, false);
  2400. if (is_clipped)
  2401. return false;
  2402. //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
  2403. // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
  2404. if (IsMouseHoveringRect(bb.Min, bb.Max))
  2405. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
  2406. return true;
  2407. }
  2408. // This is roughly matching the behavior of internal-facing ItemHoverable()
  2409. // - 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()
  2410. // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
  2411. bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
  2412. {
  2413. ImGuiContext& g = *GImGui;
  2414. ImGuiWindow* window = g.CurrentWindow;
  2415. if (g.NavDisableMouseHover && !g.NavDisableHighlight)
  2416. return IsItemFocused();
  2417. // Test for bounding box overlap, as updated as ItemAdd()
  2418. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  2419. return false;
  2420. IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
  2421. // Test if we are hovering the right window (our window could be behind another window)
  2422. // [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 to use IsItemHovered() after EndChild() itself.
  2423. // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
  2424. //if (g.HoveredWindow != window)
  2425. // return false;
  2426. if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
  2427. return false;
  2428. // Test if another item is active (e.g. being dragged)
  2429. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  2430. if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
  2431. return false;
  2432. // Test if interactions on this window are blocked by an active popup or modal
  2433. if (!IsWindowContentHoverable(window, flags))
  2434. return false;
  2435. // Test if the item is disabled
  2436. if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
  2437. return false;
  2438. // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case.
  2439. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
  2440. return false;
  2441. return true;
  2442. }
  2443. // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
  2444. bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
  2445. {
  2446. ImGuiContext& g = *GImGui;
  2447. if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
  2448. return false;
  2449. ImGuiWindow* window = g.CurrentWindow;
  2450. if (g.HoveredWindow != window)
  2451. return false;
  2452. if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
  2453. return false;
  2454. if (!IsMouseHoveringRect(bb.Min, bb.Max))
  2455. return false;
  2456. if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
  2457. return false;
  2458. if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
  2459. return false;
  2460. SetHoveredID(id);
  2461. return true;
  2462. }
  2463. bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
  2464. {
  2465. ImGuiContext& g = *GImGui;
  2466. ImGuiWindow* window = g.CurrentWindow;
  2467. if (!bb.Overlaps(window->ClipRect))
  2468. if (id == 0 || id != g.ActiveId)
  2469. if (clip_even_when_logged || !g.LogEnabled)
  2470. return true;
  2471. return false;
  2472. }
  2473. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
  2474. {
  2475. ImGuiContext& g = *GImGui;
  2476. const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
  2477. window->FocusIdxAllCounter++;
  2478. if (is_tab_stop)
  2479. window->FocusIdxTabCounter++;
  2480. // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
  2481. // Note that we can always TAB out of a widget that doesn't allow tabbing in.
  2482. if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
  2483. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
  2484. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
  2485. return true;
  2486. if (is_tab_stop && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
  2487. {
  2488. g.NavJustTabbedId = id;
  2489. return true;
  2490. }
  2491. return false;
  2492. }
  2493. void ImGui::FocusableItemUnregister(ImGuiWindow* window)
  2494. {
  2495. window->FocusIdxAllCounter--;
  2496. window->FocusIdxTabCounter--;
  2497. }
  2498. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
  2499. {
  2500. ImGuiContext& g = *GImGui;
  2501. ImVec2 content_max;
  2502. if (size.x < 0.0f || size.y < 0.0f)
  2503. content_max = g.CurrentWindow->Pos + GetContentRegionMax();
  2504. if (size.x <= 0.0f)
  2505. size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
  2506. if (size.y <= 0.0f)
  2507. size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
  2508. return size;
  2509. }
  2510. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  2511. {
  2512. if (wrap_pos_x < 0.0f)
  2513. return 0.0f;
  2514. ImGuiWindow* window = GetCurrentWindowRead();
  2515. if (wrap_pos_x == 0.0f)
  2516. wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
  2517. else if (wrap_pos_x > 0.0f)
  2518. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  2519. return ImMax(wrap_pos_x - pos.x, 1.0f);
  2520. }
  2521. void* ImGui::MemAlloc(size_t size)
  2522. {
  2523. if (ImGuiContext* ctx = GImGui)
  2524. ctx->IO.MetricsActiveAllocations++;
  2525. return GImAllocatorAllocFunc(size, GImAllocatorUserData);
  2526. }
  2527. void ImGui::MemFree(void* ptr)
  2528. {
  2529. if (ptr)
  2530. if (ImGuiContext* ctx = GImGui)
  2531. ctx->IO.MetricsActiveAllocations--;
  2532. return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
  2533. }
  2534. const char* ImGui::GetClipboardText()
  2535. {
  2536. return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
  2537. }
  2538. void ImGui::SetClipboardText(const char* text)
  2539. {
  2540. if (GImGui->IO.SetClipboardTextFn)
  2541. GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
  2542. }
  2543. const char* ImGui::GetVersion()
  2544. {
  2545. return IMGUI_VERSION;
  2546. }
  2547. // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
  2548. // 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
  2549. ImGuiContext* ImGui::GetCurrentContext()
  2550. {
  2551. return GImGui;
  2552. }
  2553. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  2554. {
  2555. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  2556. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  2557. #else
  2558. GImGui = ctx;
  2559. #endif
  2560. }
  2561. // Helper function to verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
  2562. // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. you may see different structures from what imgui.cpp sees which is highly problematic.
  2563. 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)
  2564. {
  2565. bool error = false;
  2566. if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
  2567. if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
  2568. if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
  2569. if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
  2570. if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
  2571. if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
  2572. return !error;
  2573. }
  2574. void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data)
  2575. {
  2576. GImAllocatorAllocFunc = alloc_func;
  2577. GImAllocatorFreeFunc = free_func;
  2578. GImAllocatorUserData = user_data;
  2579. }
  2580. ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
  2581. {
  2582. ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
  2583. if (GImGui == NULL)
  2584. SetCurrentContext(ctx);
  2585. Initialize(ctx);
  2586. return ctx;
  2587. }
  2588. void ImGui::DestroyContext(ImGuiContext* ctx)
  2589. {
  2590. if (ctx == NULL)
  2591. ctx = GImGui;
  2592. Shutdown(ctx);
  2593. if (GImGui == ctx)
  2594. SetCurrentContext(NULL);
  2595. IM_DELETE(ctx);
  2596. }
  2597. ImGuiIO& ImGui::GetIO()
  2598. {
  2599. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2600. return GImGui->IO;
  2601. }
  2602. ImGuiStyle& ImGui::GetStyle()
  2603. {
  2604. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2605. return GImGui->Style;
  2606. }
  2607. // Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
  2608. ImDrawData* ImGui::GetDrawData()
  2609. {
  2610. ImGuiContext& g = *GImGui;
  2611. return g.DrawData.Valid ? &g.DrawData : NULL;
  2612. }
  2613. double ImGui::GetTime()
  2614. {
  2615. return GImGui->Time;
  2616. }
  2617. int ImGui::GetFrameCount()
  2618. {
  2619. return GImGui->FrameCount;
  2620. }
  2621. static ImDrawList* GetOverlayDrawList(ImGuiWindow*)
  2622. {
  2623. // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'viewport' branches.
  2624. return &GImGui->OverlayDrawList;
  2625. }
  2626. ImDrawList* ImGui::GetOverlayDrawList()
  2627. {
  2628. return &GImGui->OverlayDrawList;
  2629. }
  2630. ImDrawListSharedData* ImGui::GetDrawListSharedData()
  2631. {
  2632. return &GImGui->DrawListSharedData;
  2633. }
  2634. void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
  2635. {
  2636. // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
  2637. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
  2638. // This is because we want ActiveId to be set even when the window is stuck from moving.
  2639. ImGuiContext& g = *GImGui;
  2640. FocusWindow(window);
  2641. SetActiveID(window->MoveId, window);
  2642. g.NavDisableHighlight = true;
  2643. g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
  2644. if (!(window->Flags & ImGuiWindowFlags_NoMove) && !(window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
  2645. g.MovingWindow = window;
  2646. }
  2647. // Handle mouse moving window
  2648. // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
  2649. void ImGui::UpdateMouseMovingWindowNewFrame()
  2650. {
  2651. ImGuiContext& g = *GImGui;
  2652. if (g.MovingWindow != NULL)
  2653. {
  2654. // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
  2655. // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
  2656. KeepAliveID(g.ActiveId);
  2657. IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
  2658. ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
  2659. if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
  2660. {
  2661. ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
  2662. if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
  2663. {
  2664. MarkIniSettingsDirty(moving_window);
  2665. SetWindowPos(moving_window, pos, ImGuiCond_Always);
  2666. }
  2667. FocusWindow(g.MovingWindow);
  2668. }
  2669. else
  2670. {
  2671. ClearActiveID();
  2672. g.MovingWindow = NULL;
  2673. }
  2674. }
  2675. else
  2676. {
  2677. // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
  2678. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
  2679. {
  2680. KeepAliveID(g.ActiveId);
  2681. if (!g.IO.MouseDown[0])
  2682. ClearActiveID();
  2683. }
  2684. }
  2685. }
  2686. // Initiate moving window, handle left-click and right-click focus
  2687. void ImGui::UpdateMouseMovingWindowEndFrame()
  2688. {
  2689. // Initiate moving window
  2690. ImGuiContext& g = *GImGui;
  2691. if (g.ActiveId != 0 || g.HoveredId != 0)
  2692. return;
  2693. // Unless we just made a window/popup appear
  2694. if (g.NavWindow && g.NavWindow->Appearing)
  2695. return;
  2696. // Click to focus window and start moving (after we're done with all our widgets)
  2697. if (g.IO.MouseClicked[0])
  2698. {
  2699. if (g.HoveredRootWindow != NULL)
  2700. {
  2701. StartMouseMovingWindow(g.HoveredWindow);
  2702. if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar))
  2703. if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
  2704. g.MovingWindow = NULL;
  2705. }
  2706. else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL)
  2707. {
  2708. FocusWindow(NULL); // Clicking on void disable focus
  2709. }
  2710. }
  2711. // With right mouse button we close popups without changing focus
  2712. // (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger)
  2713. if (g.IO.MouseClicked[1])
  2714. {
  2715. // Find the top-most window between HoveredWindow and the front most Modal Window.
  2716. // This is where we can trim the popup stack.
  2717. ImGuiWindow* modal = GetFrontMostPopupModal();
  2718. bool hovered_window_above_modal = false;
  2719. if (modal == NULL)
  2720. hovered_window_above_modal = true;
  2721. for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
  2722. {
  2723. ImGuiWindow* window = g.Windows[i];
  2724. if (window == modal)
  2725. break;
  2726. if (window == g.HoveredWindow)
  2727. hovered_window_above_modal = true;
  2728. }
  2729. ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal);
  2730. }
  2731. }
  2732. static bool IsWindowActiveAndVisible(ImGuiWindow* window)
  2733. {
  2734. return (window->Active) && (!window->Hidden);
  2735. }
  2736. static void ImGui::UpdateMouseInputs()
  2737. {
  2738. ImGuiContext& g = *GImGui;
  2739. // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
  2740. if (IsMousePosValid(&g.IO.MousePos))
  2741. g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
  2742. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
  2743. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
  2744. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  2745. else
  2746. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  2747. if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
  2748. g.NavDisableMouseHover = false;
  2749. g.IO.MousePosPrev = g.IO.MousePos;
  2750. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2751. {
  2752. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  2753. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  2754. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  2755. g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  2756. g.IO.MouseDoubleClicked[i] = false;
  2757. if (g.IO.MouseClicked[i])
  2758. {
  2759. if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
  2760. {
  2761. ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  2762. if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  2763. g.IO.MouseDoubleClicked[i] = true;
  2764. g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
  2765. }
  2766. else
  2767. {
  2768. g.IO.MouseClickedTime[i] = g.Time;
  2769. }
  2770. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  2771. g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
  2772. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  2773. }
  2774. else if (g.IO.MouseDown[i])
  2775. {
  2776. // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
  2777. ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  2778. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
  2779. g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
  2780. g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
  2781. }
  2782. if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
  2783. g.NavDisableMouseHover = false;
  2784. }
  2785. }
  2786. void ImGui::UpdateMouseWheel()
  2787. {
  2788. ImGuiContext& g = *GImGui;
  2789. if (!g.HoveredWindow || g.HoveredWindow->Collapsed)
  2790. return;
  2791. if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
  2792. return;
  2793. // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
  2794. ImGuiWindow* window = g.HoveredWindow;
  2795. ImGuiWindow* scroll_window = window;
  2796. while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs) && scroll_window->ParentWindow)
  2797. scroll_window = scroll_window->ParentWindow;
  2798. const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs);
  2799. if (g.IO.MouseWheel != 0.0f)
  2800. {
  2801. if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  2802. {
  2803. // Zoom / Scale window
  2804. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  2805. const float scale = new_font_scale / window->FontWindowScale;
  2806. window->FontWindowScale = new_font_scale;
  2807. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  2808. window->Pos += offset;
  2809. window->Size *= scale;
  2810. window->SizeFull *= scale;
  2811. }
  2812. else if (!g.IO.KeyCtrl && scroll_allowed)
  2813. {
  2814. // Mouse wheel vertical scrolling
  2815. float scroll_amount = 5 * scroll_window->CalcFontSize();
  2816. scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
  2817. SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
  2818. }
  2819. }
  2820. if (g.IO.MouseWheelH != 0.0f && scroll_allowed && !g.IO.KeyCtrl)
  2821. {
  2822. // Mouse wheel horizontal scrolling (for hardware that supports it)
  2823. float scroll_amount = scroll_window->CalcFontSize();
  2824. SetWindowScrollX(scroll_window, scroll_window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
  2825. }
  2826. }
  2827. // 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)
  2828. void ImGui::UpdateHoveredWindowAndCaptureFlags()
  2829. {
  2830. ImGuiContext& g = *GImGui;
  2831. // Find the window hovered by mouse:
  2832. // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
  2833. // - 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.
  2834. // - 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.
  2835. FindHoveredWindow();
  2836. // Modal windows prevents cursor from hovering behind them.
  2837. ImGuiWindow* modal_window = GetFrontMostPopupModal();
  2838. if (modal_window)
  2839. if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
  2840. g.HoveredRootWindow = g.HoveredWindow = NULL;
  2841. // Disabled mouse?
  2842. if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
  2843. g.HoveredWindow = g.HoveredRootWindow = NULL;
  2844. // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
  2845. int mouse_earliest_button_down = -1;
  2846. bool mouse_any_down = false;
  2847. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2848. {
  2849. if (g.IO.MouseClicked[i])
  2850. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
  2851. mouse_any_down |= g.IO.MouseDown[i];
  2852. if (g.IO.MouseDown[i])
  2853. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
  2854. mouse_earliest_button_down = i;
  2855. }
  2856. const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
  2857. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  2858. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
  2859. const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
  2860. if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
  2861. g.HoveredWindow = g.HoveredRootWindow = NULL;
  2862. // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app)
  2863. if (g.WantCaptureMouseNextFrame != -1)
  2864. g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
  2865. else
  2866. g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
  2867. // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app)
  2868. if (g.WantCaptureKeyboardNextFrame != -1)
  2869. g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
  2870. else
  2871. g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
  2872. if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
  2873. g.IO.WantCaptureKeyboard = true;
  2874. // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
  2875. g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
  2876. }
  2877. void ImGui::NewFrame()
  2878. {
  2879. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2880. ImGuiContext& g = *GImGui;
  2881. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2882. ImGuiTestEngineHook_PreNewFrame(&g);
  2883. #endif
  2884. // Check user data
  2885. // (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)
  2886. IM_ASSERT(g.Initialized);
  2887. IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
  2888. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
  2889. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  2890. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  2891. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
  2892. IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)");
  2893. IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
  2894. for (int n = 0; n < ImGuiKey_COUNT; n++)
  2895. 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..512, or -1 for unmapped key)");
  2896. // Perform simple 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 recently added in 1.60 WIP)
  2897. if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
  2898. IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
  2899. // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
  2900. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
  2901. g.IO.ConfigWindowsResizeFromEdges = false;
  2902. // Load settings on first frame (if not explicitly loaded manually before)
  2903. if (!g.SettingsLoaded)
  2904. {
  2905. IM_ASSERT(g.SettingsWindows.empty());
  2906. if (g.IO.IniFilename)
  2907. LoadIniSettingsFromDisk(g.IO.IniFilename);
  2908. g.SettingsLoaded = true;
  2909. }
  2910. // Save settings (with a delay after the last modification, so we don't spam disk too much)
  2911. if (g.SettingsDirtyTimer > 0.0f)
  2912. {
  2913. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  2914. if (g.SettingsDirtyTimer <= 0.0f)
  2915. {
  2916. if (g.IO.IniFilename != NULL)
  2917. SaveIniSettingsToDisk(g.IO.IniFilename);
  2918. else
  2919. g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
  2920. g.SettingsDirtyTimer = 0.0f;
  2921. }
  2922. }
  2923. g.Time += g.IO.DeltaTime;
  2924. g.FrameScopeActive = true;
  2925. g.FrameCount += 1;
  2926. g.TooltipOverrideCount = 0;
  2927. g.WindowsActiveCount = 0;
  2928. // Setup current font and draw list
  2929. g.IO.Fonts->Locked = true;
  2930. SetCurrentFont(GetDefaultFont());
  2931. IM_ASSERT(g.Font->IsLoaded());
  2932. g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
  2933. g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
  2934. g.OverlayDrawList.Clear();
  2935. g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
  2936. g.OverlayDrawList.PushClipRectFullScreen();
  2937. g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
  2938. // Mark rendering data as invalid to prevent user who may have a handle on it to use it
  2939. g.DrawData.Clear();
  2940. // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
  2941. if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
  2942. KeepAliveID(g.DragDropPayload.SourceId);
  2943. // Clear reference to active widget if the widget isn't alive anymore
  2944. if (!g.HoveredIdPreviousFrame)
  2945. g.HoveredIdTimer = 0.0f;
  2946. if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
  2947. g.HoveredIdNotActiveTimer = 0.0f;
  2948. if (g.HoveredId)
  2949. g.HoveredIdTimer += g.IO.DeltaTime;
  2950. if (g.HoveredId && g.ActiveId != g.HoveredId)
  2951. g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
  2952. g.HoveredIdPreviousFrame = g.HoveredId;
  2953. g.HoveredId = 0;
  2954. g.HoveredIdAllowOverlap = false;
  2955. if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  2956. ClearActiveID();
  2957. if (g.ActiveId)
  2958. g.ActiveIdTimer += g.IO.DeltaTime;
  2959. g.LastActiveIdTimer += g.IO.DeltaTime;
  2960. g.ActiveIdPreviousFrame = g.ActiveId;
  2961. g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
  2962. g.ActiveIdPreviousFrameHasBeenEdited = g.ActiveIdHasBeenEdited;
  2963. g.ActiveIdIsAlive = 0;
  2964. g.ActiveIdPreviousFrameIsAlive = false;
  2965. g.ActiveIdIsJustActivated = false;
  2966. if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
  2967. g.ScalarAsInputTextId = 0;
  2968. // Drag and drop
  2969. g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
  2970. g.DragDropAcceptIdCurr = 0;
  2971. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  2972. g.DragDropWithinSourceOrTarget = false;
  2973. // Update keyboard input state
  2974. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  2975. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  2976. g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  2977. // Update gamepad/keyboard directional navigation
  2978. NavUpdate();
  2979. // Update mouse input state
  2980. UpdateMouseInputs();
  2981. // Calculate frame-rate for the user, as a purely luxurious feature
  2982. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  2983. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  2984. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  2985. g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
  2986. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
  2987. UpdateMouseMovingWindowNewFrame();
  2988. UpdateHoveredWindowAndCaptureFlags();
  2989. // Background darkening/whitening
  2990. if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
  2991. g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  2992. else
  2993. g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
  2994. g.MouseCursor = ImGuiMouseCursor_Arrow;
  2995. g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
  2996. g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  2997. // Mouse wheel scrolling, scale
  2998. UpdateMouseWheel();
  2999. // Pressing TAB activate widget focus
  3000. if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false))
  3001. {
  3002. if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
  3003. g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
  3004. else
  3005. g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0;
  3006. }
  3007. g.NavIdTabCounter = INT_MAX;
  3008. // Mark all windows as not visible
  3009. IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
  3010. for (int i = 0; i != g.Windows.Size; i++)
  3011. {
  3012. ImGuiWindow* window = g.Windows[i];
  3013. window->WasActive = window->Active;
  3014. window->Active = false;
  3015. window->WriteAccessed = false;
  3016. }
  3017. // Closing the focused window restore focus to the first active root window in descending z-order
  3018. if (g.NavWindow && !g.NavWindow->WasActive)
  3019. FocusPreviousWindowIgnoringOne(NULL);
  3020. // No window should be open at the beginning of the frame.
  3021. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  3022. g.CurrentWindowStack.resize(0);
  3023. g.BeginPopupStack.resize(0);
  3024. ClosePopupsOverWindow(g.NavWindow);
  3025. // Create implicit/fallback window - which we will only render it if the user has added something to it.
  3026. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
  3027. // This fallback is particularly important as it avoid ImGui:: calls from crashing.
  3028. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
  3029. Begin("Debug##Default");
  3030. g.FrameScopePushedImplicitWindow = true;
  3031. #ifdef IMGUI_ENABLE_TEST_ENGINE
  3032. ImGuiTestEngineHook_PostNewFrame(&g);
  3033. #endif
  3034. }
  3035. void ImGui::Initialize(ImGuiContext* context)
  3036. {
  3037. ImGuiContext& g = *context;
  3038. IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
  3039. // Add .ini handle for ImGuiWindow type
  3040. ImGuiSettingsHandler ini_handler;
  3041. ini_handler.TypeName = "Window";
  3042. ini_handler.TypeHash = ImHash("Window", 0, 0);
  3043. ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
  3044. ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
  3045. ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
  3046. g.SettingsHandlers.push_front(ini_handler);
  3047. g.Initialized = true;
  3048. }
  3049. // This function is merely here to free heap allocations.
  3050. void ImGui::Shutdown(ImGuiContext* context)
  3051. {
  3052. // 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)
  3053. ImGuiContext& g = *context;
  3054. if (g.IO.Fonts && g.FontAtlasOwnedByContext)
  3055. {
  3056. g.IO.Fonts->Locked = false;
  3057. IM_DELETE(g.IO.Fonts);
  3058. }
  3059. g.IO.Fonts = NULL;
  3060. // Cleanup of other data are conditional on actually having initialized ImGui.
  3061. if (!g.Initialized)
  3062. return;
  3063. // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
  3064. if (g.SettingsLoaded && g.IO.IniFilename != NULL)
  3065. {
  3066. ImGuiContext* backup_context = GImGui;
  3067. SetCurrentContext(context);
  3068. SaveIniSettingsToDisk(g.IO.IniFilename);
  3069. SetCurrentContext(backup_context);
  3070. }
  3071. // Clear everything else
  3072. for (int i = 0; i < g.Windows.Size; i++)
  3073. IM_DELETE(g.Windows[i]);
  3074. g.Windows.clear();
  3075. g.WindowsFocusOrder.clear();
  3076. g.WindowsSortBuffer.clear();
  3077. g.CurrentWindow = NULL;
  3078. g.CurrentWindowStack.clear();
  3079. g.WindowsById.Clear();
  3080. g.NavWindow = NULL;
  3081. g.HoveredWindow = NULL;
  3082. g.HoveredRootWindow = NULL;
  3083. g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
  3084. g.MovingWindow = NULL;
  3085. g.ColorModifiers.clear();
  3086. g.StyleModifiers.clear();
  3087. g.FontStack.clear();
  3088. g.OpenPopupStack.clear();
  3089. g.BeginPopupStack.clear();
  3090. g.DrawDataBuilder.ClearFreeMemory();
  3091. g.OverlayDrawList.ClearFreeMemory();
  3092. g.PrivateClipboard.clear();
  3093. g.InputTextState.TextW.clear();
  3094. g.InputTextState.InitialText.clear();
  3095. g.InputTextState.TempBuffer.clear();
  3096. for (int i = 0; i < g.SettingsWindows.Size; i++)
  3097. IM_DELETE(g.SettingsWindows[i].Name);
  3098. g.SettingsWindows.clear();
  3099. g.SettingsHandlers.clear();
  3100. if (g.LogFile && g.LogFile != stdout)
  3101. {
  3102. fclose(g.LogFile);
  3103. g.LogFile = NULL;
  3104. }
  3105. g.LogClipboard.clear();
  3106. g.Initialized = false;
  3107. }
  3108. // FIXME: Add a more explicit sort order in the window structure.
  3109. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
  3110. {
  3111. const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
  3112. const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
  3113. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  3114. return d;
  3115. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  3116. return d;
  3117. return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
  3118. }
  3119. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
  3120. {
  3121. out_sorted_windows->push_back(window);
  3122. if (window->Active)
  3123. {
  3124. int count = window->DC.ChildWindows.Size;
  3125. if (count > 1)
  3126. ImQsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  3127. for (int i = 0; i < count; i++)
  3128. {
  3129. ImGuiWindow* child = window->DC.ChildWindows[i];
  3130. if (child->Active)
  3131. AddWindowToSortBuffer(out_sorted_windows, child);
  3132. }
  3133. }
  3134. }
  3135. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
  3136. {
  3137. if (draw_list->CmdBuffer.empty())
  3138. return;
  3139. // Remove trailing command if unused
  3140. ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
  3141. if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
  3142. {
  3143. draw_list->CmdBuffer.pop_back();
  3144. if (draw_list->CmdBuffer.empty())
  3145. return;
  3146. }
  3147. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
  3148. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  3149. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  3150. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  3151. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
  3152. // If this assert triggers because you are drawing lots of stuff manually:
  3153. // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
  3154. // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
  3155. // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
  3156. // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
  3157. // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
  3158. // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
  3159. if (sizeof(ImDrawIdx) == 2)
  3160. IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
  3161. out_list->push_back(draw_list);
  3162. }
  3163. static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
  3164. {
  3165. ImGuiContext& g = *GImGui;
  3166. g.IO.MetricsRenderWindows++;
  3167. AddDrawListToDrawData(out_render_list, window->DrawList);
  3168. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  3169. {
  3170. ImGuiWindow* child = window->DC.ChildWindows[i];
  3171. if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active
  3172. AddWindowToDrawData(out_render_list, child);
  3173. }
  3174. }
  3175. static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window)
  3176. {
  3177. ImGuiContext& g = *GImGui;
  3178. if (window->Flags & ImGuiWindowFlags_Tooltip)
  3179. AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
  3180. else
  3181. AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
  3182. }
  3183. void ImDrawDataBuilder::FlattenIntoSingleLayer()
  3184. {
  3185. int n = Layers[0].Size;
  3186. int size = n;
  3187. for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
  3188. size += Layers[i].Size;
  3189. Layers[0].resize(size);
  3190. for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
  3191. {
  3192. ImVector<ImDrawList*>& layer = Layers[layer_n];
  3193. if (layer.empty())
  3194. continue;
  3195. memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  3196. n += layer.Size;
  3197. layer.resize(0);
  3198. }
  3199. }
  3200. static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data)
  3201. {
  3202. ImGuiIO& io = ImGui::GetIO();
  3203. draw_data->Valid = true;
  3204. draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
  3205. draw_data->CmdListsCount = draw_lists->Size;
  3206. draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
  3207. draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
  3208. draw_data->DisplaySize = io.DisplaySize;
  3209. for (int n = 0; n < draw_lists->Size; n++)
  3210. {
  3211. draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
  3212. draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
  3213. }
  3214. }
  3215. // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
  3216. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  3217. {
  3218. ImGuiWindow* window = GetCurrentWindow();
  3219. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  3220. window->ClipRect = window->DrawList->_ClipRectStack.back();
  3221. }
  3222. void ImGui::PopClipRect()
  3223. {
  3224. ImGuiWindow* window = GetCurrentWindow();
  3225. window->DrawList->PopClipRect();
  3226. window->ClipRect = window->DrawList->_ClipRectStack.back();
  3227. }
  3228. // 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.
  3229. void ImGui::EndFrame()
  3230. {
  3231. ImGuiContext& g = *GImGui;
  3232. IM_ASSERT(g.Initialized);
  3233. if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
  3234. return;
  3235. IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()?");
  3236. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  3237. if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f)
  3238. {
  3239. g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
  3240. g.PlatformImeLastPos = g.PlatformImePos;
  3241. }
  3242. // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
  3243. // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
  3244. if (g.CurrentWindowStack.Size != 1)
  3245. {
  3246. if (g.CurrentWindowStack.Size > 1)
  3247. {
  3248. IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
  3249. while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING
  3250. End();
  3251. }
  3252. else
  3253. {
  3254. IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
  3255. }
  3256. }
  3257. // Hide implicit/fallback "Debug" window if it hasn't been used
  3258. g.FrameScopePushedImplicitWindow = false;
  3259. if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
  3260. g.CurrentWindow->Active = false;
  3261. End();
  3262. // Show CTRL+TAB list window
  3263. if (g.NavWindowingTarget)
  3264. NavUpdateWindowingList();
  3265. // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
  3266. if (g.DragDropActive)
  3267. {
  3268. bool is_delivered = g.DragDropPayload.Delivery;
  3269. bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
  3270. if (is_delivered || is_elapsed)
  3271. ClearDragDrop();
  3272. }
  3273. // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
  3274. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
  3275. {
  3276. g.DragDropWithinSourceOrTarget = true;
  3277. SetTooltip("...");
  3278. g.DragDropWithinSourceOrTarget = false;
  3279. }
  3280. // End frame
  3281. g.FrameScopeActive = false;
  3282. g.FrameCountEnded = g.FrameCount;
  3283. // Initiate moving window + handle left-click and right-click focus
  3284. UpdateMouseMovingWindowEndFrame();
  3285. // Sort the window list so that all child windows are after their parent
  3286. // We cannot do that on FocusWindow() because childs may not exist yet
  3287. g.WindowsSortBuffer.resize(0);
  3288. g.WindowsSortBuffer.reserve(g.Windows.Size);
  3289. for (int i = 0; i != g.Windows.Size; i++)
  3290. {
  3291. ImGuiWindow* window = g.Windows[i];
  3292. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  3293. continue;
  3294. AddWindowToSortBuffer(&g.WindowsSortBuffer, window);
  3295. }
  3296. IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
  3297. g.Windows.swap(g.WindowsSortBuffer);
  3298. g.IO.MetricsActiveWindows = g.WindowsActiveCount;
  3299. // Unlock font atlas
  3300. g.IO.Fonts->Locked = false;
  3301. // Clear Input data for next frame
  3302. g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
  3303. g.IO.InputQueueCharacters.resize(0);
  3304. memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
  3305. }
  3306. void ImGui::Render()
  3307. {
  3308. ImGuiContext& g = *GImGui;
  3309. IM_ASSERT(g.Initialized);
  3310. if (g.FrameCountEnded != g.FrameCount)
  3311. EndFrame();
  3312. g.FrameCountRendered = g.FrameCount;
  3313. // Gather ImDrawList to render (for each active window)
  3314. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0;
  3315. g.DrawDataBuilder.Clear();
  3316. ImGuiWindow* windows_to_render_front_most[2];
  3317. windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
  3318. windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL;
  3319. for (int n = 0; n != g.Windows.Size; n++)
  3320. {
  3321. ImGuiWindow* window = g.Windows[n];
  3322. if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1])
  3323. AddWindowToDrawDataSelectLayer(window);
  3324. }
  3325. for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++)
  3326. if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window
  3327. AddWindowToDrawDataSelectLayer(windows_to_render_front_most[n]);
  3328. g.DrawDataBuilder.FlattenIntoSingleLayer();
  3329. // Draw software mouse cursor if requested
  3330. if (g.IO.MouseDrawCursor)
  3331. RenderMouseCursor(&g.OverlayDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor);
  3332. if (!g.OverlayDrawList.VtxBuffer.empty())
  3333. AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList);
  3334. // Setup ImDrawData structure for end-user
  3335. SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
  3336. g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
  3337. g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
  3338. // (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
  3339. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  3340. if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
  3341. g.IO.RenderDrawListsFn(&g.DrawData);
  3342. #endif
  3343. }
  3344. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  3345. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
  3346. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  3347. {
  3348. ImGuiContext& g = *GImGui;
  3349. const char* text_display_end;
  3350. if (hide_text_after_double_hash)
  3351. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  3352. else
  3353. text_display_end = text_end;
  3354. ImFont* font = g.Font;
  3355. const float font_size = g.FontSize;
  3356. if (text == text_display_end)
  3357. return ImVec2(0.0f, font_size);
  3358. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  3359. // Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field)
  3360. const float font_scale = font_size / font->FontSize;
  3361. const float character_spacing_x = 1.0f * font_scale;
  3362. if (text_size.x > 0.0f)
  3363. text_size.x -= character_spacing_x;
  3364. text_size.x = (float)(int)(text_size.x + 0.95f);
  3365. return text_size;
  3366. }
  3367. // Helper to calculate coarse clipping of large list of evenly sized items.
  3368. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
  3369. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  3370. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  3371. {
  3372. ImGuiContext& g = *GImGui;
  3373. ImGuiWindow* window = g.CurrentWindow;
  3374. if (g.LogEnabled)
  3375. {
  3376. // If logging is active, do not perform any clipping
  3377. *out_items_display_start = 0;
  3378. *out_items_display_end = items_count;
  3379. return;
  3380. }
  3381. if (window->SkipItems)
  3382. {
  3383. *out_items_display_start = *out_items_display_end = 0;
  3384. return;
  3385. }
  3386. // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
  3387. ImRect unclipped_rect = window->ClipRect;
  3388. if (g.NavMoveRequest)
  3389. unclipped_rect.Add(g.NavScoringRectScreen);
  3390. const ImVec2 pos = window->DC.CursorPos;
  3391. int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
  3392. int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
  3393. // When performing a navigation request, ensure we have one item extra in the direction we are moving to
  3394. if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
  3395. start--;
  3396. if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
  3397. end++;
  3398. start = ImClamp(start, 0, items_count);
  3399. end = ImClamp(end + 1, start, items_count);
  3400. *out_items_display_start = start;
  3401. *out_items_display_end = end;
  3402. }
  3403. // Find window given position, search front-to-back
  3404. // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
  3405. // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
  3406. // called, aka before the next Begin(). Moving window isn't affected.
  3407. static void FindHoveredWindow()
  3408. {
  3409. ImGuiContext& g = *GImGui;
  3410. ImGuiWindow* hovered_window = NULL;
  3411. if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
  3412. hovered_window = g.MovingWindow;
  3413. ImVec2 padding_regular = g.Style.TouchExtraPadding;
  3414. ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
  3415. for (int i = g.Windows.Size - 1; i >= 0; i--)
  3416. {
  3417. ImGuiWindow* window = g.Windows[i];
  3418. if (!window->Active || window->Hidden)
  3419. continue;
  3420. if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
  3421. continue;
  3422. // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
  3423. ImRect bb(window->OuterRectClipped);
  3424. if ((window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_NoResize))
  3425. bb.Expand(padding_regular);
  3426. else
  3427. bb.Expand(padding_for_resize_from_edges);
  3428. if (!bb.Contains(g.IO.MousePos))
  3429. continue;
  3430. // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches.
  3431. if (hovered_window == NULL)
  3432. hovered_window = window;
  3433. if (hovered_window)
  3434. break;
  3435. }
  3436. g.HoveredWindow = hovered_window;
  3437. g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
  3438. }
  3439. // Test if mouse cursor is hovering given rectangle
  3440. // NB- Rectangle is clipped by our current clip setting
  3441. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  3442. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  3443. {
  3444. ImGuiContext& g = *GImGui;
  3445. // Clip
  3446. ImRect rect_clipped(r_min, r_max);
  3447. if (clip)
  3448. rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
  3449. // Expand for touch input
  3450. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  3451. if (!rect_for_touch.Contains(g.IO.MousePos))
  3452. return false;
  3453. return true;
  3454. }
  3455. int ImGui::GetKeyIndex(ImGuiKey imgui_key)
  3456. {
  3457. IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
  3458. return GImGui->IO.KeyMap[imgui_key];
  3459. }
  3460. // Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
  3461. bool ImGui::IsKeyDown(int user_key_index)
  3462. {
  3463. if (user_key_index < 0) return false;
  3464. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
  3465. return GImGui->IO.KeysDown[user_key_index];
  3466. }
  3467. int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
  3468. {
  3469. if (t == 0.0f)
  3470. return 1;
  3471. if (t <= repeat_delay || repeat_rate <= 0.0f)
  3472. return 0;
  3473. const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
  3474. return (count > 0) ? count : 0;
  3475. }
  3476. int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
  3477. {
  3478. ImGuiContext& g = *GImGui;
  3479. if (key_index < 0) return false;
  3480. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3481. const float t = g.IO.KeysDownDuration[key_index];
  3482. return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
  3483. }
  3484. bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
  3485. {
  3486. ImGuiContext& g = *GImGui;
  3487. if (user_key_index < 0) return false;
  3488. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3489. const float t = g.IO.KeysDownDuration[user_key_index];
  3490. if (t == 0.0f)
  3491. return true;
  3492. if (repeat && t > g.IO.KeyRepeatDelay)
  3493. return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  3494. return false;
  3495. }
  3496. bool ImGui::IsKeyReleased(int user_key_index)
  3497. {
  3498. ImGuiContext& g = *GImGui;
  3499. if (user_key_index < 0) return false;
  3500. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3501. return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
  3502. }
  3503. bool ImGui::IsMouseDown(int button)
  3504. {
  3505. ImGuiContext& g = *GImGui;
  3506. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3507. return g.IO.MouseDown[button];
  3508. }
  3509. bool ImGui::IsAnyMouseDown()
  3510. {
  3511. ImGuiContext& g = *GImGui;
  3512. for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
  3513. if (g.IO.MouseDown[n])
  3514. return true;
  3515. return false;
  3516. }
  3517. bool ImGui::IsMouseClicked(int button, bool repeat)
  3518. {
  3519. ImGuiContext& g = *GImGui;
  3520. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3521. const float t = g.IO.MouseDownDuration[button];
  3522. if (t == 0.0f)
  3523. return true;
  3524. if (repeat && t > g.IO.KeyRepeatDelay)
  3525. {
  3526. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  3527. if ((ImFmod(t - delay, rate) > rate*0.5f) != (ImFmod(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  3528. return true;
  3529. }
  3530. return false;
  3531. }
  3532. bool ImGui::IsMouseReleased(int button)
  3533. {
  3534. ImGuiContext& g = *GImGui;
  3535. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3536. return g.IO.MouseReleased[button];
  3537. }
  3538. bool ImGui::IsMouseDoubleClicked(int button)
  3539. {
  3540. ImGuiContext& g = *GImGui;
  3541. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3542. return g.IO.MouseDoubleClicked[button];
  3543. }
  3544. bool ImGui::IsMouseDragging(int button, float lock_threshold)
  3545. {
  3546. ImGuiContext& g = *GImGui;
  3547. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3548. if (!g.IO.MouseDown[button])
  3549. return false;
  3550. if (lock_threshold < 0.0f)
  3551. lock_threshold = g.IO.MouseDragThreshold;
  3552. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  3553. }
  3554. ImVec2 ImGui::GetMousePos()
  3555. {
  3556. return GImGui->IO.MousePos;
  3557. }
  3558. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  3559. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  3560. {
  3561. ImGuiContext& g = *GImGui;
  3562. if (g.BeginPopupStack.Size > 0)
  3563. return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
  3564. return g.IO.MousePos;
  3565. }
  3566. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position
  3567. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  3568. {
  3569. if (mouse_pos == NULL)
  3570. mouse_pos = &GImGui->IO.MousePos;
  3571. const float MOUSE_INVALID = -256000.0f;
  3572. return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
  3573. }
  3574. // Return the delta from the initial clicking position.
  3575. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
  3576. // NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
  3577. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
  3578. {
  3579. ImGuiContext& g = *GImGui;
  3580. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3581. if (lock_threshold < 0.0f)
  3582. lock_threshold = g.IO.MouseDragThreshold;
  3583. if (g.IO.MouseDown[button])
  3584. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  3585. return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
  3586. return ImVec2(0.0f, 0.0f);
  3587. }
  3588. void ImGui::ResetMouseDragDelta(int button)
  3589. {
  3590. ImGuiContext& g = *GImGui;
  3591. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3592. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  3593. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  3594. }
  3595. ImGuiMouseCursor ImGui::GetMouseCursor()
  3596. {
  3597. return GImGui->MouseCursor;
  3598. }
  3599. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  3600. {
  3601. GImGui->MouseCursor = cursor_type;
  3602. }
  3603. void ImGui::CaptureKeyboardFromApp(bool capture)
  3604. {
  3605. GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
  3606. }
  3607. void ImGui::CaptureMouseFromApp(bool capture)
  3608. {
  3609. GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
  3610. }
  3611. bool ImGui::IsItemActive()
  3612. {
  3613. ImGuiContext& g = *GImGui;
  3614. if (g.ActiveId)
  3615. {
  3616. ImGuiWindow* window = g.CurrentWindow;
  3617. return g.ActiveId == window->DC.LastItemId;
  3618. }
  3619. return false;
  3620. }
  3621. bool ImGui::IsItemDeactivated()
  3622. {
  3623. ImGuiContext& g = *GImGui;
  3624. ImGuiWindow* window = g.CurrentWindow;
  3625. return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
  3626. }
  3627. bool ImGui::IsItemDeactivatedAfterEdit()
  3628. {
  3629. ImGuiContext& g = *GImGui;
  3630. return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEdited || (g.ActiveId == 0 && g.ActiveIdHasBeenEdited));
  3631. }
  3632. bool ImGui::IsItemFocused()
  3633. {
  3634. ImGuiContext& g = *GImGui;
  3635. ImGuiWindow* window = g.CurrentWindow;
  3636. return g.NavId && !g.NavDisableHighlight && g.NavId == window->DC.LastItemId;
  3637. }
  3638. bool ImGui::IsItemClicked(int mouse_button)
  3639. {
  3640. return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
  3641. }
  3642. bool ImGui::IsAnyItemHovered()
  3643. {
  3644. ImGuiContext& g = *GImGui;
  3645. return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
  3646. }
  3647. bool ImGui::IsAnyItemActive()
  3648. {
  3649. ImGuiContext& g = *GImGui;
  3650. return g.ActiveId != 0;
  3651. }
  3652. bool ImGui::IsAnyItemFocused()
  3653. {
  3654. ImGuiContext& g = *GImGui;
  3655. return g.NavId != 0 && !g.NavDisableHighlight;
  3656. }
  3657. bool ImGui::IsItemVisible()
  3658. {
  3659. ImGuiWindow* window = GetCurrentWindowRead();
  3660. return window->ClipRect.Overlaps(window->DC.LastItemRect);
  3661. }
  3662. bool ImGui::IsItemEdited()
  3663. {
  3664. ImGuiWindow* window = GetCurrentWindowRead();
  3665. return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
  3666. }
  3667. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  3668. void ImGui::SetItemAllowOverlap()
  3669. {
  3670. ImGuiContext& g = *GImGui;
  3671. if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
  3672. g.HoveredIdAllowOverlap = true;
  3673. if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
  3674. g.ActiveIdAllowOverlap = true;
  3675. }
  3676. ImVec2 ImGui::GetItemRectMin()
  3677. {
  3678. ImGuiWindow* window = GetCurrentWindowRead();
  3679. return window->DC.LastItemRect.Min;
  3680. }
  3681. ImVec2 ImGui::GetItemRectMax()
  3682. {
  3683. ImGuiWindow* window = GetCurrentWindowRead();
  3684. return window->DC.LastItemRect.Max;
  3685. }
  3686. ImVec2 ImGui::GetItemRectSize()
  3687. {
  3688. ImGuiWindow* window = GetCurrentWindowRead();
  3689. return window->DC.LastItemRect.GetSize();
  3690. }
  3691. static ImRect GetViewportRect()
  3692. {
  3693. ImGuiContext& g = *GImGui;
  3694. if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
  3695. return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
  3696. return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
  3697. }
  3698. static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
  3699. {
  3700. ImGuiContext& g = *GImGui;
  3701. ImGuiWindow* parent_window = g.CurrentWindow;
  3702. flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
  3703. flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
  3704. // Size
  3705. const ImVec2 content_avail = GetContentRegionAvail();
  3706. ImVec2 size = ImFloor(size_arg);
  3707. const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
  3708. if (size.x <= 0.0f)
  3709. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  3710. if (size.y <= 0.0f)
  3711. size.y = ImMax(content_avail.y + size.y, 4.0f);
  3712. SetNextWindowSize(size);
  3713. // 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.
  3714. char title[256];
  3715. if (name)
  3716. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
  3717. else
  3718. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
  3719. const float backup_border_size = g.Style.ChildBorderSize;
  3720. if (!border)
  3721. g.Style.ChildBorderSize = 0.0f;
  3722. bool ret = Begin(title, NULL, flags);
  3723. g.Style.ChildBorderSize = backup_border_size;
  3724. ImGuiWindow* child_window = g.CurrentWindow;
  3725. child_window->ChildId = id;
  3726. child_window->AutoFitChildAxises = auto_fit_axises;
  3727. // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
  3728. // While this is not really documented/defined, it seems that the expected thing to do.
  3729. parent_window->DC.CursorPos = child_window->Pos;
  3730. // Process navigation-in immediately so NavInit can run on first frame
  3731. if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
  3732. {
  3733. FocusWindow(child_window);
  3734. NavInitWindow(child_window, false);
  3735. SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
  3736. g.ActiveIdSource = ImGuiInputSource_Nav;
  3737. }
  3738. return ret;
  3739. }
  3740. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3741. {
  3742. ImGuiWindow* window = GetCurrentWindow();
  3743. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  3744. }
  3745. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3746. {
  3747. IM_ASSERT(id != 0);
  3748. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  3749. }
  3750. void ImGui::EndChild()
  3751. {
  3752. ImGuiContext& g = *GImGui;
  3753. ImGuiWindow* window = g.CurrentWindow;
  3754. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
  3755. if (window->BeginCount > 1)
  3756. {
  3757. End();
  3758. }
  3759. else
  3760. {
  3761. ImVec2 sz = window->Size;
  3762. if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  3763. sz.x = ImMax(4.0f, sz.x);
  3764. if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
  3765. sz.y = ImMax(4.0f, sz.y);
  3766. End();
  3767. ImGuiWindow* parent_window = g.CurrentWindow;
  3768. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  3769. ItemSize(sz);
  3770. if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
  3771. {
  3772. ItemAdd(bb, window->ChildId);
  3773. RenderNavHighlight(bb, window->ChildId);
  3774. // When browsing a window that has no activable items (scroll only) we keep a highlight on the child
  3775. if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
  3776. RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
  3777. }
  3778. else
  3779. {
  3780. // Not navigable into
  3781. ItemAdd(bb, 0);
  3782. }
  3783. }
  3784. }
  3785. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  3786. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  3787. {
  3788. ImGuiContext& g = *GImGui;
  3789. const ImGuiStyle& style = g.Style;
  3790. PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
  3791. PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
  3792. PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
  3793. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  3794. bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  3795. PopStyleVar(3);
  3796. PopStyleColor();
  3797. return ret;
  3798. }
  3799. void ImGui::EndChildFrame()
  3800. {
  3801. EndChild();
  3802. }
  3803. // Save and compare stack sizes on Begin()/End() to detect usage errors
  3804. static void CheckStacksSize(ImGuiWindow* window, bool write)
  3805. {
  3806. // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
  3807. ImGuiContext& g = *GImGui;
  3808. short* p_backup = &window->DC.StackSizesBackup[0];
  3809. { int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
  3810. { int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
  3811. { int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
  3812. // 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.
  3813. { int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
  3814. { int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
  3815. { int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
  3816. IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
  3817. }
  3818. static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
  3819. {
  3820. window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
  3821. window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
  3822. window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
  3823. }
  3824. ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
  3825. {
  3826. ImGuiContext& g = *GImGui;
  3827. return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
  3828. }
  3829. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  3830. {
  3831. ImGuiID id = ImHash(name, 0);
  3832. return FindWindowByID(id);
  3833. }
  3834. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
  3835. {
  3836. ImGuiContext& g = *GImGui;
  3837. // Create window the first time
  3838. ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
  3839. window->Flags = flags;
  3840. g.WindowsById.SetVoidPtr(window->ID, window);
  3841. // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  3842. window->Pos = ImVec2(60, 60);
  3843. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  3844. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  3845. if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
  3846. {
  3847. // Retrieve settings from .ini file
  3848. window->SettingsIdx = g.SettingsWindows.index_from_pointer(settings);
  3849. SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
  3850. window->Pos = ImFloor(settings->Pos);
  3851. window->Collapsed = settings->Collapsed;
  3852. if (ImLengthSqr(settings->Size) > 0.00001f)
  3853. size = ImFloor(settings->Size);
  3854. }
  3855. window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size);
  3856. window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values
  3857. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  3858. {
  3859. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  3860. window->AutoFitOnlyGrows = false;
  3861. }
  3862. else
  3863. {
  3864. if (window->Size.x <= 0.0f)
  3865. window->AutoFitFramesX = 2;
  3866. if (window->Size.y <= 0.0f)
  3867. window->AutoFitFramesY = 2;
  3868. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  3869. }
  3870. g.WindowsFocusOrder.push_back(window);
  3871. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  3872. g.Windows.push_front(window); // Quite slow but rare and only once
  3873. else
  3874. g.Windows.push_back(window);
  3875. return window;
  3876. }
  3877. static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
  3878. {
  3879. ImGuiContext& g = *GImGui;
  3880. if (g.NextWindowData.SizeConstraintCond != 0)
  3881. {
  3882. // Using -1,-1 on either X/Y axis to preserve the current size.
  3883. ImRect cr = g.NextWindowData.SizeConstraintRect;
  3884. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  3885. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  3886. if (g.NextWindowData.SizeCallback)
  3887. {
  3888. ImGuiSizeCallbackData data;
  3889. data.UserData = g.NextWindowData.SizeCallbackUserData;
  3890. data.Pos = window->Pos;
  3891. data.CurrentSize = window->SizeFull;
  3892. data.DesiredSize = new_size;
  3893. g.NextWindowData.SizeCallback(&data);
  3894. new_size = data.DesiredSize;
  3895. }
  3896. }
  3897. // Minimum size
  3898. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  3899. {
  3900. new_size = ImMax(new_size, g.Style.WindowMinSize);
  3901. new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
  3902. }
  3903. return new_size;
  3904. }
  3905. static ImVec2 CalcSizeContents(ImGuiWindow* window)
  3906. {
  3907. if (window->Collapsed)
  3908. return window->SizeContents;
  3909. if (window->Hidden && window->HiddenFramesForResize == 0 && window->HiddenFramesRegular > 0)
  3910. return window->SizeContents;
  3911. ImVec2 sz;
  3912. sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
  3913. sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
  3914. return sz + window->WindowPadding;
  3915. }
  3916. static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
  3917. {
  3918. ImGuiContext& g = *GImGui;
  3919. ImGuiStyle& style = g.Style;
  3920. if (window->Flags & ImGuiWindowFlags_Tooltip)
  3921. {
  3922. // Tooltip always resize
  3923. return size_contents;
  3924. }
  3925. else
  3926. {
  3927. // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
  3928. const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
  3929. const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
  3930. ImVec2 size_min = style.WindowMinSize;
  3931. 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)
  3932. size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
  3933. ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
  3934. ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
  3935. if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar))
  3936. size_auto_fit.y += style.ScrollbarSize;
  3937. if (size_auto_fit_after_constraint.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar))
  3938. size_auto_fit.x += style.ScrollbarSize;
  3939. return size_auto_fit;
  3940. }
  3941. }
  3942. ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
  3943. {
  3944. ImVec2 size_contents = CalcSizeContents(window);
  3945. return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents));
  3946. }
  3947. float ImGui::GetWindowScrollMaxX(ImGuiWindow* window)
  3948. {
  3949. return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
  3950. }
  3951. float ImGui::GetWindowScrollMaxY(ImGuiWindow* window)
  3952. {
  3953. return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
  3954. }
  3955. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
  3956. {
  3957. ImGuiContext& g = *GImGui;
  3958. ImVec2 scroll = window->Scroll;
  3959. if (window->ScrollTarget.x < FLT_MAX)
  3960. {
  3961. float cr_x = window->ScrollTargetCenterRatio.x;
  3962. scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
  3963. }
  3964. if (window->ScrollTarget.y < FLT_MAX)
  3965. {
  3966. // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
  3967. float cr_y = window->ScrollTargetCenterRatio.y;
  3968. float target_y = window->ScrollTarget.y;
  3969. if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
  3970. target_y = 0.0f;
  3971. if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y - window->WindowPadding.y + g.Style.ItemSpacing.y)
  3972. target_y = window->SizeContents.y;
  3973. scroll.y = target_y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
  3974. }
  3975. scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
  3976. if (!window->Collapsed && !window->SkipItems)
  3977. {
  3978. scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window));
  3979. scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window));
  3980. }
  3981. return scroll;
  3982. }
  3983. static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
  3984. {
  3985. if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  3986. return ImGuiCol_PopupBg;
  3987. if (flags & ImGuiWindowFlags_ChildWindow)
  3988. return ImGuiCol_ChildBg;
  3989. return ImGuiCol_WindowBg;
  3990. }
  3991. static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
  3992. {
  3993. ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
  3994. ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
  3995. ImVec2 size_expected = pos_max - pos_min;
  3996. ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
  3997. *out_pos = pos_min;
  3998. if (corner_norm.x == 0.0f)
  3999. out_pos->x -= (size_constrained.x - size_expected.x);
  4000. if (corner_norm.y == 0.0f)
  4001. out_pos->y -= (size_constrained.y - size_expected.y);
  4002. *out_size = size_constrained;
  4003. }
  4004. struct ImGuiResizeGripDef
  4005. {
  4006. ImVec2 CornerPos;
  4007. ImVec2 InnerDir;
  4008. int AngleMin12, AngleMax12;
  4009. };
  4010. const ImGuiResizeGripDef resize_grip_def[4] =
  4011. {
  4012. { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
  4013. { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
  4014. { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
  4015. { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
  4016. };
  4017. static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
  4018. {
  4019. ImRect rect = window->Rect();
  4020. if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
  4021. if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness);
  4022. if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding);
  4023. if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness);
  4024. if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding);
  4025. IM_ASSERT(0);
  4026. return ImRect();
  4027. }
  4028. // Handle resize for: Resize Grips, Borders, Gamepad
  4029. static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
  4030. {
  4031. ImGuiContext& g = *GImGui;
  4032. ImGuiWindowFlags flags = window->Flags;
  4033. if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  4034. return;
  4035. if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
  4036. return;
  4037. const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
  4038. const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
  4039. const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f);
  4040. const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
  4041. ImVec2 pos_target(FLT_MAX, FLT_MAX);
  4042. ImVec2 size_target(FLT_MAX, FLT_MAX);
  4043. // Manual resize grips
  4044. PushID("#RESIZE");
  4045. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  4046. {
  4047. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  4048. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
  4049. // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
  4050. ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
  4051. if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
  4052. if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
  4053. bool hovered, held;
  4054. ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  4055. //GetOverlayDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
  4056. if (hovered || held)
  4057. g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  4058. if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
  4059. {
  4060. // Manual auto-fit when double-clicking
  4061. size_target = CalcSizeAfterConstraint(window, size_auto_fit);
  4062. ClearActiveID();
  4063. }
  4064. else if (held)
  4065. {
  4066. // Resize from any of the four corners
  4067. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  4068. ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPos); // Corner of the window corresponding to our corner grip
  4069. CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target);
  4070. }
  4071. if (resize_grip_n == 0 || held || hovered)
  4072. resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  4073. }
  4074. for (int border_n = 0; border_n < resize_border_count; border_n++)
  4075. {
  4076. bool hovered, held;
  4077. ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
  4078. ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
  4079. //GetOverlayDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
  4080. if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
  4081. {
  4082. g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
  4083. if (held) *border_held = border_n;
  4084. }
  4085. if (held)
  4086. {
  4087. ImVec2 border_target = window->Pos;
  4088. ImVec2 border_posn;
  4089. if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); }
  4090. if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); }
  4091. if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); }
  4092. if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); }
  4093. CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
  4094. }
  4095. }
  4096. PopID();
  4097. // Navigation resize (keyboard/gamepad)
  4098. if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
  4099. {
  4100. ImVec2 nav_resize_delta;
  4101. if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
  4102. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  4103. if (g.NavInputSource == ImGuiInputSource_NavGamepad)
  4104. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
  4105. if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
  4106. {
  4107. const float NAV_RESIZE_SPEED = 600.0f;
  4108. nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
  4109. g.NavWindowingToggleLayer = false;
  4110. g.NavDisableMouseHover = true;
  4111. resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
  4112. // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
  4113. size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
  4114. }
  4115. }
  4116. // Apply back modified position/size to window
  4117. if (size_target.x != FLT_MAX)
  4118. {
  4119. window->SizeFull = size_target;
  4120. MarkIniSettingsDirty(window);
  4121. }
  4122. if (pos_target.x != FLT_MAX)
  4123. {
  4124. window->Pos = ImFloor(pos_target);
  4125. MarkIniSettingsDirty(window);
  4126. }
  4127. window->Size = window->SizeFull;
  4128. }
  4129. void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
  4130. {
  4131. window->ParentWindow = parent_window;
  4132. window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
  4133. if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  4134. window->RootWindow = parent_window->RootWindow;
  4135. if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  4136. window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
  4137. while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
  4138. window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
  4139. }
  4140. // Push a new ImGui window to add widgets to.
  4141. // - 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.
  4142. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  4143. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  4144. // 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.
  4145. // - 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.
  4146. // - 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.
  4147. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  4148. {
  4149. ImGuiContext& g = *GImGui;
  4150. const ImGuiStyle& style = g.Style;
  4151. IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
  4152. IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame()
  4153. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  4154. // Find or create
  4155. ImGuiWindow* window = FindWindowByName(name);
  4156. const bool window_just_created = (window == NULL);
  4157. if (window_just_created)
  4158. {
  4159. ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
  4160. window = CreateNewWindow(name, size_on_first_use, flags);
  4161. }
  4162. // Automatically disable manual moving/resizing when NoInputs is set
  4163. if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
  4164. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  4165. if (flags & ImGuiWindowFlags_NavFlattened)
  4166. IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
  4167. const int current_frame = g.FrameCount;
  4168. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  4169. // Update Flags, LastFrameActive, BeginOrderXXX fields
  4170. if (first_begin_of_the_frame)
  4171. window->Flags = (ImGuiWindowFlags)flags;
  4172. else
  4173. flags = window->Flags;
  4174. // 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
  4175. ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
  4176. ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
  4177. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  4178. window->HasCloseButton = (p_open != NULL);
  4179. // Update the Appearing flag
  4180. bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  4181. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesForResize > 0);
  4182. if (flags & ImGuiWindowFlags_Popup)
  4183. {
  4184. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  4185. window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
  4186. window_just_activated_by_user |= (window != popup_ref.Window);
  4187. }
  4188. window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
  4189. if (window->Appearing)
  4190. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
  4191. // Add to stack
  4192. g.CurrentWindowStack.push_back(window);
  4193. SetCurrentWindow(window);
  4194. CheckStacksSize(window, true);
  4195. if (flags & ImGuiWindowFlags_Popup)
  4196. {
  4197. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  4198. popup_ref.Window = window;
  4199. g.BeginPopupStack.push_back(popup_ref);
  4200. window->PopupId = popup_ref.PopupId;
  4201. }
  4202. if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
  4203. window->NavLastIds[0] = 0;
  4204. // Process SetNextWindow***() calls
  4205. bool window_pos_set_by_api = false;
  4206. bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
  4207. if (g.NextWindowData.PosCond)
  4208. {
  4209. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
  4210. if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
  4211. {
  4212. // May be processed on the next frame if this is our first frame and we are measuring size
  4213. // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
  4214. window->SetWindowPosVal = g.NextWindowData.PosVal;
  4215. window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
  4216. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  4217. }
  4218. else
  4219. {
  4220. SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
  4221. }
  4222. }
  4223. if (g.NextWindowData.SizeCond)
  4224. {
  4225. window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
  4226. window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
  4227. SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
  4228. }
  4229. if (g.NextWindowData.ContentSizeCond)
  4230. {
  4231. // Adjust passed "client size" to become a "window size"
  4232. window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
  4233. if (window->SizeContentsExplicit.y != 0.0f)
  4234. window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
  4235. }
  4236. else if (first_begin_of_the_frame)
  4237. {
  4238. window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  4239. }
  4240. if (g.NextWindowData.CollapsedCond)
  4241. SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
  4242. if (g.NextWindowData.FocusCond)
  4243. FocusWindow(window);
  4244. if (window->Appearing)
  4245. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
  4246. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  4247. if (first_begin_of_the_frame)
  4248. {
  4249. // Initialize
  4250. const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
  4251. UpdateWindowParentAndRootLinks(window, flags, parent_window);
  4252. window->Active = true;
  4253. window->BeginOrderWithinParent = 0;
  4254. window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
  4255. window->BeginCount = 0;
  4256. window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
  4257. window->LastFrameActive = current_frame;
  4258. window->IDStack.resize(1);
  4259. // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
  4260. // 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.
  4261. bool window_title_visible_elsewhere = false;
  4262. if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
  4263. window_title_visible_elsewhere = true;
  4264. if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
  4265. {
  4266. size_t buf_len = (size_t)window->NameBufLen;
  4267. window->Name = ImStrdupcpy(window->Name, &buf_len, name);
  4268. window->NameBufLen = (int)buf_len;
  4269. }
  4270. // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
  4271. // Update contents size from last frame for auto-fitting (or use explicit size)
  4272. window->SizeContents = CalcSizeContents(window);
  4273. if (window->HiddenFramesRegular > 0)
  4274. window->HiddenFramesRegular--;
  4275. if (window->HiddenFramesForResize > 0)
  4276. window->HiddenFramesForResize--;
  4277. // Hide new windows for one frame until they calculate their size
  4278. if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
  4279. window->HiddenFramesForResize = 1;
  4280. // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
  4281. // We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
  4282. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
  4283. {
  4284. window->HiddenFramesForResize = 1;
  4285. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  4286. {
  4287. if (!window_size_x_set_by_api)
  4288. window->Size.x = window->SizeFull.x = 0.f;
  4289. if (!window_size_y_set_by_api)
  4290. window->Size.y = window->SizeFull.y = 0.f;
  4291. window->SizeContents = ImVec2(0.f, 0.f);
  4292. }
  4293. }
  4294. SetCurrentWindow(window);
  4295. // Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies)
  4296. window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
  4297. window->WindowPadding = style.WindowPadding;
  4298. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
  4299. window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
  4300. window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
  4301. window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
  4302. // Collapse window by double-clicking on title bar
  4303. // 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
  4304. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  4305. {
  4306. // 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.
  4307. ImRect title_bar_rect = window->TitleBarRect();
  4308. if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
  4309. window->WantCollapseToggle = true;
  4310. if (window->WantCollapseToggle)
  4311. {
  4312. window->Collapsed = !window->Collapsed;
  4313. MarkIniSettingsDirty(window);
  4314. FocusWindow(window);
  4315. }
  4316. }
  4317. else
  4318. {
  4319. window->Collapsed = false;
  4320. }
  4321. window->WantCollapseToggle = false;
  4322. // SIZE
  4323. // Calculate auto-fit size, handle automatic resize
  4324. const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
  4325. ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
  4326. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
  4327. {
  4328. // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
  4329. if (!window_size_x_set_by_api)
  4330. window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
  4331. if (!window_size_y_set_by_api)
  4332. window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
  4333. }
  4334. else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  4335. {
  4336. // Auto-fit may only grow window during the first few frames
  4337. // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  4338. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
  4339. window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  4340. if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
  4341. window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  4342. if (!window->Collapsed)
  4343. MarkIniSettingsDirty(window);
  4344. }
  4345. // Apply minimum/maximum window size constraints and final size
  4346. window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
  4347. window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
  4348. // SCROLLBAR STATUS
  4349. // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
  4350. if (!window->Collapsed)
  4351. {
  4352. // When reading the current size we need to read it after size constraints have been applied
  4353. float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
  4354. float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
  4355. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
  4356. window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
  4357. if (window->ScrollbarX && !window->ScrollbarY)
  4358. window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
  4359. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  4360. }
  4361. // POSITION
  4362. // Popup latch its initial position, will position itself when it appears next frame
  4363. if (window_just_activated_by_user)
  4364. {
  4365. window->AutoPosLastDirection = ImGuiDir_None;
  4366. if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
  4367. window->Pos = g.BeginPopupStack.back().OpenPopupPos;
  4368. }
  4369. // Position child window
  4370. if (flags & ImGuiWindowFlags_ChildWindow)
  4371. {
  4372. IM_ASSERT(parent_window->Active);
  4373. window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
  4374. parent_window->DC.ChildWindows.push_back(window);
  4375. if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
  4376. window->Pos = parent_window->DC.CursorPos;
  4377. }
  4378. const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesForResize == 0);
  4379. if (window_pos_with_pivot)
  4380. SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering)
  4381. else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
  4382. window->Pos = FindBestWindowPosForPopup(window);
  4383. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
  4384. window->Pos = FindBestWindowPosForPopup(window);
  4385. else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
  4386. window->Pos = FindBestWindowPosForPopup(window);
  4387. // Clamp position so it stays visible
  4388. if (!(flags & ImGuiWindowFlags_ChildWindow))
  4389. {
  4390. if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
  4391. {
  4392. ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  4393. ImVec2 size_for_clamping = ((g.IO.ConfigWindowsMoveFromTitleBarOnly) && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
  4394. window->Pos = ImMax(window->Pos + size_for_clamping, padding) - size_for_clamping;
  4395. window->Pos = ImMin(window->Pos, g.IO.DisplaySize - padding);
  4396. }
  4397. }
  4398. window->Pos = ImFloor(window->Pos);
  4399. // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
  4400. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
  4401. // Prepare for item focus requests
  4402. window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
  4403. window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
  4404. window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
  4405. window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
  4406. // Apply scrolling
  4407. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
  4408. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  4409. // Apply window focus (new and reactivated windows are moved to front)
  4410. bool want_focus = false;
  4411. if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  4412. if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
  4413. want_focus = true;
  4414. // Handle manual resize: Resize Grips, Borders, Gamepad
  4415. int border_held = -1;
  4416. ImU32 resize_grip_col[4] = { 0 };
  4417. const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4
  4418. const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
  4419. if (!window->Collapsed)
  4420. UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
  4421. // Default item width. Make it proportional to window size if window manually resizes
  4422. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  4423. window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
  4424. else
  4425. window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
  4426. // DRAWING
  4427. // Setup draw list and outer clipping rectangle
  4428. window->DrawList->Clear();
  4429. window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
  4430. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  4431. ImRect viewport_rect(GetViewportRect());
  4432. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
  4433. PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
  4434. else
  4435. PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
  4436. // Draw modal window background (darkens what is behind them, all viewports)
  4437. const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesForResize <= 0;
  4438. const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
  4439. if (dim_bg_for_modal || dim_bg_for_window_list)
  4440. {
  4441. const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
  4442. window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
  4443. }
  4444. // Draw navigation selection/windowing rectangle background
  4445. if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
  4446. {
  4447. ImRect bb = window->Rect();
  4448. bb.Expand(g.FontSize);
  4449. if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
  4450. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
  4451. }
  4452. // Draw window + handle manual resize
  4453. const float window_rounding = window->WindowRounding;
  4454. const float window_border_size = window->WindowBorderSize;
  4455. const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
  4456. const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
  4457. const ImRect title_bar_rect = window->TitleBarRect();
  4458. if (window->Collapsed)
  4459. {
  4460. // Title bar only
  4461. float backup_border_size = style.FrameBorderSize;
  4462. g.Style.FrameBorderSize = window->WindowBorderSize;
  4463. ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
  4464. RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
  4465. g.Style.FrameBorderSize = backup_border_size;
  4466. }
  4467. else
  4468. {
  4469. // Window background
  4470. if (!(flags & ImGuiWindowFlags_NoBackground))
  4471. {
  4472. ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
  4473. if (g.NextWindowData.BgAlphaCond != 0)
  4474. bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
  4475. window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
  4476. }
  4477. g.NextWindowData.BgAlphaCond = 0;
  4478. // Title bar
  4479. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4480. {
  4481. ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  4482. window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
  4483. }
  4484. // Menu bar
  4485. if (flags & ImGuiWindowFlags_MenuBar)
  4486. {
  4487. ImRect menu_bar_rect = window->MenuBarRect();
  4488. 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.
  4489. window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
  4490. if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
  4491. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  4492. }
  4493. // Scrollbars
  4494. if (window->ScrollbarX)
  4495. Scrollbar(ImGuiLayoutType_Horizontal);
  4496. if (window->ScrollbarY)
  4497. Scrollbar(ImGuiLayoutType_Vertical);
  4498. // Render resize grips (after their input handling so we don't have a frame of latency)
  4499. if (!(flags & ImGuiWindowFlags_NoResize))
  4500. {
  4501. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  4502. {
  4503. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  4504. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
  4505. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size)));
  4506. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size)));
  4507. 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);
  4508. window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
  4509. }
  4510. }
  4511. // Borders
  4512. if (window_border_size > 0.0f && !(flags & ImGuiWindowFlags_NoBackground))
  4513. window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size);
  4514. if (border_held != -1)
  4515. {
  4516. ImRect border = GetResizeBorderRect(window, border_held, grip_draw_size, 0.0f);
  4517. window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size));
  4518. }
  4519. if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar))
  4520. window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize, -1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  4521. }
  4522. // Draw navigation selection/windowing rectangle border
  4523. if (g.NavWindowingTargetAnim == window)
  4524. {
  4525. float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
  4526. ImRect bb = window->Rect();
  4527. bb.Expand(g.FontSize);
  4528. if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
  4529. {
  4530. bb.Expand(-g.FontSize - 1.0f);
  4531. rounding = window->WindowRounding;
  4532. }
  4533. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
  4534. }
  4535. // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
  4536. window->SizeFullAtLastBegin = window->SizeFull;
  4537. // Update various regions. Variables they depends on are set above in this function.
  4538. // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
  4539. window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
  4540. window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
  4541. window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
  4542. window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
  4543. // Setup drawing context
  4544. // (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.)
  4545. window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
  4546. window->DC.GroupOffset.x = 0.0f;
  4547. window->DC.ColumnsOffset.x = 0.0f;
  4548. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
  4549. window->DC.CursorPos = window->DC.CursorStartPos;
  4550. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  4551. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  4552. window->DC.CurrentLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
  4553. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  4554. window->DC.NavHideHighlightOneFrame = false;
  4555. window->DC.NavHasScroll = (GetWindowScrollMaxY(window) > 0.0f);
  4556. window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
  4557. window->DC.NavLayerActiveMaskNext = 0x00;
  4558. window->DC.MenuBarAppending = false;
  4559. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  4560. window->DC.ChildWindows.resize(0);
  4561. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  4562. window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
  4563. window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
  4564. window->DC.ItemWidth = window->ItemWidthDefault;
  4565. window->DC.TextWrapPos = -1.0f; // disabled
  4566. window->DC.ItemFlagsStack.resize(0);
  4567. window->DC.ItemWidthStack.resize(0);
  4568. window->DC.TextWrapPosStack.resize(0);
  4569. window->DC.ColumnsSet = NULL;
  4570. window->DC.TreeDepth = 0;
  4571. window->DC.TreeDepthMayJumpToParentOnPop = 0x00;
  4572. window->DC.StateStorage = &window->StateStorage;
  4573. window->DC.GroupStack.resize(0);
  4574. window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
  4575. if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
  4576. {
  4577. window->DC.ItemFlags = parent_window->DC.ItemFlags;
  4578. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  4579. }
  4580. if (window->AutoFitFramesX > 0)
  4581. window->AutoFitFramesX--;
  4582. if (window->AutoFitFramesY > 0)
  4583. window->AutoFitFramesY--;
  4584. // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  4585. if (want_focus)
  4586. {
  4587. FocusWindow(window);
  4588. NavInitWindow(window, false);
  4589. }
  4590. // Title bar
  4591. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4592. {
  4593. // Close & collapse button are on layer 1 (same as menus) and don't default focus
  4594. const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
  4595. window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
  4596. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  4597. window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
  4598. // Collapse button
  4599. if (!(flags & ImGuiWindowFlags_NoCollapse))
  4600. if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos))
  4601. window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function
  4602. // Close button
  4603. if (p_open != NULL)
  4604. {
  4605. const float pad = style.FramePadding.y;
  4606. const float rad = g.FontSize * 0.5f;
  4607. if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad + 1))
  4608. *p_open = false;
  4609. }
  4610. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  4611. window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
  4612. window->DC.ItemFlags = item_flags_backup;
  4613. // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
  4614. // FIXME: Refactor text alignment facilities along with RenderText helpers, this is too much code..
  4615. const char* UNSAVED_DOCUMENT_MARKER = "*";
  4616. float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
  4617. ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
  4618. ImRect text_r = title_bar_rect;
  4619. float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
  4620. float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
  4621. if (style.WindowTitleAlign.x > 0.0f)
  4622. pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
  4623. text_r.Min.x += pad_left;
  4624. text_r.Max.x -= pad_right;
  4625. ImRect clip_rect = text_r;
  4626. clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
  4627. RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
  4628. if (flags & ImGuiWindowFlags_UnsavedDocument)
  4629. {
  4630. ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
  4631. ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f));
  4632. RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect);
  4633. }
  4634. }
  4635. // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
  4636. window->OuterRectClipped = window->Rect();
  4637. window->OuterRectClipped.ClipWith(window->ClipRect);
  4638. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  4639. // 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.
  4640. // Maybe we can support CTRL+C on every element?
  4641. /*
  4642. if (g.ActiveId == move_id)
  4643. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  4644. LogToClipboard();
  4645. */
  4646. // Inner rectangle
  4647. // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
  4648. // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
  4649. window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
  4650. window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
  4651. window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize;
  4652. window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
  4653. //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
  4654. // Inner clipping rectangle
  4655. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  4656. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
  4657. window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y);
  4658. window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
  4659. window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y);
  4660. // After Begin() we fill the last item / hovered data based on title bar data. It is a standard behavior (to allow creation of context menus on title bar only, etc.).
  4661. window->DC.LastItemId = window->MoveId;
  4662. window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
  4663. window->DC.LastItemRect = title_bar_rect;
  4664. }
  4665. PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
  4666. // 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)
  4667. if (first_begin_of_the_frame)
  4668. window->WriteAccessed = false;
  4669. window->BeginCount++;
  4670. g.NextWindowData.Clear();
  4671. if (flags & ImGuiWindowFlags_ChildWindow)
  4672. {
  4673. // Child window can be out of sight and have "negative" clip windows.
  4674. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
  4675. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  4676. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  4677. if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
  4678. window->HiddenFramesRegular = 1;
  4679. // Completely hide along with parent or if parent is collapsed
  4680. if (parent_window && (parent_window->Collapsed || parent_window->Hidden))
  4681. window->HiddenFramesRegular = 1;
  4682. }
  4683. // 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)
  4684. if (style.Alpha <= 0.0f)
  4685. window->HiddenFramesRegular = 1;
  4686. // Update the Hidden flag
  4687. window->Hidden = (window->HiddenFramesRegular > 0) || (window->HiddenFramesForResize > 0);
  4688. // Return false if we don't intend to display anything to allow user to perform an early out optimization
  4689. window->SkipItems = (window->Collapsed || !window->Active || window->Hidden) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesForResize <= 0;
  4690. return !window->SkipItems;
  4691. }
  4692. // Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
  4693. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  4694. bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
  4695. {
  4696. // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
  4697. if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
  4698. SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
  4699. // Old API feature: override the window background alpha with a parameter.
  4700. if (bg_alpha_override >= 0.0f)
  4701. SetNextWindowBgAlpha(bg_alpha_override);
  4702. return Begin(name, p_open, flags);
  4703. }
  4704. #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  4705. void ImGui::End()
  4706. {
  4707. ImGuiContext& g = *GImGui;
  4708. if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow)
  4709. {
  4710. IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!");
  4711. return; // FIXME-ERRORHANDLING
  4712. }
  4713. IM_ASSERT(g.CurrentWindowStack.Size > 0);
  4714. ImGuiWindow* window = g.CurrentWindow;
  4715. if (window->DC.ColumnsSet != NULL)
  4716. EndColumns();
  4717. PopClipRect(); // Inner window clip rectangle
  4718. // Stop logging
  4719. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  4720. LogFinish();
  4721. // Pop from window stack
  4722. g.CurrentWindowStack.pop_back();
  4723. if (window->Flags & ImGuiWindowFlags_Popup)
  4724. g.BeginPopupStack.pop_back();
  4725. CheckStacksSize(window, false);
  4726. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  4727. }
  4728. void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
  4729. {
  4730. ImGuiContext& g = *GImGui;
  4731. if (g.WindowsFocusOrder.back() == window)
  4732. return;
  4733. for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the front most window
  4734. if (g.WindowsFocusOrder[i] == window)
  4735. {
  4736. memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
  4737. g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
  4738. break;
  4739. }
  4740. }
  4741. void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
  4742. {
  4743. ImGuiContext& g = *GImGui;
  4744. ImGuiWindow* current_front_window = g.Windows.back();
  4745. if (current_front_window == window || current_front_window->RootWindow == window)
  4746. return;
  4747. for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
  4748. if (g.Windows[i] == window)
  4749. {
  4750. memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
  4751. g.Windows[g.Windows.Size - 1] = window;
  4752. break;
  4753. }
  4754. }
  4755. void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
  4756. {
  4757. ImGuiContext& g = *GImGui;
  4758. if (g.Windows[0] == window)
  4759. return;
  4760. for (int i = 0; i < g.Windows.Size; i++)
  4761. if (g.Windows[i] == window)
  4762. {
  4763. memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
  4764. g.Windows[0] = window;
  4765. break;
  4766. }
  4767. }
  4768. // Moving window to front of display and set focus (which happens to be back of our sorted list)
  4769. void ImGui::FocusWindow(ImGuiWindow* window)
  4770. {
  4771. ImGuiContext& g = *GImGui;
  4772. if (g.NavWindow != window)
  4773. {
  4774. g.NavWindow = window;
  4775. if (window && g.NavDisableMouseHover)
  4776. g.NavMousePosDirty = true;
  4777. g.NavInitRequest = false;
  4778. g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
  4779. g.NavIdIsAlive = false;
  4780. g.NavLayer = ImGuiNavLayer_Main;
  4781. //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", g.FrameCount, window ? window->Name : NULL);
  4782. }
  4783. // Passing NULL allow to disable keyboard focus
  4784. if (!window)
  4785. return;
  4786. // Move the root window to the top of the pile
  4787. if (window->RootWindow)
  4788. window = window->RootWindow;
  4789. // Steal focus on active widgets
  4790. if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
  4791. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
  4792. ClearActiveID();
  4793. // Bring to front
  4794. BringWindowToFocusFront(window);
  4795. if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
  4796. BringWindowToDisplayFront(window);
  4797. }
  4798. void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window)
  4799. {
  4800. ImGuiContext& g = *GImGui;
  4801. for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--)
  4802. {
  4803. // 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.
  4804. ImGuiWindow* window = g.WindowsFocusOrder[i];
  4805. if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
  4806. if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
  4807. {
  4808. ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
  4809. FocusWindow(focus_window);
  4810. return;
  4811. }
  4812. }
  4813. }
  4814. void ImGui::PushItemWidth(float item_width)
  4815. {
  4816. ImGuiWindow* window = GetCurrentWindow();
  4817. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  4818. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
  4819. }
  4820. void ImGui::PushMultiItemsWidths(int components, float w_full)
  4821. {
  4822. ImGuiWindow* window = GetCurrentWindow();
  4823. const ImGuiStyle& style = GImGui->Style;
  4824. if (w_full <= 0.0f)
  4825. w_full = CalcItemWidth();
  4826. const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  4827. const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  4828. window->DC.ItemWidthStack.push_back(w_item_last);
  4829. for (int i = 0; i < components-1; i++)
  4830. window->DC.ItemWidthStack.push_back(w_item_one);
  4831. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  4832. }
  4833. void ImGui::PopItemWidth()
  4834. {
  4835. ImGuiWindow* window = GetCurrentWindow();
  4836. window->DC.ItemWidthStack.pop_back();
  4837. window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
  4838. }
  4839. float ImGui::CalcItemWidth()
  4840. {
  4841. ImGuiWindow* window = GetCurrentWindowRead();
  4842. float w = window->DC.ItemWidth;
  4843. if (w < 0.0f)
  4844. {
  4845. // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well.
  4846. float width_to_right_edge = GetContentRegionAvail().x;
  4847. w = ImMax(1.0f, width_to_right_edge + w);
  4848. }
  4849. w = (float)(int)w;
  4850. return w;
  4851. }
  4852. void ImGui::SetCurrentFont(ImFont* font)
  4853. {
  4854. ImGuiContext& g = *GImGui;
  4855. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  4856. IM_ASSERT(font->Scale > 0.0f);
  4857. g.Font = font;
  4858. g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
  4859. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  4860. ImFontAtlas* atlas = g.Font->ContainerAtlas;
  4861. g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
  4862. g.DrawListSharedData.Font = g.Font;
  4863. g.DrawListSharedData.FontSize = g.FontSize;
  4864. }
  4865. void ImGui::PushFont(ImFont* font)
  4866. {
  4867. ImGuiContext& g = *GImGui;
  4868. if (!font)
  4869. font = GetDefaultFont();
  4870. SetCurrentFont(font);
  4871. g.FontStack.push_back(font);
  4872. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  4873. }
  4874. void ImGui::PopFont()
  4875. {
  4876. ImGuiContext& g = *GImGui;
  4877. g.CurrentWindow->DrawList->PopTextureID();
  4878. g.FontStack.pop_back();
  4879. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  4880. }
  4881. void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
  4882. {
  4883. ImGuiWindow* window = GetCurrentWindow();
  4884. if (enabled)
  4885. window->DC.ItemFlags |= option;
  4886. else
  4887. window->DC.ItemFlags &= ~option;
  4888. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  4889. }
  4890. void ImGui::PopItemFlag()
  4891. {
  4892. ImGuiWindow* window = GetCurrentWindow();
  4893. window->DC.ItemFlagsStack.pop_back();
  4894. window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
  4895. }
  4896. // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
  4897. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  4898. {
  4899. PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
  4900. }
  4901. void ImGui::PopAllowKeyboardFocus()
  4902. {
  4903. PopItemFlag();
  4904. }
  4905. void ImGui::PushButtonRepeat(bool repeat)
  4906. {
  4907. PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
  4908. }
  4909. void ImGui::PopButtonRepeat()
  4910. {
  4911. PopItemFlag();
  4912. }
  4913. void ImGui::PushTextWrapPos(float wrap_pos_x)
  4914. {
  4915. ImGuiWindow* window = GetCurrentWindow();
  4916. window->DC.TextWrapPos = wrap_pos_x;
  4917. window->DC.TextWrapPosStack.push_back(wrap_pos_x);
  4918. }
  4919. void ImGui::PopTextWrapPos()
  4920. {
  4921. ImGuiWindow* window = GetCurrentWindow();
  4922. window->DC.TextWrapPosStack.pop_back();
  4923. window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
  4924. }
  4925. // 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
  4926. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  4927. {
  4928. ImGuiContext& g = *GImGui;
  4929. ImGuiColorMod backup;
  4930. backup.Col = idx;
  4931. backup.BackupValue = g.Style.Colors[idx];
  4932. g.ColorModifiers.push_back(backup);
  4933. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  4934. }
  4935. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  4936. {
  4937. ImGuiContext& g = *GImGui;
  4938. ImGuiColorMod backup;
  4939. backup.Col = idx;
  4940. backup.BackupValue = g.Style.Colors[idx];
  4941. g.ColorModifiers.push_back(backup);
  4942. g.Style.Colors[idx] = col;
  4943. }
  4944. void ImGui::PopStyleColor(int count)
  4945. {
  4946. ImGuiContext& g = *GImGui;
  4947. while (count > 0)
  4948. {
  4949. ImGuiColorMod& backup = g.ColorModifiers.back();
  4950. g.Style.Colors[backup.Col] = backup.BackupValue;
  4951. g.ColorModifiers.pop_back();
  4952. count--;
  4953. }
  4954. }
  4955. struct ImGuiStyleVarInfo
  4956. {
  4957. ImGuiDataType Type;
  4958. ImU32 Count;
  4959. ImU32 Offset;
  4960. void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  4961. };
  4962. static const ImGuiStyleVarInfo GStyleVarInfo[] =
  4963. {
  4964. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  4965. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  4966. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  4967. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
  4968. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  4969. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
  4970. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
  4971. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
  4972. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
  4973. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
  4974. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  4975. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  4976. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
  4977. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  4978. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  4979. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  4980. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
  4981. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
  4982. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  4983. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
  4984. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
  4985. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  4986. };
  4987. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  4988. {
  4989. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
  4990. IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
  4991. return &GStyleVarInfo[idx];
  4992. }
  4993. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  4994. {
  4995. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  4996. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
  4997. {
  4998. ImGuiContext& g = *GImGui;
  4999. float* pvar = (float*)var_info->GetVarPtr(&g.Style);
  5000. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  5001. *pvar = val;
  5002. return;
  5003. }
  5004. IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
  5005. }
  5006. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  5007. {
  5008. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  5009. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
  5010. {
  5011. ImGuiContext& g = *GImGui;
  5012. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
  5013. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  5014. *pvar = val;
  5015. return;
  5016. }
  5017. IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
  5018. }
  5019. void ImGui::PopStyleVar(int count)
  5020. {
  5021. ImGuiContext& g = *GImGui;
  5022. while (count > 0)
  5023. {
  5024. // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
  5025. ImGuiStyleMod& backup = g.StyleModifiers.back();
  5026. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  5027. void* data = info->GetVarPtr(&g.Style);
  5028. if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
  5029. else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
  5030. g.StyleModifiers.pop_back();
  5031. count--;
  5032. }
  5033. }
  5034. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  5035. {
  5036. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  5037. switch (idx)
  5038. {
  5039. case ImGuiCol_Text: return "Text";
  5040. case ImGuiCol_TextDisabled: return "TextDisabled";
  5041. case ImGuiCol_WindowBg: return "WindowBg";
  5042. case ImGuiCol_ChildBg: return "ChildBg";
  5043. case ImGuiCol_PopupBg: return "PopupBg";
  5044. case ImGuiCol_Border: return "Border";
  5045. case ImGuiCol_BorderShadow: return "BorderShadow";
  5046. case ImGuiCol_FrameBg: return "FrameBg";
  5047. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  5048. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  5049. case ImGuiCol_TitleBg: return "TitleBg";
  5050. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  5051. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  5052. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  5053. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  5054. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  5055. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  5056. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  5057. case ImGuiCol_CheckMark: return "CheckMark";
  5058. case ImGuiCol_SliderGrab: return "SliderGrab";
  5059. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  5060. case ImGuiCol_Button: return "Button";
  5061. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  5062. case ImGuiCol_ButtonActive: return "ButtonActive";
  5063. case ImGuiCol_Header: return "Header";
  5064. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  5065. case ImGuiCol_HeaderActive: return "HeaderActive";
  5066. case ImGuiCol_Separator: return "Separator";
  5067. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  5068. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  5069. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  5070. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  5071. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  5072. case ImGuiCol_Tab: return "Tab";
  5073. case ImGuiCol_TabHovered: return "TabHovered";
  5074. case ImGuiCol_TabActive: return "TabActive";
  5075. case ImGuiCol_TabUnfocused: return "TabUnfocused";
  5076. case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
  5077. case ImGuiCol_PlotLines: return "PlotLines";
  5078. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  5079. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  5080. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  5081. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  5082. case ImGuiCol_DragDropTarget: return "DragDropTarget";
  5083. case ImGuiCol_NavHighlight: return "NavHighlight";
  5084. case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
  5085. case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
  5086. case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
  5087. }
  5088. IM_ASSERT(0);
  5089. return "Unknown";
  5090. }
  5091. bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
  5092. {
  5093. if (window->RootWindow == potential_parent)
  5094. return true;
  5095. while (window != NULL)
  5096. {
  5097. if (window == potential_parent)
  5098. return true;
  5099. window = window->ParentWindow;
  5100. }
  5101. return false;
  5102. }
  5103. bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
  5104. {
  5105. IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
  5106. ImGuiContext& g = *GImGui;
  5107. if (flags & ImGuiHoveredFlags_AnyWindow)
  5108. {
  5109. if (g.HoveredWindow == NULL)
  5110. return false;
  5111. }
  5112. else
  5113. {
  5114. switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
  5115. {
  5116. case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
  5117. if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
  5118. return false;
  5119. break;
  5120. case ImGuiHoveredFlags_RootWindow:
  5121. if (g.HoveredWindow != g.CurrentWindow->RootWindow)
  5122. return false;
  5123. break;
  5124. case ImGuiHoveredFlags_ChildWindows:
  5125. if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
  5126. return false;
  5127. break;
  5128. default:
  5129. if (g.HoveredWindow != g.CurrentWindow)
  5130. return false;
  5131. break;
  5132. }
  5133. }
  5134. if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
  5135. return false;
  5136. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  5137. if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
  5138. return false;
  5139. return true;
  5140. }
  5141. bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
  5142. {
  5143. ImGuiContext& g = *GImGui;
  5144. if (flags & ImGuiFocusedFlags_AnyWindow)
  5145. return g.NavWindow != NULL;
  5146. IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
  5147. switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
  5148. {
  5149. case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
  5150. return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
  5151. case ImGuiFocusedFlags_RootWindow:
  5152. return g.NavWindow == g.CurrentWindow->RootWindow;
  5153. case ImGuiFocusedFlags_ChildWindows:
  5154. return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
  5155. default:
  5156. return g.NavWindow == g.CurrentWindow;
  5157. }
  5158. }
  5159. // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
  5160. // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
  5161. // If you want a window to never be focused, you may use the e.g. NoInputs flag.
  5162. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
  5163. {
  5164. return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
  5165. }
  5166. float ImGui::GetWindowWidth()
  5167. {
  5168. ImGuiWindow* window = GImGui->CurrentWindow;
  5169. return window->Size.x;
  5170. }
  5171. float ImGui::GetWindowHeight()
  5172. {
  5173. ImGuiWindow* window = GImGui->CurrentWindow;
  5174. return window->Size.y;
  5175. }
  5176. ImVec2 ImGui::GetWindowPos()
  5177. {
  5178. ImGuiContext& g = *GImGui;
  5179. ImGuiWindow* window = g.CurrentWindow;
  5180. return window->Pos;
  5181. }
  5182. void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
  5183. {
  5184. window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
  5185. window->Scroll.x = new_scroll_x;
  5186. window->DC.CursorMaxPos.x -= window->Scroll.x;
  5187. }
  5188. void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
  5189. {
  5190. window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
  5191. window->Scroll.y = new_scroll_y;
  5192. window->DC.CursorMaxPos.y -= window->Scroll.y;
  5193. }
  5194. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  5195. {
  5196. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5197. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  5198. return;
  5199. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  5200. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5201. window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
  5202. // Set
  5203. const ImVec2 old_pos = window->Pos;
  5204. window->Pos = ImFloor(pos);
  5205. window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
  5206. window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
  5207. }
  5208. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  5209. {
  5210. ImGuiWindow* window = GetCurrentWindowRead();
  5211. SetWindowPos(window, pos, cond);
  5212. }
  5213. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  5214. {
  5215. if (ImGuiWindow* window = FindWindowByName(name))
  5216. SetWindowPos(window, pos, cond);
  5217. }
  5218. ImVec2 ImGui::GetWindowSize()
  5219. {
  5220. ImGuiWindow* window = GetCurrentWindowRead();
  5221. return window->Size;
  5222. }
  5223. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  5224. {
  5225. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5226. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  5227. return;
  5228. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  5229. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5230. // Set
  5231. if (size.x > 0.0f)
  5232. {
  5233. window->AutoFitFramesX = 0;
  5234. window->SizeFull.x = ImFloor(size.x);
  5235. }
  5236. else
  5237. {
  5238. window->AutoFitFramesX = 2;
  5239. window->AutoFitOnlyGrows = false;
  5240. }
  5241. if (size.y > 0.0f)
  5242. {
  5243. window->AutoFitFramesY = 0;
  5244. window->SizeFull.y = ImFloor(size.y);
  5245. }
  5246. else
  5247. {
  5248. window->AutoFitFramesY = 2;
  5249. window->AutoFitOnlyGrows = false;
  5250. }
  5251. }
  5252. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  5253. {
  5254. SetWindowSize(GImGui->CurrentWindow, size, cond);
  5255. }
  5256. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  5257. {
  5258. if (ImGuiWindow* window = FindWindowByName(name))
  5259. SetWindowSize(window, size, cond);
  5260. }
  5261. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  5262. {
  5263. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5264. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  5265. return;
  5266. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5267. // Set
  5268. window->Collapsed = collapsed;
  5269. }
  5270. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  5271. {
  5272. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  5273. }
  5274. bool ImGui::IsWindowCollapsed()
  5275. {
  5276. ImGuiWindow* window = GetCurrentWindowRead();
  5277. return window->Collapsed;
  5278. }
  5279. bool ImGui::IsWindowAppearing()
  5280. {
  5281. ImGuiWindow* window = GetCurrentWindowRead();
  5282. return window->Appearing;
  5283. }
  5284. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  5285. {
  5286. if (ImGuiWindow* window = FindWindowByName(name))
  5287. SetWindowCollapsed(window, collapsed, cond);
  5288. }
  5289. void ImGui::SetWindowFocus()
  5290. {
  5291. FocusWindow(GImGui->CurrentWindow);
  5292. }
  5293. void ImGui::SetWindowFocus(const char* name)
  5294. {
  5295. if (name)
  5296. {
  5297. if (ImGuiWindow* window = FindWindowByName(name))
  5298. FocusWindow(window);
  5299. }
  5300. else
  5301. {
  5302. FocusWindow(NULL);
  5303. }
  5304. }
  5305. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
  5306. {
  5307. ImGuiContext& g = *GImGui;
  5308. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  5309. g.NextWindowData.PosVal = pos;
  5310. g.NextWindowData.PosPivotVal = pivot;
  5311. g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
  5312. }
  5313. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  5314. {
  5315. ImGuiContext& g = *GImGui;
  5316. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  5317. g.NextWindowData.SizeVal = size;
  5318. g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
  5319. }
  5320. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
  5321. {
  5322. ImGuiContext& g = *GImGui;
  5323. g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
  5324. g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
  5325. g.NextWindowData.SizeCallback = custom_callback;
  5326. g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
  5327. }
  5328. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  5329. {
  5330. ImGuiContext& g = *GImGui;
  5331. g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
  5332. g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
  5333. }
  5334. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  5335. {
  5336. ImGuiContext& g = *GImGui;
  5337. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  5338. g.NextWindowData.CollapsedVal = collapsed;
  5339. g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
  5340. }
  5341. void ImGui::SetNextWindowFocus()
  5342. {
  5343. ImGuiContext& g = *GImGui;
  5344. g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
  5345. }
  5346. void ImGui::SetNextWindowBgAlpha(float alpha)
  5347. {
  5348. ImGuiContext& g = *GImGui;
  5349. g.NextWindowData.BgAlphaVal = alpha;
  5350. g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
  5351. }
  5352. // In window space (not screen space!)
  5353. ImVec2 ImGui::GetContentRegionMax()
  5354. {
  5355. ImGuiWindow* window = GetCurrentWindowRead();
  5356. ImVec2 mx = window->ContentsRegionRect.Max - window->Pos;
  5357. if (window->DC.ColumnsSet)
  5358. mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x;
  5359. return mx;
  5360. }
  5361. ImVec2 ImGui::GetContentRegionAvail()
  5362. {
  5363. ImGuiWindow* window = GetCurrentWindowRead();
  5364. return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
  5365. }
  5366. float ImGui::GetContentRegionAvailWidth()
  5367. {
  5368. return GetContentRegionAvail().x;
  5369. }
  5370. // In window space (not screen space!)
  5371. ImVec2 ImGui::GetWindowContentRegionMin()
  5372. {
  5373. ImGuiWindow* window = GetCurrentWindowRead();
  5374. return window->ContentsRegionRect.Min - window->Pos;
  5375. }
  5376. ImVec2 ImGui::GetWindowContentRegionMax()
  5377. {
  5378. ImGuiWindow* window = GetCurrentWindowRead();
  5379. return window->ContentsRegionRect.Max - window->Pos;
  5380. }
  5381. float ImGui::GetWindowContentRegionWidth()
  5382. {
  5383. ImGuiWindow* window = GetCurrentWindowRead();
  5384. return window->ContentsRegionRect.GetWidth();
  5385. }
  5386. float ImGui::GetTextLineHeight()
  5387. {
  5388. ImGuiContext& g = *GImGui;
  5389. return g.FontSize;
  5390. }
  5391. float ImGui::GetTextLineHeightWithSpacing()
  5392. {
  5393. ImGuiContext& g = *GImGui;
  5394. return g.FontSize + g.Style.ItemSpacing.y;
  5395. }
  5396. float ImGui::GetFrameHeight()
  5397. {
  5398. ImGuiContext& g = *GImGui;
  5399. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  5400. }
  5401. float ImGui::GetFrameHeightWithSpacing()
  5402. {
  5403. ImGuiContext& g = *GImGui;
  5404. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  5405. }
  5406. ImDrawList* ImGui::GetWindowDrawList()
  5407. {
  5408. ImGuiWindow* window = GetCurrentWindow();
  5409. return window->DrawList;
  5410. }
  5411. ImFont* ImGui::GetFont()
  5412. {
  5413. return GImGui->Font;
  5414. }
  5415. float ImGui::GetFontSize()
  5416. {
  5417. return GImGui->FontSize;
  5418. }
  5419. ImVec2 ImGui::GetFontTexUvWhitePixel()
  5420. {
  5421. return GImGui->DrawListSharedData.TexUvWhitePixel;
  5422. }
  5423. void ImGui::SetWindowFontScale(float scale)
  5424. {
  5425. ImGuiContext& g = *GImGui;
  5426. ImGuiWindow* window = GetCurrentWindow();
  5427. window->FontWindowScale = scale;
  5428. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  5429. }
  5430. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  5431. // 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'.
  5432. ImVec2 ImGui::GetCursorPos()
  5433. {
  5434. ImGuiWindow* window = GetCurrentWindowRead();
  5435. return window->DC.CursorPos - window->Pos + window->Scroll;
  5436. }
  5437. float ImGui::GetCursorPosX()
  5438. {
  5439. ImGuiWindow* window = GetCurrentWindowRead();
  5440. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  5441. }
  5442. float ImGui::GetCursorPosY()
  5443. {
  5444. ImGuiWindow* window = GetCurrentWindowRead();
  5445. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  5446. }
  5447. void ImGui::SetCursorPos(const ImVec2& local_pos)
  5448. {
  5449. ImGuiWindow* window = GetCurrentWindow();
  5450. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  5451. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5452. }
  5453. void ImGui::SetCursorPosX(float x)
  5454. {
  5455. ImGuiWindow* window = GetCurrentWindow();
  5456. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  5457. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  5458. }
  5459. void ImGui::SetCursorPosY(float y)
  5460. {
  5461. ImGuiWindow* window = GetCurrentWindow();
  5462. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  5463. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  5464. }
  5465. ImVec2 ImGui::GetCursorStartPos()
  5466. {
  5467. ImGuiWindow* window = GetCurrentWindowRead();
  5468. return window->DC.CursorStartPos - window->Pos;
  5469. }
  5470. ImVec2 ImGui::GetCursorScreenPos()
  5471. {
  5472. ImGuiWindow* window = GetCurrentWindowRead();
  5473. return window->DC.CursorPos;
  5474. }
  5475. void ImGui::SetCursorScreenPos(const ImVec2& pos)
  5476. {
  5477. ImGuiWindow* window = GetCurrentWindow();
  5478. window->DC.CursorPos = pos;
  5479. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5480. }
  5481. float ImGui::GetScrollX()
  5482. {
  5483. return GImGui->CurrentWindow->Scroll.x;
  5484. }
  5485. float ImGui::GetScrollY()
  5486. {
  5487. return GImGui->CurrentWindow->Scroll.y;
  5488. }
  5489. float ImGui::GetScrollMaxX()
  5490. {
  5491. return GetWindowScrollMaxX(GImGui->CurrentWindow);
  5492. }
  5493. float ImGui::GetScrollMaxY()
  5494. {
  5495. return GetWindowScrollMaxY(GImGui->CurrentWindow);
  5496. }
  5497. void ImGui::SetScrollX(float scroll_x)
  5498. {
  5499. ImGuiWindow* window = GetCurrentWindow();
  5500. window->ScrollTarget.x = scroll_x;
  5501. window->ScrollTargetCenterRatio.x = 0.0f;
  5502. }
  5503. void ImGui::SetScrollY(float scroll_y)
  5504. {
  5505. ImGuiWindow* window = GetCurrentWindow();
  5506. window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
  5507. window->ScrollTargetCenterRatio.y = 0.0f;
  5508. }
  5509. void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
  5510. {
  5511. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  5512. ImGuiWindow* window = GetCurrentWindow();
  5513. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  5514. window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y);
  5515. window->ScrollTargetCenterRatio.y = center_y_ratio;
  5516. }
  5517. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  5518. void ImGui::SetScrollHereY(float center_y_ratio)
  5519. {
  5520. ImGuiWindow* window = GetCurrentWindow();
  5521. float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
  5522. target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
  5523. SetScrollFromPosY(target_y, center_y_ratio);
  5524. }
  5525. void ImGui::ActivateItem(ImGuiID id)
  5526. {
  5527. ImGuiContext& g = *GImGui;
  5528. g.NavNextActivateId = id;
  5529. }
  5530. void ImGui::SetKeyboardFocusHere(int offset)
  5531. {
  5532. IM_ASSERT(offset >= -1); // -1 is allowed but not below
  5533. ImGuiWindow* window = GetCurrentWindow();
  5534. window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
  5535. window->FocusIdxTabRequestNext = INT_MAX;
  5536. }
  5537. void ImGui::SetItemDefaultFocus()
  5538. {
  5539. ImGuiContext& g = *GImGui;
  5540. ImGuiWindow* window = g.CurrentWindow;
  5541. if (!window->Appearing)
  5542. return;
  5543. if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
  5544. {
  5545. g.NavInitRequest = false;
  5546. g.NavInitResultId = g.NavWindow->DC.LastItemId;
  5547. g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
  5548. NavUpdateAnyRequestFlag();
  5549. if (!IsItemVisible())
  5550. SetScrollHereY();
  5551. }
  5552. }
  5553. void ImGui::SetStateStorage(ImGuiStorage* tree)
  5554. {
  5555. ImGuiWindow* window = GetCurrentWindow();
  5556. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  5557. }
  5558. ImGuiStorage* ImGui::GetStateStorage()
  5559. {
  5560. ImGuiWindow* window = GetCurrentWindowRead();
  5561. return window->DC.StateStorage;
  5562. }
  5563. void ImGui::PushID(const char* str_id)
  5564. {
  5565. ImGuiWindow* window = GetCurrentWindowRead();
  5566. window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
  5567. }
  5568. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  5569. {
  5570. ImGuiWindow* window = GetCurrentWindowRead();
  5571. window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
  5572. }
  5573. void ImGui::PushID(const void* ptr_id)
  5574. {
  5575. ImGuiWindow* window = GetCurrentWindowRead();
  5576. window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
  5577. }
  5578. void ImGui::PushID(int int_id)
  5579. {
  5580. const void* ptr_id = (void*)(intptr_t)int_id;
  5581. ImGuiWindow* window = GetCurrentWindowRead();
  5582. window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
  5583. }
  5584. void ImGui::PopID()
  5585. {
  5586. ImGuiWindow* window = GetCurrentWindowRead();
  5587. window->IDStack.pop_back();
  5588. }
  5589. ImGuiID ImGui::GetID(const char* str_id)
  5590. {
  5591. return GImGui->CurrentWindow->GetID(str_id);
  5592. }
  5593. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  5594. {
  5595. return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
  5596. }
  5597. ImGuiID ImGui::GetID(const void* ptr_id)
  5598. {
  5599. return GImGui->CurrentWindow->GetID(ptr_id);
  5600. }
  5601. bool ImGui::IsRectVisible(const ImVec2& size)
  5602. {
  5603. ImGuiWindow* window = GetCurrentWindowRead();
  5604. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  5605. }
  5606. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  5607. {
  5608. ImGuiWindow* window = GetCurrentWindowRead();
  5609. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  5610. }
  5611. // 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.)
  5612. void ImGui::BeginGroup()
  5613. {
  5614. ImGuiContext& g = *GImGui;
  5615. ImGuiWindow* window = GetCurrentWindow();
  5616. window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
  5617. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  5618. group_data.BackupCursorPos = window->DC.CursorPos;
  5619. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  5620. group_data.BackupIndent = window->DC.Indent;
  5621. group_data.BackupGroupOffset = window->DC.GroupOffset;
  5622. group_data.BackupCurrentLineSize = window->DC.CurrentLineSize;
  5623. group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
  5624. group_data.BackupLogLinePosY = window->DC.LogLinePosY;
  5625. group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
  5626. group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
  5627. group_data.AdvanceCursor = true;
  5628. window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
  5629. window->DC.Indent = window->DC.GroupOffset;
  5630. window->DC.CursorMaxPos = window->DC.CursorPos;
  5631. window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
  5632. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return
  5633. }
  5634. void ImGui::EndGroup()
  5635. {
  5636. ImGuiContext& g = *GImGui;
  5637. ImGuiWindow* window = GetCurrentWindow();
  5638. IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
  5639. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  5640. ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
  5641. group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
  5642. window->DC.CursorPos = group_data.BackupCursorPos;
  5643. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  5644. window->DC.Indent = group_data.BackupIndent;
  5645. window->DC.GroupOffset = group_data.BackupGroupOffset;
  5646. window->DC.CurrentLineSize = group_data.BackupCurrentLineSize;
  5647. window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
  5648. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return
  5649. if (group_data.AdvanceCursor)
  5650. {
  5651. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
  5652. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
  5653. ItemAdd(group_bb, 0);
  5654. }
  5655. // 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.
  5656. // 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.
  5657. // (and if you grep for LastItemId you'll notice it is only used in that context.
  5658. if ((group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId) // && g.ActiveIdWindow->RootWindow == window->RootWindow)
  5659. window->DC.LastItemId = g.ActiveId;
  5660. else if (!group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive) // && g.ActiveIdPreviousFrameWindow->RootWindow == window->RootWindow)
  5661. window->DC.LastItemId = g.ActiveIdPreviousFrame;
  5662. window->DC.LastItemRect = group_bb;
  5663. window->DC.GroupStack.pop_back();
  5664. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  5665. }
  5666. // Gets back to previous line and continue with horizontal layout
  5667. // pos_x == 0 : follow right after previous item
  5668. // pos_x != 0 : align to specified x position (relative to window/group left)
  5669. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  5670. // spacing_w >= 0 : enforce spacing amount
  5671. void ImGui::SameLine(float pos_x, float spacing_w)
  5672. {
  5673. ImGuiWindow* window = GetCurrentWindow();
  5674. if (window->SkipItems)
  5675. return;
  5676. ImGuiContext& g = *GImGui;
  5677. if (pos_x != 0.0f)
  5678. {
  5679. if (spacing_w < 0.0f) spacing_w = 0.0f;
  5680. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
  5681. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  5682. }
  5683. else
  5684. {
  5685. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  5686. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  5687. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  5688. }
  5689. window->DC.CurrentLineSize = window->DC.PrevLineSize;
  5690. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  5691. }
  5692. void ImGui::Indent(float indent_w)
  5693. {
  5694. ImGuiContext& g = *GImGui;
  5695. ImGuiWindow* window = GetCurrentWindow();
  5696. window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  5697. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  5698. }
  5699. void ImGui::Unindent(float indent_w)
  5700. {
  5701. ImGuiContext& g = *GImGui;
  5702. ImGuiWindow* window = GetCurrentWindow();
  5703. window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  5704. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  5705. }
  5706. //-----------------------------------------------------------------------------
  5707. // [SECTION] TOOLTIPS
  5708. //-----------------------------------------------------------------------------
  5709. void ImGui::BeginTooltip()
  5710. {
  5711. ImGuiContext& g = *GImGui;
  5712. if (g.DragDropWithinSourceOrTarget)
  5713. {
  5714. // 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)
  5715. // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
  5716. // 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.
  5717. //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
  5718. ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
  5719. SetNextWindowPos(tooltip_pos);
  5720. SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
  5721. //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
  5722. BeginTooltipEx(0, true);
  5723. }
  5724. else
  5725. {
  5726. BeginTooltipEx(0, false);
  5727. }
  5728. }
  5729. // Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
  5730. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
  5731. {
  5732. ImGuiContext& g = *GImGui;
  5733. char window_name[16];
  5734. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
  5735. if (override_previous_tooltip)
  5736. if (ImGuiWindow* window = FindWindowByName(window_name))
  5737. if (window->Active)
  5738. {
  5739. // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
  5740. window->Hidden = true;
  5741. window->HiddenFramesRegular = 1;
  5742. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
  5743. }
  5744. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
  5745. Begin(window_name, NULL, flags | extra_flags);
  5746. }
  5747. void ImGui::EndTooltip()
  5748. {
  5749. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  5750. End();
  5751. }
  5752. void ImGui::SetTooltipV(const char* fmt, va_list args)
  5753. {
  5754. ImGuiContext& g = *GImGui;
  5755. if (g.DragDropWithinSourceOrTarget)
  5756. BeginTooltip();
  5757. else
  5758. BeginTooltipEx(0, true);
  5759. TextV(fmt, args);
  5760. EndTooltip();
  5761. }
  5762. void ImGui::SetTooltip(const char* fmt, ...)
  5763. {
  5764. va_list args;
  5765. va_start(args, fmt);
  5766. SetTooltipV(fmt, args);
  5767. va_end(args);
  5768. }
  5769. //-----------------------------------------------------------------------------
  5770. // [SECTION] POPUPS
  5771. //-----------------------------------------------------------------------------
  5772. bool ImGui::IsPopupOpen(ImGuiID id)
  5773. {
  5774. ImGuiContext& g = *GImGui;
  5775. return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
  5776. }
  5777. bool ImGui::IsPopupOpen(const char* str_id)
  5778. {
  5779. ImGuiContext& g = *GImGui;
  5780. return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
  5781. }
  5782. ImGuiWindow* ImGui::GetFrontMostPopupModal()
  5783. {
  5784. ImGuiContext& g = *GImGui;
  5785. for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
  5786. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  5787. if (popup->Flags & ImGuiWindowFlags_Modal)
  5788. return popup;
  5789. return NULL;
  5790. }
  5791. void ImGui::OpenPopup(const char* str_id)
  5792. {
  5793. ImGuiContext& g = *GImGui;
  5794. OpenPopupEx(g.CurrentWindow->GetID(str_id));
  5795. }
  5796. // Mark popup as open (toggle toward open state).
  5797. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  5798. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  5799. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  5800. void ImGui::OpenPopupEx(ImGuiID id)
  5801. {
  5802. ImGuiContext& g = *GImGui;
  5803. ImGuiWindow* parent_window = g.CurrentWindow;
  5804. int current_stack_size = g.BeginPopupStack.Size;
  5805. ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
  5806. popup_ref.PopupId = id;
  5807. popup_ref.Window = NULL;
  5808. popup_ref.ParentWindow = parent_window;
  5809. popup_ref.OpenFrameCount = g.FrameCount;
  5810. popup_ref.OpenParentId = parent_window->IDStack.back();
  5811. popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
  5812. popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
  5813. //IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
  5814. if (g.OpenPopupStack.Size < current_stack_size + 1)
  5815. {
  5816. g.OpenPopupStack.push_back(popup_ref);
  5817. }
  5818. else
  5819. {
  5820. // 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
  5821. // 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
  5822. // 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.
  5823. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
  5824. {
  5825. g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
  5826. }
  5827. else
  5828. {
  5829. // Close child popups if any, then flag popup for open/reopen
  5830. g.OpenPopupStack.resize(current_stack_size + 1);
  5831. g.OpenPopupStack[current_stack_size] = popup_ref;
  5832. }
  5833. // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
  5834. // This is equivalent to what ClosePopupToLevel() does.
  5835. //if (g.OpenPopupStack[current_stack_size].PopupId == id)
  5836. // FocusWindow(parent_window);
  5837. }
  5838. }
  5839. bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
  5840. {
  5841. ImGuiWindow* window = GImGui->CurrentWindow;
  5842. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  5843. {
  5844. ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  5845. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  5846. OpenPopupEx(id);
  5847. return true;
  5848. }
  5849. return false;
  5850. }
  5851. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
  5852. {
  5853. ImGuiContext& g = *GImGui;
  5854. if (g.OpenPopupStack.empty())
  5855. return;
  5856. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  5857. // Don't close our own child popup windows.
  5858. int popup_count_to_keep = 0;
  5859. if (ref_window)
  5860. {
  5861. // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
  5862. for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
  5863. {
  5864. ImGuiPopupRef& popup = g.OpenPopupStack[popup_count_to_keep];
  5865. if (!popup.Window)
  5866. continue;
  5867. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  5868. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  5869. continue;
  5870. // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow)
  5871. bool popup_or_descendent_has_focus = false;
  5872. for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_has_focus; m++)
  5873. if (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow)
  5874. popup_or_descendent_has_focus = true;
  5875. if (!popup_or_descendent_has_focus)
  5876. break;
  5877. }
  5878. }
  5879. 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
  5880. {
  5881. //IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
  5882. ClosePopupToLevel(popup_count_to_keep, false);
  5883. }
  5884. }
  5885. void ImGui::ClosePopupToLevel(int remaining, bool apply_focus_to_window_under)
  5886. {
  5887. IM_ASSERT(remaining >= 0);
  5888. ImGuiContext& g = *GImGui;
  5889. ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow;
  5890. g.OpenPopupStack.resize(remaining);
  5891. // FIXME: This code is faulty and we may want to eventually to replace or remove the 'apply_focus_to_window_under=true' path completely.
  5892. // Instead of using g.OpenPopupStack[remaining-1].Window etc. we should find the highest root window that is behind the popups we are closing.
  5893. // The current code will set focus to the parent of the popup window which is incorrect.
  5894. // It rarely manifested until now because UpdateMouseMovingWindow() would call FocusWindow() again on the clicked window,
  5895. // leading to a chain of focusing A (clicked window) then B (parent window of the popup) then A again.
  5896. // However if the clicked window has the _NoMove flag set we would be left with B focused.
  5897. // For now, we have disabled this path when called from ClosePopupsOverWindow() because the users of ClosePopupsOverWindow() don't need to alter focus anyway,
  5898. // but we should inspect and fix this properly.
  5899. if (apply_focus_to_window_under)
  5900. {
  5901. if (g.NavLayer == 0)
  5902. focus_window = NavRestoreLastChildNavWindow(focus_window);
  5903. FocusWindow(focus_window);
  5904. }
  5905. }
  5906. // Close the popup we have begin-ed into.
  5907. void ImGui::CloseCurrentPopup()
  5908. {
  5909. ImGuiContext& g = *GImGui;
  5910. int popup_idx = g.BeginPopupStack.Size - 1;
  5911. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  5912. return;
  5913. while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
  5914. popup_idx--;
  5915. ClosePopupToLevel(popup_idx, true);
  5916. // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
  5917. // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
  5918. // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
  5919. if (ImGuiWindow* window = g.NavWindow)
  5920. window->DC.NavHideHighlightOneFrame = true;
  5921. }
  5922. bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
  5923. {
  5924. ImGuiContext& g = *GImGui;
  5925. if (!IsPopupOpen(id))
  5926. {
  5927. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  5928. return false;
  5929. }
  5930. char name[20];
  5931. if (extra_flags & ImGuiWindowFlags_ChildMenu)
  5932. ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
  5933. else
  5934. ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
  5935. bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
  5936. if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
  5937. EndPopup();
  5938. return is_open;
  5939. }
  5940. bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
  5941. {
  5942. ImGuiContext& g = *GImGui;
  5943. if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
  5944. {
  5945. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  5946. return false;
  5947. }
  5948. flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
  5949. return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
  5950. }
  5951. // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
  5952. // Note that popup visibility status is owned by imgui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
  5953. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
  5954. {
  5955. ImGuiContext& g = *GImGui;
  5956. ImGuiWindow* window = g.CurrentWindow;
  5957. const ImGuiID id = window->GetID(name);
  5958. if (!IsPopupOpen(id))
  5959. {
  5960. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  5961. return false;
  5962. }
  5963. // Center modal windows by default
  5964. // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
  5965. if (g.NextWindowData.PosCond == 0)
  5966. SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
  5967. flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
  5968. const bool is_open = Begin(name, p_open, flags);
  5969. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  5970. {
  5971. EndPopup();
  5972. if (is_open)
  5973. ClosePopupToLevel(g.BeginPopupStack.Size, true);
  5974. return false;
  5975. }
  5976. return is_open;
  5977. }
  5978. void ImGui::EndPopup()
  5979. {
  5980. ImGuiContext& g = *GImGui; (void)g;
  5981. IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  5982. IM_ASSERT(g.BeginPopupStack.Size > 0);
  5983. // Make all menus and popups wrap around for now, may need to expose that policy.
  5984. NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY);
  5985. End();
  5986. }
  5987. // This is a helper to handle the simplest case of associating one named popup to one given widget.
  5988. // You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
  5989. // You can pass a NULL str_id to use the identifier of the last item.
  5990. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
  5991. {
  5992. ImGuiWindow* window = GImGui->CurrentWindow;
  5993. ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  5994. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  5995. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  5996. OpenPopupEx(id);
  5997. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  5998. }
  5999. bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
  6000. {
  6001. if (!str_id)
  6002. str_id = "window_context";
  6003. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  6004. if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  6005. if (also_over_items || !IsAnyItemHovered())
  6006. OpenPopupEx(id);
  6007. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  6008. }
  6009. bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
  6010. {
  6011. if (!str_id)
  6012. str_id = "void_context";
  6013. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  6014. if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
  6015. OpenPopupEx(id);
  6016. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  6017. }
  6018. ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow*)
  6019. {
  6020. ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
  6021. ImRect r_screen = GetViewportRect();
  6022. r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
  6023. return r_screen;
  6024. }
  6025. // 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.)
  6026. // 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.
  6027. ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
  6028. {
  6029. ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
  6030. //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
  6031. //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
  6032. // Combo Box policy (we want a connecting edge)
  6033. if (policy == ImGuiPopupPositionPolicy_ComboBox)
  6034. {
  6035. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
  6036. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  6037. {
  6038. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  6039. if (n != -1 && dir == *last_dir) // Already tried this direction?
  6040. continue;
  6041. ImVec2 pos;
  6042. if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
  6043. if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
  6044. if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
  6045. if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
  6046. if (!r_outer.Contains(ImRect(pos, pos + size)))
  6047. continue;
  6048. *last_dir = dir;
  6049. return pos;
  6050. }
  6051. }
  6052. // Default popup policy
  6053. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
  6054. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  6055. {
  6056. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  6057. if (n != -1 && dir == *last_dir) // Already tried this direction?
  6058. continue;
  6059. 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);
  6060. 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);
  6061. if (avail_w < size.x || avail_h < size.y)
  6062. continue;
  6063. ImVec2 pos;
  6064. pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
  6065. pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
  6066. *last_dir = dir;
  6067. return pos;
  6068. }
  6069. // Fallback, try to keep within display
  6070. *last_dir = ImGuiDir_None;
  6071. ImVec2 pos = ref_pos;
  6072. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  6073. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  6074. return pos;
  6075. }
  6076. ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
  6077. {
  6078. ImGuiContext& g = *GImGui;
  6079. ImRect r_outer = GetWindowAllowedExtentRect(window);
  6080. if (window->Flags & ImGuiWindowFlags_ChildMenu)
  6081. {
  6082. // Child menus typically request _any_ position within the parent menu item, and then our FindBestWindowPosForPopup() function will move the new menu outside the parent bounds.
  6083. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  6084. IM_ASSERT(g.CurrentWindow == window);
  6085. ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
  6086. float horizontal_overlap = g.Style.ItemSpacing.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).
  6087. ImRect r_avoid;
  6088. if (parent_window->DC.MenuBarAppending)
  6089. r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
  6090. else
  6091. 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);
  6092. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
  6093. }
  6094. if (window->Flags & ImGuiWindowFlags_Popup)
  6095. {
  6096. ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
  6097. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
  6098. }
  6099. if (window->Flags & ImGuiWindowFlags_Tooltip)
  6100. {
  6101. // Position tooltip (always follows mouse)
  6102. float sc = g.Style.MouseCursorScale;
  6103. ImVec2 ref_pos = NavCalcPreferredRefPos();
  6104. ImRect r_avoid;
  6105. if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
  6106. r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
  6107. else
  6108. 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.
  6109. ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
  6110. if (window->AutoPosLastDirection == ImGuiDir_None)
  6111. pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  6112. return pos;
  6113. }
  6114. IM_ASSERT(0);
  6115. return window->Pos;
  6116. }
  6117. //-----------------------------------------------------------------------------
  6118. // [SECTION] VIEWPORTS, PLATFORM WINDOWS
  6119. //-----------------------------------------------------------------------------
  6120. // (this section is filled in the 'viewport' and 'docking' branches)
  6121. //-----------------------------------------------------------------------------
  6122. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  6123. //-----------------------------------------------------------------------------
  6124. ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
  6125. {
  6126. if (ImFabs(dx) > ImFabs(dy))
  6127. return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
  6128. return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
  6129. }
  6130. static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
  6131. {
  6132. if (a1 < b0)
  6133. return a1 - b0;
  6134. if (b1 < a0)
  6135. return a0 - b1;
  6136. return 0.0f;
  6137. }
  6138. static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
  6139. {
  6140. if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
  6141. {
  6142. r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
  6143. r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
  6144. }
  6145. else
  6146. {
  6147. r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
  6148. r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
  6149. }
  6150. }
  6151. // Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
  6152. static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
  6153. {
  6154. ImGuiContext& g = *GImGui;
  6155. ImGuiWindow* window = g.CurrentWindow;
  6156. if (g.NavLayer != window->DC.NavLayerCurrent)
  6157. return false;
  6158. const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
  6159. g.NavScoringCount++;
  6160. // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
  6161. if (window->ParentWindow == g.NavWindow)
  6162. {
  6163. IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
  6164. if (!window->ClipRect.Contains(cand))
  6165. return false;
  6166. cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
  6167. }
  6168. // 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)
  6169. // For example, this ensure that items in one column are not reached when moving vertically from items in another column.
  6170. NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
  6171. // Compute distance between boxes
  6172. // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
  6173. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
  6174. 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
  6175. if (dby != 0.0f && dbx != 0.0f)
  6176. dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
  6177. float dist_box = ImFabs(dbx) + ImFabs(dby);
  6178. // 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)
  6179. float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
  6180. float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
  6181. float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
  6182. // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
  6183. ImGuiDir quadrant;
  6184. float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
  6185. if (dbx != 0.0f || dby != 0.0f)
  6186. {
  6187. // For non-overlapping boxes, use distance between boxes
  6188. dax = dbx;
  6189. day = dby;
  6190. dist_axial = dist_box;
  6191. quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
  6192. }
  6193. else if (dcx != 0.0f || dcy != 0.0f)
  6194. {
  6195. // For overlapping boxes with different centers, use distance between centers
  6196. dax = dcx;
  6197. day = dcy;
  6198. dist_axial = dist_center;
  6199. quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
  6200. }
  6201. else
  6202. {
  6203. // 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)
  6204. quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
  6205. }
  6206. #if IMGUI_DEBUG_NAV_SCORING
  6207. char buf[128];
  6208. if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max))
  6209. {
  6210. 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]);
  6211. ImDrawList* draw_list = ImGui::GetOverlayDrawList(window);
  6212. draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
  6213. draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
  6214. draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
  6215. draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
  6216. }
  6217. else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
  6218. {
  6219. if (ImGui::IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
  6220. if (quadrant == g.NavMoveDir)
  6221. {
  6222. ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
  6223. ImDrawList* draw_list = ImGui::GetOverlayDrawList(window);
  6224. draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
  6225. draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
  6226. }
  6227. }
  6228. #endif
  6229. // Is it in the quadrant we're interesting in moving to?
  6230. bool new_best = false;
  6231. if (quadrant == g.NavMoveDir)
  6232. {
  6233. // Does it beat the current best candidate?
  6234. if (dist_box < result->DistBox)
  6235. {
  6236. result->DistBox = dist_box;
  6237. result->DistCenter = dist_center;
  6238. return true;
  6239. }
  6240. if (dist_box == result->DistBox)
  6241. {
  6242. // Try using distance between center points to break ties
  6243. if (dist_center < result->DistCenter)
  6244. {
  6245. result->DistCenter = dist_center;
  6246. new_best = true;
  6247. }
  6248. else if (dist_center == result->DistCenter)
  6249. {
  6250. // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
  6251. // (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),
  6252. // 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.
  6253. if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
  6254. new_best = true;
  6255. }
  6256. }
  6257. }
  6258. // 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
  6259. // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
  6260. // 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.
  6261. // 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.
  6262. // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
  6263. if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
  6264. if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
  6265. if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
  6266. {
  6267. result->DistAxial = dist_axial;
  6268. new_best = true;
  6269. }
  6270. return new_best;
  6271. }
  6272. // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
  6273. static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
  6274. {
  6275. ImGuiContext& g = *GImGui;
  6276. //if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
  6277. // return;
  6278. const ImGuiItemFlags item_flags = window->DC.ItemFlags;
  6279. const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
  6280. // Process Init Request
  6281. if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
  6282. {
  6283. // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
  6284. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
  6285. {
  6286. g.NavInitResultId = id;
  6287. g.NavInitResultRectRel = nav_bb_rel;
  6288. }
  6289. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
  6290. {
  6291. g.NavInitRequest = false; // Found a match, clear request
  6292. NavUpdateAnyRequestFlag();
  6293. }
  6294. }
  6295. // Process Move Request (scoring for navigation)
  6296. // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
  6297. if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_NoNav))
  6298. {
  6299. ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  6300. #if IMGUI_DEBUG_NAV_SCORING
  6301. // [DEBUG] Score all items in NavWindow at all times
  6302. if (!g.NavMoveRequest)
  6303. g.NavMoveDir = g.NavMoveDirLast;
  6304. bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
  6305. #else
  6306. bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
  6307. #endif
  6308. if (new_best)
  6309. {
  6310. result->ID = id;
  6311. result->Window = window;
  6312. result->RectRel = nav_bb_rel;
  6313. }
  6314. const float VISIBLE_RATIO = 0.70f;
  6315. if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
  6316. 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)
  6317. if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
  6318. {
  6319. result = &g.NavMoveResultLocalVisibleSet;
  6320. result->ID = id;
  6321. result->Window = window;
  6322. result->RectRel = nav_bb_rel;
  6323. }
  6324. }
  6325. // Update window-relative bounding box of navigated item
  6326. if (g.NavId == id)
  6327. {
  6328. g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
  6329. g.NavLayer = window->DC.NavLayerCurrent;
  6330. g.NavIdIsAlive = true;
  6331. g.NavIdTabCounter = window->FocusIdxTabCounter;
  6332. window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
  6333. }
  6334. }
  6335. bool ImGui::NavMoveRequestButNoResultYet()
  6336. {
  6337. ImGuiContext& g = *GImGui;
  6338. return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
  6339. }
  6340. void ImGui::NavMoveRequestCancel()
  6341. {
  6342. ImGuiContext& g = *GImGui;
  6343. g.NavMoveRequest = false;
  6344. NavUpdateAnyRequestFlag();
  6345. }
  6346. void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
  6347. {
  6348. ImGuiContext& g = *GImGui;
  6349. IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
  6350. ImGui::NavMoveRequestCancel();
  6351. g.NavMoveDir = move_dir;
  6352. g.NavMoveClipDir = clip_dir;
  6353. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
  6354. g.NavMoveRequestFlags = move_flags;
  6355. g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
  6356. }
  6357. void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
  6358. {
  6359. ImGuiContext& g = *GImGui;
  6360. if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
  6361. return;
  6362. IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
  6363. ImRect bb_rel = window->NavRectRel[0];
  6364. ImGuiDir clip_dir = g.NavMoveDir;
  6365. if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  6366. {
  6367. bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x) - window->Scroll.x;
  6368. if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
  6369. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  6370. }
  6371. if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  6372. {
  6373. bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
  6374. if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
  6375. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  6376. }
  6377. if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  6378. {
  6379. bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y) - window->Scroll.y;
  6380. if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
  6381. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  6382. }
  6383. if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  6384. {
  6385. bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
  6386. if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
  6387. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  6388. }
  6389. }
  6390. static void ImGui::NavSaveLastChildNavWindow(ImGuiWindow* nav_window)
  6391. {
  6392. ImGuiWindow* parent_window = nav_window;
  6393. while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  6394. parent_window = parent_window->ParentWindow;
  6395. if (parent_window && parent_window != nav_window)
  6396. parent_window->NavLastChildNavWindow = nav_window;
  6397. }
  6398. // Call when we are expected to land on Layer 0 after FocusWindow()
  6399. static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
  6400. {
  6401. return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
  6402. }
  6403. static void NavRestoreLayer(ImGuiNavLayer layer)
  6404. {
  6405. ImGuiContext& g = *GImGui;
  6406. g.NavLayer = layer;
  6407. if (layer == 0)
  6408. g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
  6409. if (layer == 0 && g.NavWindow->NavLastIds[0] != 0)
  6410. ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]);
  6411. else
  6412. ImGui::NavInitWindow(g.NavWindow, true);
  6413. }
  6414. static inline void ImGui::NavUpdateAnyRequestFlag()
  6415. {
  6416. ImGuiContext& g = *GImGui;
  6417. g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
  6418. if (g.NavAnyRequest)
  6419. IM_ASSERT(g.NavWindow != NULL);
  6420. }
  6421. // This needs to be called before we submit any widget (aka in or before Begin)
  6422. void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
  6423. {
  6424. ImGuiContext& g = *GImGui;
  6425. IM_ASSERT(window == g.NavWindow);
  6426. bool init_for_nav = false;
  6427. if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
  6428. if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
  6429. init_for_nav = true;
  6430. if (init_for_nav)
  6431. {
  6432. SetNavID(0, g.NavLayer);
  6433. g.NavInitRequest = true;
  6434. g.NavInitRequestFromMove = false;
  6435. g.NavInitResultId = 0;
  6436. g.NavInitResultRectRel = ImRect();
  6437. NavUpdateAnyRequestFlag();
  6438. }
  6439. else
  6440. {
  6441. g.NavId = window->NavLastIds[0];
  6442. }
  6443. }
  6444. static ImVec2 ImGui::NavCalcPreferredRefPos()
  6445. {
  6446. ImGuiContext& g = *GImGui;
  6447. if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
  6448. {
  6449. // Mouse (we need a fallback in case the mouse becomes invalid after being used)
  6450. if (IsMousePosValid(&g.IO.MousePos))
  6451. return g.IO.MousePos;
  6452. return g.LastValidMousePos;
  6453. }
  6454. else
  6455. {
  6456. // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
  6457. const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
  6458. ImVec2 pos = g.NavWindow->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()));
  6459. ImRect visible_rect = GetViewportRect();
  6460. return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
  6461. }
  6462. }
  6463. float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
  6464. {
  6465. ImGuiContext& g = *GImGui;
  6466. if (mode == ImGuiInputReadMode_Down)
  6467. return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
  6468. const float t = g.IO.NavInputsDownDuration[n];
  6469. if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
  6470. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
  6471. if (t < 0.0f)
  6472. return 0.0f;
  6473. if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
  6474. return (t == 0.0f) ? 1.0f : 0.0f;
  6475. if (mode == ImGuiInputReadMode_Repeat)
  6476. return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
  6477. if (mode == ImGuiInputReadMode_RepeatSlow)
  6478. return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
  6479. if (mode == ImGuiInputReadMode_RepeatFast)
  6480. return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
  6481. return 0.0f;
  6482. }
  6483. ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
  6484. {
  6485. ImVec2 delta(0.0f, 0.0f);
  6486. if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
  6487. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
  6488. if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
  6489. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
  6490. if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
  6491. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
  6492. if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
  6493. delta *= slow_factor;
  6494. if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
  6495. delta *= fast_factor;
  6496. return delta;
  6497. }
  6498. // Scroll to keep newly navigated item fully into view
  6499. // NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated.
  6500. static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect)
  6501. {
  6502. ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1));
  6503. //GetOverlayDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
  6504. if (window_rect.Contains(item_rect))
  6505. return;
  6506. ImGuiContext& g = *GImGui;
  6507. if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
  6508. {
  6509. window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x;
  6510. window->ScrollTargetCenterRatio.x = 0.0f;
  6511. }
  6512. else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
  6513. {
  6514. window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x;
  6515. window->ScrollTargetCenterRatio.x = 1.0f;
  6516. }
  6517. if (item_rect.Min.y < window_rect.Min.y)
  6518. {
  6519. window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y;
  6520. window->ScrollTargetCenterRatio.y = 0.0f;
  6521. }
  6522. else if (item_rect.Max.y >= window_rect.Max.y)
  6523. {
  6524. window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y;
  6525. window->ScrollTargetCenterRatio.y = 1.0f;
  6526. }
  6527. }
  6528. static void ImGui::NavUpdate()
  6529. {
  6530. ImGuiContext& g = *GImGui;
  6531. g.IO.WantSetMousePos = false;
  6532. #if 0
  6533. if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
  6534. #endif
  6535. // Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard)
  6536. bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  6537. bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  6538. if (nav_gamepad_active)
  6539. if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
  6540. g.NavInputSource = ImGuiInputSource_NavGamepad;
  6541. // Update Keyboard->Nav inputs mapping
  6542. if (nav_keyboard_active)
  6543. {
  6544. #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; }
  6545. NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
  6546. NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
  6547. NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
  6548. NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
  6549. NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
  6550. NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
  6551. NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
  6552. if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
  6553. if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
  6554. if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
  6555. #undef NAV_MAP_KEY
  6556. }
  6557. memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
  6558. for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
  6559. g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  6560. // Process navigation init request (select first/default focus)
  6561. if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
  6562. {
  6563. // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
  6564. IM_ASSERT(g.NavWindow);
  6565. if (g.NavInitRequestFromMove)
  6566. SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
  6567. else
  6568. SetNavID(g.NavInitResultId, g.NavLayer);
  6569. g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
  6570. }
  6571. g.NavInitRequest = false;
  6572. g.NavInitRequestFromMove = false;
  6573. g.NavInitResultId = 0;
  6574. g.NavJustMovedToId = 0;
  6575. // Process navigation move request
  6576. if (g.NavMoveRequest)
  6577. NavUpdateMoveResult();
  6578. // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
  6579. if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
  6580. {
  6581. IM_ASSERT(g.NavMoveRequest);
  6582. if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
  6583. g.NavDisableHighlight = false;
  6584. g.NavMoveRequestForward = ImGuiNavForward_None;
  6585. }
  6586. // Apply application mouse position movement, after we had a chance to process move request result.
  6587. if (g.NavMousePosDirty && g.NavIdIsAlive)
  6588. {
  6589. // Set mouse position given our knowledge of the navigated item position from last frame
  6590. if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
  6591. {
  6592. if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
  6593. {
  6594. g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
  6595. g.IO.WantSetMousePos = true;
  6596. }
  6597. }
  6598. g.NavMousePosDirty = false;
  6599. }
  6600. g.NavIdIsAlive = false;
  6601. g.NavJustTabbedId = 0;
  6602. IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
  6603. // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
  6604. if (g.NavWindow)
  6605. NavSaveLastChildNavWindow(g.NavWindow);
  6606. if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
  6607. g.NavWindow->NavLastChildNavWindow = NULL;
  6608. // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
  6609. NavUpdateWindowing();
  6610. // Set output flags for user application
  6611. g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
  6612. g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL) || g.NavInitRequest;
  6613. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  6614. if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
  6615. {
  6616. if (g.ActiveId != 0)
  6617. {
  6618. ClearActiveID();
  6619. }
  6620. else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
  6621. {
  6622. // Exit child window
  6623. ImGuiWindow* child_window = g.NavWindow;
  6624. ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
  6625. IM_ASSERT(child_window->ChildId != 0);
  6626. FocusWindow(parent_window);
  6627. SetNavID(child_window->ChildId, 0);
  6628. g.NavIdIsAlive = false;
  6629. if (g.NavDisableMouseHover)
  6630. g.NavMousePosDirty = true;
  6631. }
  6632. else if (g.OpenPopupStack.Size > 0)
  6633. {
  6634. // Close open popup/menu
  6635. if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
  6636. ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
  6637. }
  6638. else if (g.NavLayer != 0)
  6639. {
  6640. // Leave the "menu" layer
  6641. NavRestoreLayer(ImGuiNavLayer_Main);
  6642. }
  6643. else
  6644. {
  6645. // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
  6646. if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
  6647. g.NavWindow->NavLastIds[0] = 0;
  6648. g.NavId = 0;
  6649. }
  6650. }
  6651. // Process manual activation request
  6652. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
  6653. if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  6654. {
  6655. bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
  6656. bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
  6657. if (g.ActiveId == 0 && activate_pressed)
  6658. g.NavActivateId = g.NavId;
  6659. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
  6660. g.NavActivateDownId = g.NavId;
  6661. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
  6662. g.NavActivatePressedId = g.NavId;
  6663. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
  6664. g.NavInputId = g.NavId;
  6665. }
  6666. if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  6667. g.NavDisableHighlight = true;
  6668. if (g.NavActivateId != 0)
  6669. IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
  6670. g.NavMoveRequest = false;
  6671. // Process programmatic activation request
  6672. if (g.NavNextActivateId != 0)
  6673. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
  6674. g.NavNextActivateId = 0;
  6675. // Initiate directional inputs request
  6676. const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
  6677. if (g.NavMoveRequestForward == ImGuiNavForward_None)
  6678. {
  6679. g.NavMoveDir = ImGuiDir_None;
  6680. g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
  6681. if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  6682. {
  6683. if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
  6684. if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
  6685. if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
  6686. if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
  6687. }
  6688. g.NavMoveClipDir = g.NavMoveDir;
  6689. }
  6690. else
  6691. {
  6692. // 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)
  6693. // (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
  6694. IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
  6695. IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
  6696. g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
  6697. }
  6698. // Update PageUp/PageDown scroll
  6699. float nav_scoring_rect_offset_y = 0.0f;
  6700. if (nav_keyboard_active)
  6701. nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags);
  6702. // If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
  6703. if (g.NavMoveDir != ImGuiDir_None)
  6704. {
  6705. g.NavMoveRequest = true;
  6706. g.NavMoveDirLast = g.NavMoveDir;
  6707. }
  6708. if (g.NavMoveRequest && g.NavId == 0)
  6709. {
  6710. g.NavInitRequest = g.NavInitRequestFromMove = true;
  6711. g.NavInitResultId = 0;
  6712. g.NavDisableHighlight = false;
  6713. }
  6714. NavUpdateAnyRequestFlag();
  6715. // Scrolling
  6716. if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
  6717. {
  6718. // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
  6719. ImGuiWindow* window = g.NavWindow;
  6720. const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
  6721. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
  6722. {
  6723. if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
  6724. SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
  6725. if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
  6726. SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
  6727. }
  6728. // *Normal* Manual scroll with NavScrollXXX keys
  6729. // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
  6730. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
  6731. if (scroll_dir.x != 0.0f && window->ScrollbarX)
  6732. {
  6733. SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
  6734. g.NavMoveFromClampedRefRect = true;
  6735. }
  6736. if (scroll_dir.y != 0.0f)
  6737. {
  6738. SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
  6739. g.NavMoveFromClampedRefRect = true;
  6740. }
  6741. }
  6742. // Reset search results
  6743. g.NavMoveResultLocal.Clear();
  6744. g.NavMoveResultLocalVisibleSet.Clear();
  6745. g.NavMoveResultOther.Clear();
  6746. // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
  6747. if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
  6748. {
  6749. ImGuiWindow* window = g.NavWindow;
  6750. ImRect window_rect_rel(window->InnerMainRect.Min - window->Pos - ImVec2(1,1), window->InnerMainRect.Max - window->Pos + ImVec2(1,1));
  6751. if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
  6752. {
  6753. float pad = window->CalcFontSize() * 0.5f;
  6754. 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
  6755. window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
  6756. g.NavId = 0;
  6757. }
  6758. g.NavMoveFromClampedRefRect = false;
  6759. }
  6760. // 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)
  6761. ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
  6762. g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
  6763. g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
  6764. g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
  6765. g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
  6766. IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
  6767. //g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
  6768. g.NavScoringCount = 0;
  6769. #if IMGUI_DEBUG_NAV_RECTS
  6770. if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) GetOverlayDrawList(g.NavWindow)->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
  6771. if (g.NavWindow) { 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); GetOverlayDrawList(g.NavWindow)->AddCircleFilled(p, 3.0f, col); GetOverlayDrawList(g.NavWindow)->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
  6772. #endif
  6773. }
  6774. // Apply result from previous frame navigation directional move request
  6775. static void ImGui::NavUpdateMoveResult()
  6776. {
  6777. ImGuiContext& g = *GImGui;
  6778. if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
  6779. {
  6780. // 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)
  6781. if (g.NavId != 0)
  6782. {
  6783. g.NavDisableHighlight = false;
  6784. g.NavDisableMouseHover = true;
  6785. }
  6786. return;
  6787. }
  6788. // Select which result to use
  6789. ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  6790. // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
  6791. if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
  6792. if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
  6793. result = &g.NavMoveResultLocalVisibleSet;
  6794. // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
  6795. if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
  6796. if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
  6797. result = &g.NavMoveResultOther;
  6798. IM_ASSERT(g.NavWindow && result->Window);
  6799. // Scroll to keep newly navigated item fully into view.
  6800. if (g.NavLayer == 0)
  6801. {
  6802. ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
  6803. NavScrollToBringItemIntoView(result->Window, rect_abs);
  6804. // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate()
  6805. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false);
  6806. ImVec2 delta_scroll = result->Window->Scroll - next_scroll;
  6807. result->RectRel.Translate(delta_scroll);
  6808. // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy).
  6809. if (result->Window->Flags & ImGuiWindowFlags_ChildWindow)
  6810. NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll));
  6811. }
  6812. ClearActiveID();
  6813. g.NavWindow = result->Window;
  6814. SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
  6815. g.NavJustMovedToId = result->ID;
  6816. g.NavMoveFromClampedRefRect = false;
  6817. }
  6818. static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags)
  6819. {
  6820. ImGuiContext& g = *GImGui;
  6821. if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0)
  6822. {
  6823. ImGuiWindow* window = g.NavWindow;
  6824. bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up));
  6825. bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down));
  6826. if ((page_up_held && !page_down_held) || (page_down_held && !page_up_held))
  6827. {
  6828. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
  6829. {
  6830. // Fallback manual-scroll when window has no navigable item
  6831. if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
  6832. SetWindowScrollY(window, window->Scroll.y - window->InnerClipRect.GetHeight());
  6833. else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
  6834. SetWindowScrollY(window, window->Scroll.y + window->InnerClipRect.GetHeight());
  6835. }
  6836. else
  6837. {
  6838. const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
  6839. const float page_offset_y = ImMax(0.0f, window->InnerClipRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
  6840. float nav_scoring_rect_offset_y = 0.0f;
  6841. if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
  6842. {
  6843. nav_scoring_rect_offset_y = -page_offset_y;
  6844. g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
  6845. g.NavMoveClipDir = ImGuiDir_Up;
  6846. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  6847. }
  6848. else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
  6849. {
  6850. nav_scoring_rect_offset_y = +page_offset_y;
  6851. g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
  6852. g.NavMoveClipDir = ImGuiDir_Down;
  6853. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  6854. }
  6855. return nav_scoring_rect_offset_y;
  6856. }
  6857. }
  6858. }
  6859. return 0.0f;
  6860. }
  6861. static int FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
  6862. {
  6863. ImGuiContext& g = *GImGui;
  6864. for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
  6865. if (g.WindowsFocusOrder[i] == window)
  6866. return i;
  6867. return -1;
  6868. }
  6869. static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
  6870. {
  6871. ImGuiContext& g = *GImGui;
  6872. for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
  6873. if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
  6874. return g.WindowsFocusOrder[i];
  6875. return NULL;
  6876. }
  6877. static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
  6878. {
  6879. ImGuiContext& g = *GImGui;
  6880. IM_ASSERT(g.NavWindowingTarget);
  6881. if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
  6882. return;
  6883. const int i_current = FindWindowFocusIndex(g.NavWindowingTarget);
  6884. ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
  6885. if (!window_target)
  6886. window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
  6887. if (window_target) // Don't reset windowing target if there's a single window in the list
  6888. g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
  6889. g.NavWindowingToggleLayer = false;
  6890. }
  6891. // Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer)
  6892. static void ImGui::NavUpdateWindowing()
  6893. {
  6894. ImGuiContext& g = *GImGui;
  6895. ImGuiWindow* apply_focus_window = NULL;
  6896. bool apply_toggle_layer = false;
  6897. ImGuiWindow* modal_window = GetFrontMostPopupModal();
  6898. if (modal_window != NULL)
  6899. {
  6900. g.NavWindowingTarget = NULL;
  6901. return;
  6902. }
  6903. // Fade out
  6904. if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
  6905. {
  6906. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
  6907. if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
  6908. g.NavWindowingTargetAnim = NULL;
  6909. }
  6910. // Start CTRL-TAB or Square+L/R window selection
  6911. bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
  6912. bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
  6913. if (start_windowing_with_gamepad || start_windowing_with_keyboard)
  6914. if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
  6915. {
  6916. g.NavWindowingTarget = g.NavWindowingTargetAnim = window;
  6917. g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
  6918. g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
  6919. g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
  6920. }
  6921. // Gamepad update
  6922. g.NavWindowingTimer += g.IO.DeltaTime;
  6923. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
  6924. {
  6925. // 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
  6926. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
  6927. // Select window to focus
  6928. const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
  6929. if (focus_change_dir != 0)
  6930. {
  6931. NavUpdateWindowingHighlightWindow(focus_change_dir);
  6932. g.NavWindowingHighlightAlpha = 1.0f;
  6933. }
  6934. // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most)
  6935. if (!IsNavInputDown(ImGuiNavInput_Menu))
  6936. {
  6937. g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
  6938. if (g.NavWindowingToggleLayer && g.NavWindow)
  6939. apply_toggle_layer = true;
  6940. else if (!g.NavWindowingToggleLayer)
  6941. apply_focus_window = g.NavWindowingTarget;
  6942. g.NavWindowingTarget = NULL;
  6943. }
  6944. }
  6945. // Keyboard: Focus
  6946. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
  6947. {
  6948. // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
  6949. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
  6950. if (IsKeyPressedMap(ImGuiKey_Tab, true))
  6951. NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
  6952. if (!g.IO.KeyCtrl)
  6953. apply_focus_window = g.NavWindowingTarget;
  6954. }
  6955. // Keyboard: Press and Release ALT to toggle menu layer
  6956. // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
  6957. if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
  6958. if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
  6959. apply_toggle_layer = true;
  6960. // Move window
  6961. if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
  6962. {
  6963. ImVec2 move_delta;
  6964. if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
  6965. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  6966. if (g.NavInputSource == ImGuiInputSource_NavGamepad)
  6967. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
  6968. if (move_delta.x != 0.0f || move_delta.y != 0.0f)
  6969. {
  6970. const float NAV_MOVE_SPEED = 800.0f;
  6971. const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
  6972. g.NavWindowingTarget->RootWindow->Pos += move_delta * move_speed;
  6973. g.NavDisableMouseHover = true;
  6974. MarkIniSettingsDirty(g.NavWindowingTarget);
  6975. }
  6976. }
  6977. // Apply final focus
  6978. if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
  6979. {
  6980. g.NavDisableHighlight = false;
  6981. g.NavDisableMouseHover = true;
  6982. apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
  6983. ClosePopupsOverWindow(apply_focus_window);
  6984. FocusWindow(apply_focus_window);
  6985. if (apply_focus_window->NavLastIds[0] == 0)
  6986. NavInitWindow(apply_focus_window, false);
  6987. // If the window only has a menu layer, select it directly
  6988. if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
  6989. g.NavLayer = ImGuiNavLayer_Menu;
  6990. }
  6991. if (apply_focus_window)
  6992. g.NavWindowingTarget = NULL;
  6993. // Apply menu/layer toggle
  6994. if (apply_toggle_layer && g.NavWindow)
  6995. {
  6996. // Move to parent menu if necessary
  6997. ImGuiWindow* new_nav_window = g.NavWindow;
  6998. while ((new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0
  6999. && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
  7000. && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  7001. new_nav_window = new_nav_window->ParentWindow;
  7002. if (new_nav_window != g.NavWindow)
  7003. {
  7004. ImGuiWindow* old_nav_window = g.NavWindow;
  7005. FocusWindow(new_nav_window);
  7006. new_nav_window->NavLastChildNavWindow = old_nav_window;
  7007. }
  7008. g.NavDisableHighlight = false;
  7009. g.NavDisableMouseHover = true;
  7010. NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main);
  7011. }
  7012. }
  7013. // Window has already passed the IsWindowNavFocusable()
  7014. static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
  7015. {
  7016. if (window->Flags & ImGuiWindowFlags_Popup)
  7017. return "(Popup)";
  7018. if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
  7019. return "(Main menu bar)";
  7020. return "(Untitled)";
  7021. }
  7022. // Overlay displayed when using CTRL+TAB. Called by EndFrame().
  7023. void ImGui::NavUpdateWindowingList()
  7024. {
  7025. ImGuiContext& g = *GImGui;
  7026. IM_ASSERT(g.NavWindowingTarget != NULL);
  7027. if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
  7028. return;
  7029. if (g.NavWindowingList == NULL)
  7030. g.NavWindowingList = FindWindowByName("###NavWindowingList");
  7031. SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
  7032. SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
  7033. PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
  7034. Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
  7035. for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
  7036. {
  7037. ImGuiWindow* window = g.WindowsFocusOrder[n];
  7038. if (!IsWindowNavFocusable(window))
  7039. continue;
  7040. const char* label = window->Name;
  7041. if (label == FindRenderedTextEnd(label))
  7042. label = GetFallbackWindowNameForWindowingList(window);
  7043. Selectable(label, g.NavWindowingTarget == window);
  7044. }
  7045. End();
  7046. PopStyleVar();
  7047. }
  7048. //-----------------------------------------------------------------------------
  7049. // [SECTION] COLUMNS
  7050. // In the current version, Columns are very weak. Needs to be replaced with a more full-featured system.
  7051. //-----------------------------------------------------------------------------
  7052. void ImGui::NextColumn()
  7053. {
  7054. ImGuiWindow* window = GetCurrentWindow();
  7055. if (window->SkipItems || window->DC.ColumnsSet == NULL)
  7056. return;
  7057. ImGuiContext& g = *GImGui;
  7058. PopItemWidth();
  7059. PopClipRect();
  7060. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  7061. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  7062. if (++columns->Current < columns->Count)
  7063. {
  7064. // Columns 1+ cancel out IndentX
  7065. window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x;
  7066. window->DrawList->ChannelsSetCurrent(columns->Current);
  7067. }
  7068. else
  7069. {
  7070. window->DC.ColumnsOffset.x = 0.0f;
  7071. window->DrawList->ChannelsSetCurrent(0);
  7072. columns->Current = 0;
  7073. columns->LineMinY = columns->LineMaxY;
  7074. }
  7075. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  7076. window->DC.CursorPos.y = columns->LineMinY;
  7077. window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
  7078. window->DC.CurrentLineTextBaseOffset = 0.0f;
  7079. PushColumnClipRect();
  7080. PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
  7081. }
  7082. int ImGui::GetColumnIndex()
  7083. {
  7084. ImGuiWindow* window = GetCurrentWindowRead();
  7085. return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0;
  7086. }
  7087. int ImGui::GetColumnsCount()
  7088. {
  7089. ImGuiWindow* window = GetCurrentWindowRead();
  7090. return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1;
  7091. }
  7092. static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm)
  7093. {
  7094. return offset_norm * (columns->MaxX - columns->MinX);
  7095. }
  7096. static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset)
  7097. {
  7098. return offset / (columns->MaxX - columns->MinX);
  7099. }
  7100. static inline float GetColumnsRectHalfWidth() { return 4.0f; }
  7101. static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
  7102. {
  7103. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  7104. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  7105. ImGuiContext& g = *GImGui;
  7106. ImGuiWindow* window = g.CurrentWindow;
  7107. IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
  7108. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
  7109. float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
  7110. x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
  7111. if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
  7112. x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
  7113. return x;
  7114. }
  7115. float ImGui::GetColumnOffset(int column_index)
  7116. {
  7117. ImGuiWindow* window = GetCurrentWindowRead();
  7118. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  7119. IM_ASSERT(columns != NULL);
  7120. if (column_index < 0)
  7121. column_index = columns->Current;
  7122. IM_ASSERT(column_index < columns->Columns.Size);
  7123. const float t = columns->Columns[column_index].OffsetNorm;
  7124. const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
  7125. return x_offset;
  7126. }
  7127. static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false)
  7128. {
  7129. if (column_index < 0)
  7130. column_index = columns->Current;
  7131. float offset_norm;
  7132. if (before_resize)
  7133. offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
  7134. else
  7135. offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
  7136. return OffsetNormToPixels(columns, offset_norm);
  7137. }
  7138. float ImGui::GetColumnWidth(int column_index)
  7139. {
  7140. ImGuiWindow* window = GetCurrentWindowRead();
  7141. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  7142. IM_ASSERT(columns != NULL);
  7143. if (column_index < 0)
  7144. column_index = columns->Current;
  7145. return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
  7146. }
  7147. void ImGui::SetColumnOffset(int column_index, float offset)
  7148. {
  7149. ImGuiContext& g = *GImGui;
  7150. ImGuiWindow* window = g.CurrentWindow;
  7151. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  7152. IM_ASSERT(columns != NULL);
  7153. if (column_index < 0)
  7154. column_index = columns->Current;
  7155. IM_ASSERT(column_index < columns->Columns.Size);
  7156. const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
  7157. const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
  7158. if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
  7159. offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
  7160. columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX);
  7161. if (preserve_width)
  7162. SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
  7163. }
  7164. void ImGui::SetColumnWidth(int column_index, float width)
  7165. {
  7166. ImGuiWindow* window = GetCurrentWindowRead();
  7167. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  7168. IM_ASSERT(columns != NULL);
  7169. if (column_index < 0)
  7170. column_index = columns->Current;
  7171. SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
  7172. }
  7173. void ImGui::PushColumnClipRect(int column_index)
  7174. {
  7175. ImGuiWindow* window = GetCurrentWindowRead();
  7176. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  7177. if (column_index < 0)
  7178. column_index = columns->Current;
  7179. PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false);
  7180. }
  7181. static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id)
  7182. {
  7183. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  7184. if (window->ColumnsStorage[n].ID == id)
  7185. return &window->ColumnsStorage[n];
  7186. window->ColumnsStorage.push_back(ImGuiColumnsSet());
  7187. ImGuiColumnsSet* columns = &window->ColumnsStorage.back();
  7188. columns->ID = id;
  7189. return columns;
  7190. }
  7191. void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
  7192. {
  7193. ImGuiContext& g = *GImGui;
  7194. ImGuiWindow* window = GetCurrentWindow();
  7195. IM_ASSERT(columns_count > 1);
  7196. IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported
  7197. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  7198. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  7199. PushID(0x11223347 + (str_id ? 0 : columns_count));
  7200. ImGuiID id = window->GetID(str_id ? str_id : "columns");
  7201. PopID();
  7202. // Acquire storage for the columns set
  7203. ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id);
  7204. IM_ASSERT(columns->ID == id);
  7205. columns->Current = 0;
  7206. columns->Count = columns_count;
  7207. columns->Flags = flags;
  7208. window->DC.ColumnsSet = columns;
  7209. // Set state for first column
  7210. const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x);
  7211. columns->MinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range
  7212. columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f);
  7213. columns->StartPosY = window->DC.CursorPos.y;
  7214. columns->StartMaxPosX = window->DC.CursorMaxPos.x;
  7215. columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
  7216. window->DC.ColumnsOffset.x = 0.0f;
  7217. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  7218. // Clear data if columns count changed
  7219. if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
  7220. columns->Columns.resize(0);
  7221. // Initialize defaults
  7222. columns->IsFirstFrame = (columns->Columns.Size == 0);
  7223. if (columns->Columns.Size == 0)
  7224. {
  7225. columns->Columns.reserve(columns_count + 1);
  7226. for (int n = 0; n < columns_count + 1; n++)
  7227. {
  7228. ImGuiColumnData column;
  7229. column.OffsetNorm = n / (float)columns_count;
  7230. columns->Columns.push_back(column);
  7231. }
  7232. }
  7233. for (int n = 0; n < columns_count; n++)
  7234. {
  7235. // Compute clipping rectangle
  7236. ImGuiColumnData* column = &columns->Columns[n];
  7237. float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
  7238. float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
  7239. column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
  7240. column->ClipRect.ClipWith(window->ClipRect);
  7241. }
  7242. window->DrawList->ChannelsSplit(columns->Count);
  7243. PushColumnClipRect();
  7244. PushItemWidth(GetColumnWidth() * 0.65f);
  7245. }
  7246. void ImGui::EndColumns()
  7247. {
  7248. ImGuiContext& g = *GImGui;
  7249. ImGuiWindow* window = GetCurrentWindow();
  7250. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  7251. IM_ASSERT(columns != NULL);
  7252. PopItemWidth();
  7253. PopClipRect();
  7254. window->DrawList->ChannelsMerge();
  7255. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  7256. window->DC.CursorPos.y = columns->LineMaxY;
  7257. if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
  7258. window->DC.CursorMaxPos.x = columns->StartMaxPosX; // Restore cursor max pos, as columns don't grow parent
  7259. // Draw columns borders and handle resize
  7260. bool is_being_resized = false;
  7261. if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
  7262. {
  7263. const float y1 = columns->StartPosY;
  7264. const float y2 = window->DC.CursorPos.y;
  7265. int dragging_column = -1;
  7266. for (int n = 1; n < columns->Count; n++)
  7267. {
  7268. float x = window->Pos.x + GetColumnOffset(n);
  7269. const ImGuiID column_id = columns->ID + ImGuiID(n);
  7270. const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction
  7271. const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2));
  7272. KeepAliveID(column_id);
  7273. if (IsClippedEx(column_rect, column_id, false))
  7274. continue;
  7275. bool hovered = false, held = false;
  7276. if (!(columns->Flags & ImGuiColumnsFlags_NoResize))
  7277. {
  7278. ButtonBehavior(column_rect, column_id, &hovered, &held);
  7279. if (hovered || held)
  7280. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  7281. if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize))
  7282. dragging_column = n;
  7283. }
  7284. // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.)
  7285. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  7286. const float xi = (float)(int)x;
  7287. window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col);
  7288. }
  7289. // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
  7290. if (dragging_column != -1)
  7291. {
  7292. if (!columns->IsBeingResized)
  7293. for (int n = 0; n < columns->Count + 1; n++)
  7294. columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
  7295. columns->IsBeingResized = is_being_resized = true;
  7296. float x = GetDraggedColumnOffset(columns, dragging_column);
  7297. SetColumnOffset(dragging_column, x);
  7298. }
  7299. }
  7300. columns->IsBeingResized = is_being_resized;
  7301. window->DC.ColumnsSet = NULL;
  7302. window->DC.ColumnsOffset.x = 0.0f;
  7303. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  7304. }
  7305. // [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
  7306. void ImGui::Columns(int columns_count, const char* id, bool border)
  7307. {
  7308. ImGuiWindow* window = GetCurrentWindow();
  7309. IM_ASSERT(columns_count >= 1);
  7310. ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
  7311. //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
  7312. if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count == columns_count && window->DC.ColumnsSet->Flags == flags)
  7313. return;
  7314. if (window->DC.ColumnsSet != NULL)
  7315. EndColumns();
  7316. if (columns_count != 1)
  7317. BeginColumns(id, columns_count, flags);
  7318. }
  7319. //-----------------------------------------------------------------------------
  7320. // [SECTION] DRAG AND DROP
  7321. //-----------------------------------------------------------------------------
  7322. void ImGui::ClearDragDrop()
  7323. {
  7324. ImGuiContext& g = *GImGui;
  7325. g.DragDropActive = false;
  7326. g.DragDropPayload.Clear();
  7327. g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
  7328. g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
  7329. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  7330. g.DragDropAcceptFrameCount = -1;
  7331. g.DragDropPayloadBufHeap.clear();
  7332. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  7333. }
  7334. // Call when current ID is active.
  7335. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
  7336. bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
  7337. {
  7338. ImGuiContext& g = *GImGui;
  7339. ImGuiWindow* window = g.CurrentWindow;
  7340. bool source_drag_active = false;
  7341. ImGuiID source_id = 0;
  7342. ImGuiID source_parent_id = 0;
  7343. int mouse_button = 0;
  7344. if (!(flags & ImGuiDragDropFlags_SourceExtern))
  7345. {
  7346. source_id = window->DC.LastItemId;
  7347. if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
  7348. return false;
  7349. if (g.IO.MouseDown[mouse_button] == false)
  7350. return false;
  7351. if (source_id == 0)
  7352. {
  7353. // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
  7354. // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
  7355. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
  7356. {
  7357. IM_ASSERT(0);
  7358. return false;
  7359. }
  7360. // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
  7361. // We build a throwaway ID based on current ID stack + relative AABB of items in window.
  7362. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
  7363. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
  7364. bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0;
  7365. if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
  7366. return false;
  7367. source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
  7368. if (is_hovered)
  7369. SetHoveredID(source_id);
  7370. if (is_hovered && g.IO.MouseClicked[mouse_button])
  7371. {
  7372. SetActiveID(source_id, window);
  7373. FocusWindow(window);
  7374. }
  7375. if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
  7376. g.ActiveIdAllowOverlap = is_hovered;
  7377. }
  7378. else
  7379. {
  7380. g.ActiveIdAllowOverlap = false;
  7381. }
  7382. if (g.ActiveId != source_id)
  7383. return false;
  7384. source_parent_id = window->IDStack.back();
  7385. source_drag_active = IsMouseDragging(mouse_button);
  7386. }
  7387. else
  7388. {
  7389. window = NULL;
  7390. source_id = ImHash("#SourceExtern", 0);
  7391. source_drag_active = true;
  7392. }
  7393. if (source_drag_active)
  7394. {
  7395. if (!g.DragDropActive)
  7396. {
  7397. IM_ASSERT(source_id != 0);
  7398. ClearDragDrop();
  7399. ImGuiPayload& payload = g.DragDropPayload;
  7400. payload.SourceId = source_id;
  7401. payload.SourceParentId = source_parent_id;
  7402. g.DragDropActive = true;
  7403. g.DragDropSourceFlags = flags;
  7404. g.DragDropMouseButton = mouse_button;
  7405. }
  7406. g.DragDropSourceFrameCount = g.FrameCount;
  7407. g.DragDropWithinSourceOrTarget = true;
  7408. if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  7409. {
  7410. // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
  7411. // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
  7412. BeginTooltip();
  7413. if (g.DragDropActive && g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
  7414. {
  7415. ImGuiWindow* tooltip_window = g.CurrentWindow;
  7416. tooltip_window->SkipItems = true;
  7417. tooltip_window->HiddenFramesRegular = 1;
  7418. }
  7419. }
  7420. if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
  7421. window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
  7422. return true;
  7423. }
  7424. return false;
  7425. }
  7426. void ImGui::EndDragDropSource()
  7427. {
  7428. ImGuiContext& g = *GImGui;
  7429. IM_ASSERT(g.DragDropActive);
  7430. IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?");
  7431. if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  7432. EndTooltip();
  7433. // Discard the drag if have not called SetDragDropPayload()
  7434. if (g.DragDropPayload.DataFrameCount == -1)
  7435. ClearDragDrop();
  7436. g.DragDropWithinSourceOrTarget = false;
  7437. }
  7438. // Use 'cond' to choose to submit payload on drag start or every frame
  7439. bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
  7440. {
  7441. ImGuiContext& g = *GImGui;
  7442. ImGuiPayload& payload = g.DragDropPayload;
  7443. if (cond == 0)
  7444. cond = ImGuiCond_Always;
  7445. IM_ASSERT(type != NULL);
  7446. IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
  7447. IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
  7448. IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
  7449. IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
  7450. if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
  7451. {
  7452. // Copy payload
  7453. ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
  7454. g.DragDropPayloadBufHeap.resize(0);
  7455. if (data_size > sizeof(g.DragDropPayloadBufLocal))
  7456. {
  7457. // Store in heap
  7458. g.DragDropPayloadBufHeap.resize((int)data_size);
  7459. payload.Data = g.DragDropPayloadBufHeap.Data;
  7460. memcpy(payload.Data, data, data_size);
  7461. }
  7462. else if (data_size > 0)
  7463. {
  7464. // Store locally
  7465. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  7466. payload.Data = g.DragDropPayloadBufLocal;
  7467. memcpy(payload.Data, data, data_size);
  7468. }
  7469. else
  7470. {
  7471. payload.Data = NULL;
  7472. }
  7473. payload.DataSize = (int)data_size;
  7474. }
  7475. payload.DataFrameCount = g.FrameCount;
  7476. return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
  7477. }
  7478. bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
  7479. {
  7480. ImGuiContext& g = *GImGui;
  7481. if (!g.DragDropActive)
  7482. return false;
  7483. ImGuiWindow* window = g.CurrentWindow;
  7484. if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
  7485. return false;
  7486. IM_ASSERT(id != 0);
  7487. if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
  7488. return false;
  7489. if (window->SkipItems)
  7490. return false;
  7491. IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
  7492. g.DragDropTargetRect = bb;
  7493. g.DragDropTargetId = id;
  7494. g.DragDropWithinSourceOrTarget = true;
  7495. return true;
  7496. }
  7497. // We don't use BeginDragDropTargetCustom() and duplicate its code because:
  7498. // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
  7499. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
  7500. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
  7501. bool ImGui::BeginDragDropTarget()
  7502. {
  7503. ImGuiContext& g = *GImGui;
  7504. if (!g.DragDropActive)
  7505. return false;
  7506. ImGuiWindow* window = g.CurrentWindow;
  7507. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  7508. return false;
  7509. if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
  7510. return false;
  7511. const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
  7512. ImGuiID id = window->DC.LastItemId;
  7513. if (id == 0)
  7514. id = window->GetIDFromRectangle(display_rect);
  7515. if (g.DragDropPayload.SourceId == id)
  7516. return false;
  7517. IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
  7518. g.DragDropTargetRect = display_rect;
  7519. g.DragDropTargetId = id;
  7520. g.DragDropWithinSourceOrTarget = true;
  7521. return true;
  7522. }
  7523. bool ImGui::IsDragDropPayloadBeingAccepted()
  7524. {
  7525. ImGuiContext& g = *GImGui;
  7526. return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
  7527. }
  7528. const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
  7529. {
  7530. ImGuiContext& g = *GImGui;
  7531. ImGuiWindow* window = g.CurrentWindow;
  7532. ImGuiPayload& payload = g.DragDropPayload;
  7533. IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
  7534. IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
  7535. if (type != NULL && !payload.IsDataType(type))
  7536. return NULL;
  7537. // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
  7538. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
  7539. const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
  7540. ImRect r = g.DragDropTargetRect;
  7541. float r_surface = r.GetWidth() * r.GetHeight();
  7542. if (r_surface < g.DragDropAcceptIdCurrRectSurface)
  7543. {
  7544. g.DragDropAcceptFlags = flags;
  7545. g.DragDropAcceptIdCurr = g.DragDropTargetId;
  7546. g.DragDropAcceptIdCurrRectSurface = r_surface;
  7547. }
  7548. // Render default drop visuals
  7549. payload.Preview = was_accepted_previously;
  7550. flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
  7551. if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
  7552. {
  7553. // FIXME-DRAG: Settle on a proper default visuals for drop target.
  7554. r.Expand(3.5f);
  7555. bool push_clip_rect = !window->ClipRect.Contains(r);
  7556. if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
  7557. window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
  7558. if (push_clip_rect) window->DrawList->PopClipRect();
  7559. }
  7560. g.DragDropAcceptFrameCount = g.FrameCount;
  7561. 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()
  7562. if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
  7563. return NULL;
  7564. return &payload;
  7565. }
  7566. const ImGuiPayload* ImGui::GetDragDropPayload()
  7567. {
  7568. ImGuiContext& g = *GImGui;
  7569. return g.DragDropActive ? &g.DragDropPayload : NULL;
  7570. }
  7571. // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
  7572. void ImGui::EndDragDropTarget()
  7573. {
  7574. ImGuiContext& g = *GImGui;
  7575. IM_ASSERT(g.DragDropActive);
  7576. IM_ASSERT(g.DragDropWithinSourceOrTarget);
  7577. g.DragDropWithinSourceOrTarget = false;
  7578. }
  7579. //-----------------------------------------------------------------------------
  7580. // [SECTION] DOCKING
  7581. //-----------------------------------------------------------------------------
  7582. // (this section is filled in the 'docking' branch)
  7583. //-----------------------------------------------------------------------------
  7584. // [SECTION] LOGGING/CAPTURING
  7585. //-----------------------------------------------------------------------------
  7586. // Pass text data straight to log (without being displayed)
  7587. void ImGui::LogText(const char* fmt, ...)
  7588. {
  7589. ImGuiContext& g = *GImGui;
  7590. if (!g.LogEnabled)
  7591. return;
  7592. va_list args;
  7593. va_start(args, fmt);
  7594. if (g.LogFile)
  7595. vfprintf(g.LogFile, fmt, args);
  7596. else
  7597. g.LogClipboard.appendfv(fmt, args);
  7598. va_end(args);
  7599. }
  7600. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  7601. // We split text into individual lines to add current tree level padding
  7602. void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
  7603. {
  7604. ImGuiContext& g = *GImGui;
  7605. ImGuiWindow* window = g.CurrentWindow;
  7606. if (!text_end)
  7607. text_end = FindRenderedTextEnd(text, text_end);
  7608. const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1);
  7609. if (ref_pos)
  7610. window->DC.LogLinePosY = ref_pos->y;
  7611. const char* text_remaining = text;
  7612. if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
  7613. g.LogStartDepth = window->DC.TreeDepth;
  7614. const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
  7615. for (;;)
  7616. {
  7617. // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
  7618. const char* line_start = text_remaining;
  7619. const char* line_end = ImStreolRange(line_start, text_end);
  7620. const bool is_first_line = (line_start == text);
  7621. const bool is_last_line = (line_end == text_end);
  7622. if (!is_last_line || (line_start != line_end))
  7623. {
  7624. const int char_count = (int)(line_end - line_start);
  7625. if (log_new_line || !is_first_line)
  7626. LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, line_start);
  7627. else
  7628. LogText(" %.*s", char_count, line_start);
  7629. }
  7630. if (is_last_line)
  7631. break;
  7632. text_remaining = line_end + 1;
  7633. }
  7634. }
  7635. // Start logging ImGui output to TTY
  7636. void ImGui::LogToTTY(int max_depth)
  7637. {
  7638. ImGuiContext& g = *GImGui;
  7639. if (g.LogEnabled)
  7640. return;
  7641. ImGuiWindow* window = g.CurrentWindow;
  7642. IM_ASSERT(g.LogFile == NULL);
  7643. g.LogFile = stdout;
  7644. g.LogEnabled = true;
  7645. g.LogStartDepth = window->DC.TreeDepth;
  7646. if (max_depth >= 0)
  7647. g.LogAutoExpandMaxDepth = max_depth;
  7648. }
  7649. // Start logging ImGui output to given file
  7650. void ImGui::LogToFile(int max_depth, const char* filename)
  7651. {
  7652. ImGuiContext& g = *GImGui;
  7653. if (g.LogEnabled)
  7654. return;
  7655. ImGuiWindow* window = g.CurrentWindow;
  7656. if (!filename)
  7657. {
  7658. filename = g.IO.LogFilename;
  7659. if (!filename)
  7660. return;
  7661. }
  7662. IM_ASSERT(g.LogFile == NULL);
  7663. g.LogFile = ImFileOpen(filename, "ab");
  7664. if (!g.LogFile)
  7665. {
  7666. IM_ASSERT(g.LogFile != NULL); // Consider this an error
  7667. return;
  7668. }
  7669. g.LogEnabled = true;
  7670. g.LogStartDepth = window->DC.TreeDepth;
  7671. if (max_depth >= 0)
  7672. g.LogAutoExpandMaxDepth = max_depth;
  7673. }
  7674. // Start logging ImGui output to clipboard
  7675. void ImGui::LogToClipboard(int max_depth)
  7676. {
  7677. ImGuiContext& g = *GImGui;
  7678. if (g.LogEnabled)
  7679. return;
  7680. ImGuiWindow* window = g.CurrentWindow;
  7681. IM_ASSERT(g.LogFile == NULL);
  7682. g.LogFile = NULL;
  7683. g.LogEnabled = true;
  7684. g.LogStartDepth = window->DC.TreeDepth;
  7685. if (max_depth >= 0)
  7686. g.LogAutoExpandMaxDepth = max_depth;
  7687. }
  7688. void ImGui::LogFinish()
  7689. {
  7690. ImGuiContext& g = *GImGui;
  7691. if (!g.LogEnabled)
  7692. return;
  7693. LogText(IM_NEWLINE);
  7694. if (g.LogFile != NULL)
  7695. {
  7696. if (g.LogFile == stdout)
  7697. fflush(g.LogFile);
  7698. else
  7699. fclose(g.LogFile);
  7700. g.LogFile = NULL;
  7701. }
  7702. if (g.LogClipboard.size() > 1)
  7703. {
  7704. SetClipboardText(g.LogClipboard.begin());
  7705. g.LogClipboard.clear();
  7706. }
  7707. g.LogEnabled = false;
  7708. }
  7709. // Helper to display logging buttons
  7710. void ImGui::LogButtons()
  7711. {
  7712. ImGuiContext& g = *GImGui;
  7713. PushID("LogButtons");
  7714. const bool log_to_tty = Button("Log To TTY"); SameLine();
  7715. const bool log_to_file = Button("Log To File"); SameLine();
  7716. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  7717. PushItemWidth(80.0f);
  7718. PushAllowKeyboardFocus(false);
  7719. SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
  7720. PopAllowKeyboardFocus();
  7721. PopItemWidth();
  7722. PopID();
  7723. // Start logging at the end of the function so that the buttons don't appear in the log
  7724. if (log_to_tty)
  7725. LogToTTY(g.LogAutoExpandMaxDepth);
  7726. if (log_to_file)
  7727. LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
  7728. if (log_to_clipboard)
  7729. LogToClipboard(g.LogAutoExpandMaxDepth);
  7730. }
  7731. //-----------------------------------------------------------------------------
  7732. // [SECTION] SETTINGS
  7733. //-----------------------------------------------------------------------------
  7734. void ImGui::MarkIniSettingsDirty()
  7735. {
  7736. ImGuiContext& g = *GImGui;
  7737. if (g.SettingsDirtyTimer <= 0.0f)
  7738. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  7739. }
  7740. void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
  7741. {
  7742. ImGuiContext& g = *GImGui;
  7743. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  7744. if (g.SettingsDirtyTimer <= 0.0f)
  7745. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  7746. }
  7747. ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
  7748. {
  7749. ImGuiContext& g = *GImGui;
  7750. g.SettingsWindows.push_back(ImGuiWindowSettings());
  7751. ImGuiWindowSettings* settings = &g.SettingsWindows.back();
  7752. settings->Name = ImStrdup(name);
  7753. settings->ID = ImHash(name, 0);
  7754. return settings;
  7755. }
  7756. ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
  7757. {
  7758. ImGuiContext& g = *GImGui;
  7759. for (int i = 0; i != g.SettingsWindows.Size; i++)
  7760. if (g.SettingsWindows[i].ID == id)
  7761. return &g.SettingsWindows[i];
  7762. return NULL;
  7763. }
  7764. void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
  7765. {
  7766. size_t file_data_size = 0;
  7767. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
  7768. if (!file_data)
  7769. return;
  7770. LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
  7771. ImGui::MemFree(file_data);
  7772. }
  7773. ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
  7774. {
  7775. ImGuiContext& g = *GImGui;
  7776. const ImGuiID type_hash = ImHash(type_name, 0, 0);
  7777. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  7778. if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
  7779. return &g.SettingsHandlers[handler_n];
  7780. return NULL;
  7781. }
  7782. // Zero-tolerance, no error reporting, cheap .ini parsing
  7783. void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
  7784. {
  7785. ImGuiContext& g = *GImGui;
  7786. IM_ASSERT(g.Initialized);
  7787. IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
  7788. // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
  7789. // 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..
  7790. if (ini_size == 0)
  7791. ini_size = strlen(ini_data);
  7792. char* buf = (char*)ImGui::MemAlloc(ini_size + 1);
  7793. char* buf_end = buf + ini_size;
  7794. memcpy(buf, ini_data, ini_size);
  7795. buf[ini_size] = 0;
  7796. void* entry_data = NULL;
  7797. ImGuiSettingsHandler* entry_handler = NULL;
  7798. char* line_end = NULL;
  7799. for (char* line = buf; line < buf_end; line = line_end + 1)
  7800. {
  7801. // Skip new lines markers, then find end of the line
  7802. while (*line == '\n' || *line == '\r')
  7803. line++;
  7804. line_end = line;
  7805. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  7806. line_end++;
  7807. line_end[0] = 0;
  7808. if (line[0] == ';')
  7809. continue;
  7810. if (line[0] == '[' && line_end > line && line_end[-1] == ']')
  7811. {
  7812. // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
  7813. line_end[-1] = 0;
  7814. const char* name_end = line_end - 1;
  7815. const char* type_start = line + 1;
  7816. char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']');
  7817. const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
  7818. if (!type_end || !name_start)
  7819. {
  7820. name_start = type_start; // Import legacy entries that have no type
  7821. type_start = "Window";
  7822. }
  7823. else
  7824. {
  7825. *type_end = 0; // Overwrite first ']'
  7826. name_start++; // Skip second '['
  7827. }
  7828. entry_handler = FindSettingsHandler(type_start);
  7829. entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
  7830. }
  7831. else if (entry_handler != NULL && entry_data != NULL)
  7832. {
  7833. // Let type handler parse the line
  7834. entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
  7835. }
  7836. }
  7837. ImGui::MemFree(buf);
  7838. g.SettingsLoaded = true;
  7839. }
  7840. void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
  7841. {
  7842. ImGuiContext& g = *GImGui;
  7843. g.SettingsDirtyTimer = 0.0f;
  7844. if (!ini_filename)
  7845. return;
  7846. size_t ini_data_size = 0;
  7847. const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
  7848. FILE* f = ImFileOpen(ini_filename, "wt");
  7849. if (!f)
  7850. return;
  7851. fwrite(ini_data, sizeof(char), ini_data_size, f);
  7852. fclose(f);
  7853. }
  7854. // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
  7855. const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
  7856. {
  7857. ImGuiContext& g = *GImGui;
  7858. g.SettingsDirtyTimer = 0.0f;
  7859. g.SettingsIniData.Buf.resize(0);
  7860. g.SettingsIniData.Buf.push_back(0);
  7861. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  7862. {
  7863. ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
  7864. handler->WriteAllFn(&g, handler, &g.SettingsIniData);
  7865. }
  7866. if (out_size)
  7867. *out_size = (size_t)g.SettingsIniData.size();
  7868. return g.SettingsIniData.c_str();
  7869. }
  7870. static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  7871. {
  7872. ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
  7873. if (!settings)
  7874. settings = ImGui::CreateNewWindowSettings(name);
  7875. return (void*)settings;
  7876. }
  7877. static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  7878. {
  7879. ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
  7880. float x, y;
  7881. int i;
  7882. if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y);
  7883. else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize);
  7884. else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
  7885. }
  7886. static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  7887. {
  7888. // Gather data from windows that were active during this session
  7889. // (if a window wasn't opened in this session we preserve its settings)
  7890. ImGuiContext& g = *imgui_ctx;
  7891. for (int i = 0; i != g.Windows.Size; i++)
  7892. {
  7893. ImGuiWindow* window = g.Windows[i];
  7894. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  7895. continue;
  7896. ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID);
  7897. if (!settings)
  7898. {
  7899. settings = ImGui::CreateNewWindowSettings(window->Name);
  7900. window->SettingsIdx = g.SettingsWindows.index_from_pointer(settings);
  7901. }
  7902. IM_ASSERT(settings->ID == window->ID);
  7903. settings->Pos = window->Pos;
  7904. settings->Size = window->SizeFull;
  7905. settings->Collapsed = window->Collapsed;
  7906. }
  7907. // Write to text buffer
  7908. buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
  7909. for (int i = 0; i != g.SettingsWindows.Size; i++)
  7910. {
  7911. const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
  7912. if (settings->Pos.x == FLT_MAX)
  7913. continue;
  7914. const char* name = settings->Name;
  7915. if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  7916. name = p;
  7917. buf->appendf("[%s][%s]\n", handler->TypeName, name);
  7918. buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
  7919. buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
  7920. buf->appendf("Collapsed=%d\n", settings->Collapsed);
  7921. buf->appendf("\n");
  7922. }
  7923. }
  7924. //-----------------------------------------------------------------------------
  7925. // [SECTION] PLATFORM DEPENDENT HELPERS
  7926. //-----------------------------------------------------------------------------
  7927. #if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
  7928. #ifndef WIN32_LEAN_AND_MEAN
  7929. #define WIN32_LEAN_AND_MEAN
  7930. #endif
  7931. #ifndef __MINGW32__
  7932. #include <Windows.h>
  7933. #else
  7934. #include <windows.h>
  7935. #endif
  7936. #endif
  7937. // Win32 API clipboard implementation
  7938. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
  7939. #ifdef _MSC_VER
  7940. #pragma comment(lib, "user32")
  7941. #endif
  7942. static const char* GetClipboardTextFn_DefaultImpl(void*)
  7943. {
  7944. static ImVector<char> buf_local;
  7945. buf_local.clear();
  7946. if (!::OpenClipboard(NULL))
  7947. return NULL;
  7948. HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
  7949. if (wbuf_handle == NULL)
  7950. {
  7951. ::CloseClipboard();
  7952. return NULL;
  7953. }
  7954. if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle))
  7955. {
  7956. int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
  7957. buf_local.resize(buf_len);
  7958. ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
  7959. }
  7960. ::GlobalUnlock(wbuf_handle);
  7961. ::CloseClipboard();
  7962. return buf_local.Data;
  7963. }
  7964. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  7965. {
  7966. if (!::OpenClipboard(NULL))
  7967. return;
  7968. const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
  7969. HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
  7970. if (wbuf_handle == NULL)
  7971. {
  7972. ::CloseClipboard();
  7973. return;
  7974. }
  7975. ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle);
  7976. ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
  7977. ::GlobalUnlock(wbuf_handle);
  7978. ::EmptyClipboard();
  7979. if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
  7980. ::GlobalFree(wbuf_handle);
  7981. ::CloseClipboard();
  7982. }
  7983. #else
  7984. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  7985. static const char* GetClipboardTextFn_DefaultImpl(void*)
  7986. {
  7987. ImGuiContext& g = *GImGui;
  7988. return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
  7989. }
  7990. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  7991. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  7992. {
  7993. ImGuiContext& g = *GImGui;
  7994. g.PrivateClipboard.clear();
  7995. const char* text_end = text + strlen(text);
  7996. g.PrivateClipboard.resize((int)(text_end - text) + 1);
  7997. memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
  7998. g.PrivateClipboard[(int)(text_end - text)] = 0;
  7999. }
  8000. #endif
  8001. // Win32 API IME support (for Asian languages, etc.)
  8002. #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  8003. #include <imm.h>
  8004. #ifdef _MSC_VER
  8005. #pragma comment(lib, "imm32")
  8006. #endif
  8007. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
  8008. {
  8009. // Notify OS Input Method Editor of text input position
  8010. if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
  8011. if (HIMC himc = ::ImmGetContext(hwnd))
  8012. {
  8013. COMPOSITIONFORM cf;
  8014. cf.ptCurrentPos.x = x;
  8015. cf.ptCurrentPos.y = y;
  8016. cf.dwStyle = CFS_FORCE_POSITION;
  8017. ::ImmSetCompositionWindow(himc, &cf);
  8018. ::ImmReleaseContext(hwnd, himc);
  8019. }
  8020. }
  8021. #else
  8022. static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
  8023. #endif
  8024. //-----------------------------------------------------------------------------
  8025. // [SECTION] METRICS/DEBUG WINDOW
  8026. //-----------------------------------------------------------------------------
  8027. void ImGui::ShowMetricsWindow(bool* p_open)
  8028. {
  8029. if (!ImGui::Begin("ImGui Metrics", p_open))
  8030. {
  8031. ImGui::End();
  8032. return;
  8033. }
  8034. static bool show_draw_cmd_clip_rects = true;
  8035. static bool show_window_begin_order = false;
  8036. ImGuiIO& io = ImGui::GetIO();
  8037. ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
  8038. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  8039. ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
  8040. ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
  8041. ImGui::Text("%d allocations", io.MetricsActiveAllocations);
  8042. ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_draw_cmd_clip_rects);
  8043. ImGui::Checkbox("Ctrl shows window begin order", &show_window_begin_order);
  8044. ImGui::Separator();
  8045. struct Funcs
  8046. {
  8047. static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
  8048. {
  8049. bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
  8050. if (draw_list == ImGui::GetWindowDrawList())
  8051. {
  8052. ImGui::SameLine();
  8053. ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  8054. if (node_open) ImGui::TreePop();
  8055. return;
  8056. }
  8057. ImDrawList* overlay_draw_list = GetOverlayDrawList(window); // Render additional visuals into the top-most draw list
  8058. if (window && IsItemHovered())
  8059. overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  8060. if (!node_open)
  8061. return;
  8062. int elem_offset = 0;
  8063. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
  8064. {
  8065. if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
  8066. continue;
  8067. if (pcmd->UserCallback)
  8068. {
  8069. ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  8070. continue;
  8071. }
  8072. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  8073. bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  8074. if (show_draw_cmd_clip_rects && ImGui::IsItemHovered())
  8075. {
  8076. ImRect clip_rect = pcmd->ClipRect;
  8077. ImRect vtxs_rect;
  8078. for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
  8079. vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
  8080. clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
  8081. vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
  8082. }
  8083. if (!pcmd_node_open)
  8084. continue;
  8085. // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
  8086. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  8087. while (clipper.Step())
  8088. for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
  8089. {
  8090. char buf[300];
  8091. char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
  8092. ImVec2 triangles_pos[3];
  8093. for (int n = 0; n < 3; n++, vtx_i++)
  8094. {
  8095. ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
  8096. triangles_pos[n] = v.pos;
  8097. buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  8098. }
  8099. ImGui::Selectable(buf, false);
  8100. if (ImGui::IsItemHovered())
  8101. {
  8102. ImDrawListFlags backup_flags = overlay_draw_list->Flags;
  8103. overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
  8104. overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
  8105. overlay_draw_list->Flags = backup_flags;
  8106. }
  8107. }
  8108. ImGui::TreePop();
  8109. }
  8110. ImGui::TreePop();
  8111. }
  8112. static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
  8113. {
  8114. if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
  8115. return;
  8116. for (int i = 0; i < windows.Size; i++)
  8117. Funcs::NodeWindow(windows[i], "Window");
  8118. ImGui::TreePop();
  8119. }
  8120. static void NodeWindow(ImGuiWindow* window, const char* label)
  8121. {
  8122. if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
  8123. return;
  8124. ImGuiWindowFlags flags = window->Flags;
  8125. NodeDrawList(window, window->DrawList, "DrawList");
  8126. ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
  8127. ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
  8128. (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
  8129. (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
  8130. (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
  8131. ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window));
  8132. ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
  8133. ImGui::BulletText("Appearing: %d, Hidden: %d (Reg %d Resize %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesRegular, window->HiddenFramesForResize, window->SkipItems);
  8134. ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
  8135. ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
  8136. if (!window->NavRectRel[0].IsInverted())
  8137. ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
  8138. else
  8139. ImGui::BulletText("NavRectRel[0]: <None>");
  8140. if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
  8141. if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
  8142. if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
  8143. if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
  8144. {
  8145. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  8146. {
  8147. const ImGuiColumnsSet* columns = &window->ColumnsStorage[n];
  8148. if (ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
  8149. {
  8150. ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX);
  8151. for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
  8152. ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm));
  8153. ImGui::TreePop();
  8154. }
  8155. }
  8156. ImGui::TreePop();
  8157. }
  8158. ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
  8159. ImGui::TreePop();
  8160. }
  8161. static void NodeTabBar(ImGuiTabBar* tab_bar)
  8162. {
  8163. // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernable strings.
  8164. char buf[256];
  8165. char* p = buf;
  8166. const char* buf_end = buf + IM_ARRAYSIZE(buf);
  8167. p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s",
  8168. tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
  8169. if (ImGui::TreeNode(tab_bar, "%s", buf))
  8170. {
  8171. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
  8172. {
  8173. const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  8174. ImGui::PushID(tab);
  8175. if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
  8176. if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
  8177. ImGui::Text("%02d%c Tab 0x%08X", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID);
  8178. ImGui::PopID();
  8179. }
  8180. ImGui::TreePop();
  8181. }
  8182. }
  8183. };
  8184. // Access private state, we are going to display the draw lists from last frame
  8185. ImGuiContext& g = *GImGui;
  8186. Funcs::NodeWindows(g.Windows, "Windows");
  8187. if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
  8188. {
  8189. for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
  8190. Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
  8191. ImGui::TreePop();
  8192. }
  8193. if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
  8194. {
  8195. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  8196. {
  8197. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  8198. ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
  8199. }
  8200. ImGui::TreePop();
  8201. }
  8202. if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size))
  8203. {
  8204. for (int n = 0; n < g.TabBars.Data.Size; n++)
  8205. Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
  8206. ImGui::TreePop();
  8207. }
  8208. if (ImGui::TreeNode("Internal state"))
  8209. {
  8210. const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
  8211. ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  8212. ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
  8213. ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
  8214. ImGui::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]);
  8215. ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  8216. ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
  8217. ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  8218. ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
  8219. ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
  8220. ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
  8221. ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
  8222. ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
  8223. ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
  8224. ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
  8225. ImGui::TreePop();
  8226. }
  8227. if (g.IO.KeyCtrl && show_window_begin_order)
  8228. {
  8229. for (int n = 0; n < g.Windows.Size; n++)
  8230. {
  8231. ImGuiWindow* window = g.Windows[n];
  8232. if ((window->Flags & ImGuiWindowFlags_ChildWindow) || !window->WasActive)
  8233. continue;
  8234. char buf[32];
  8235. ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
  8236. float font_size = ImGui::GetFontSize() * 2;
  8237. ImDrawList* overlay_draw_list = GetOverlayDrawList(window);
  8238. overlay_draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
  8239. overlay_draw_list->AddText(NULL, font_size, window->Pos, IM_COL32(255, 255, 255, 255), buf);
  8240. }
  8241. }
  8242. ImGui::End();
  8243. }
  8244. //-----------------------------------------------------------------------------
  8245. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  8246. // 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.
  8247. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  8248. #include "imgui_user.inl"
  8249. #endif
  8250. //-----------------------------------------------------------------------------