imgui.cpp 387 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335
  1. // dear imgui, v1.48 WIP
  2. // (main code and documentation)
  3. // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code.
  4. // Newcomers, read 'Programmer guide' below for notes on how to setup 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. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  8. // This library is free but I need your support to sustain development and maintenance.
  9. // If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui
  10. /*
  11. Index
  12. - MISSION STATEMENT
  13. - END-USER GUIDE
  14. - PROGRAMMER GUIDE (read me!)
  15. - API BREAKING CHANGES (read me when you update!)
  16. - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  17. - How can I help?
  18. - How do I update to a newer version of ImGui?
  19. - Can I have multiple widgets with the same label? Can I have widget without a label? (Yes)
  20. - I integrated ImGui in my engine and the text or lines are blurry..
  21. - I integrated ImGui in my engine and some elements are disappearing when I move windows around..
  22. - How can I load a different font than the default?
  23. - How can I load multiple fonts?
  24. - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
  25. - ISSUES & TODO-LIST
  26. - CODE
  27. MISSION STATEMENT
  28. =================
  29. - easy to use to create code-driven and data-driven tools
  30. - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
  31. - easy to hack and improve
  32. - minimize screen real-estate usage
  33. - minimize setup and maintenance
  34. - minimize state storage on user side
  35. - portable, minimize dependencies, run on target (consoles, phones, etc.)
  36. - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything)
  37. - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html
  38. Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
  39. - doesn't look fancy, doesn't animate
  40. - limited layout features, intricate layouts are typically crafted in code
  41. - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction.
  42. END-USER GUIDE
  43. ==============
  44. - double-click title bar to collapse window
  45. - click upper right corner to close a window, available when 'bool* p_opened' is passed to ImGui::Begin()
  46. - click and drag on lower right corner to resize window
  47. - click and drag on any empty space to move window
  48. - double-click/double-tap on lower right corner grip to auto-fit to content
  49. - TAB/SHIFT+TAB to cycle through keyboard editable fields
  50. - use mouse wheel to scroll
  51. - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true)
  52. - CTRL+Click on a slider or drag box to input value as text
  53. - text editor:
  54. - Hold SHIFT or use mouse to select text.
  55. - CTRL+Left/Right to word jump
  56. - CTRL+Shift+Left/Right to select words
  57. - CTRL+A our Double-Click to select all
  58. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard
  59. - CTRL+Z,CTRL+Y to undo/redo
  60. - ESCAPE to revert text to its original value
  61. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  62. PROGRAMMER GUIDE
  63. ================
  64. - read the FAQ below this section!
  65. - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs.
  66. - call and read ImGui::ShowTestWindow() for demo code demonstrating most features.
  67. - see examples/ folder for standalone sample applications. Prefer reading examples/opengl_example/ first at it is the simplest.
  68. - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme).
  69. - getting started:
  70. - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'.
  71. - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory.
  72. - every frame:
  73. 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input'
  74. 2/ call ImGui::NewFrame().
  75. 3/ use any ImGui function you want between NewFrame() and Render()
  76. 4/ call ImGui::Render() to render all the accumulated command-lists. it will call your RenderDrawListFn handler that you set in the IO structure.
  77. - all rendering information are stored into command-lists until ImGui::Render() is called.
  78. - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you must provide.
  79. - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases.
  80. - refer to the examples applications in the examples/ folder for instruction on how to setup your code.
  81. - a typical application skeleton may be:
  82. // Application init
  83. ImGuiIO& io = ImGui::GetIO();
  84. io.DisplaySize.x = 1920.0f;
  85. io.DisplaySize.y = 1280.0f;
  86. io.IniFilename = "imgui.ini";
  87. io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data.
  88. // TODO: Fill others settings of the io structure
  89. // Load texture atlas
  90. // There is a default font so you don't need to care about choosing a font yet
  91. unsigned char* pixels;
  92. int width, height;
  93. io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
  94. // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system
  95. // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'
  96. // Application main loop
  97. while (true)
  98. {
  99. // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.)
  100. // TODO: fill all fields of IO structure and call NewFrame
  101. ImGuiIO& io = ImGui::GetIO();
  102. io.DeltaTime = 1.0f/60.0f;
  103. io.MousePos = mouse_pos;
  104. io.MouseDown[0] = mouse_button_0;
  105. io.MouseDown[1] = mouse_button_1;
  106. io.KeysDown[i] = ...
  107. // 2) call NewFrame(), after this point you can use ImGui::* functions anytime
  108. ImGui::NewFrame();
  109. // 3) most of your application code here
  110. ImGui::Begin("My window");
  111. ImGui::Text("Hello, world.");
  112. ImGui::End();
  113. MyGameUpdate(); // may use ImGui functions
  114. MyGameRender(); // may use ImGui functions
  115. // 4) render & swap video buffers
  116. ImGui::Render();
  117. // swap video buffer, etc.
  118. }
  119. - after calling ImGui::NewFrame() you can read back flags from the IO structure to tell how ImGui intends to use your inputs.
  120. When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
  121. When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available.
  122. API BREAKING CHANGES
  123. ====================
  124. Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
  125. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
  126. Also read releases logs https://github.com/ocornut/imgui/releases for more details.
  127. - 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.
  128. - 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.
  129. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  130. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  131. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  132. 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.
  133. 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!
  134. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  135. - 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.
  136. - 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
  137. - 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.
  138. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  139. - 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.
  140. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  141. - 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.
  142. - the signature of the io.RenderDrawListsFn handler has changed!
  143. ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  144. became:
  145. ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  146. argument 'cmd_lists' -> 'draw_data->CmdLists'
  147. argument 'cmd_lists_count' -> 'draw_data->CmdListsCount'
  148. ImDrawList 'commands' -> 'CmdBuffer'
  149. ImDrawList 'vtx_buffer' -> 'VtxBuffer'
  150. ImDrawList n/a -> 'IdxBuffer' (new)
  151. ImDrawCmd 'vtx_count' -> 'ElemCount'
  152. ImDrawCmd 'clip_rect' -> 'ClipRect'
  153. ImDrawCmd 'user_callback' -> 'UserCallback'
  154. ImDrawCmd 'texture_id' -> 'TextureId'
  155. - 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.
  156. - 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!
  157. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  158. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  159. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  160. - 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.
  161. - 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
  162. - 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!
  163. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  164. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  165. - 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.
  166. - 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 "opened" state of a popup. BeginPopup() returns true if the popup is opened.
  167. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  168. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function (will obsolete).
  169. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  170. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  171. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  172. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function (will obsolete).
  173. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  174. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function (will obsolete).
  175. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  176. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function (will obsolete).
  177. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  178. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  179. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  180. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  181. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  182. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  183. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  184. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  185. this sequence:
  186. const void* png_data;
  187. unsigned int png_size;
  188. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  189. // <Copy to GPU>
  190. became:
  191. unsigned char* pixels;
  192. int width, height;
  193. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  194. // <Copy to GPU>
  195. io.Fonts->TexID = (your_texture_identifier);
  196. you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
  197. it is now recommended that you sample the font texture with bilinear interpolation.
  198. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
  199. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  200. (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  201. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  202. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  203. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  204. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  205. - 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)
  206. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  207. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  208. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  209. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  210. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  211. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  212. FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  213. ======================================
  214. Q: How can I help?
  215. A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help!
  216. - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time.
  217. Q: How do I update to a newer version of ImGui?
  218. A: Overwrite the following files:
  219. imgui.cpp
  220. imgui.h
  221. imgui_demo.cpp
  222. imgui_draw.cpp
  223. imgui_internal.h
  224. stb_rect_pack.h
  225. stb_textedit.h
  226. stb_truetype.h
  227. Don't overwrite imconfig.h if you have made modification to your copy.
  228. Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name
  229. in the code, there will likely be a comment about it. Please report any issue to the GitHub page!
  230. Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes)
  231. A: Yes. A primer on the use of labels/IDs in ImGui..
  232. - Elements that are not clickable, such as Text() items don't need an ID.
  233. - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget).
  234. to do so they need an unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
  235. Button("OK"); // Label = "OK", ID = hash of "OK"
  236. Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
  237. - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows
  238. or in two different locations of a tree.
  239. - If you have a same ID twice in the same location, you'll have a conflict:
  240. Button("OK");
  241. Button("OK"); // ID collision! Both buttons will be treated as the same.
  242. Fear not! this is easy to solve and there are many ways to solve it!
  243. - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases.
  244. use "##" to pass a complement to the ID that won't be visible to the end-user:
  245. Button("Play"); // Label = "Play", ID = hash of "Play"
  246. Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
  247. Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
  248. - If you want to completely hide the label, but still need an ID:
  249. Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
  250. - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels.
  251. For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously)
  252. Use "###" to pass a label that isn't part of ID:
  253. Button("Hello###ID"; // Label = "Hello", ID = hash of "ID"
  254. Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above)
  255. sprintf(buf, "My game (%f FPS)###MyGame");
  256. Begin(buf); // Variable label, ID = hash of "MyGame"
  257. - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
  258. This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
  259. You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack!
  260. for (int i = 0; i < 100; i++)
  261. {
  262. PushID(i);
  263. Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
  264. PopID();
  265. }
  266. for (int i = 0; i < 100; i++)
  267. {
  268. MyObject* obj = Objects[i];
  269. PushID(obj);
  270. Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
  271. PopID();
  272. }
  273. for (int i = 0; i < 100; i++)
  274. {
  275. MyObject* obj = Objects[i];
  276. PushID(obj->Name);
  277. Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
  278. PopID();
  279. }
  280. - More example showing that you can stack multiple prefixes into the ID stack:
  281. Button("Click"); // Label = "Click", ID = hash of "Click"
  282. PushID("node");
  283. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  284. PushID(my_ptr);
  285. Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click"
  286. PopID();
  287. PopID();
  288. - Tree nodes implicitly creates a scope for you by calling PushID().
  289. Button("Click"); // Label = "Click", ID = hash of "Click"
  290. if (TreeNode("node"))
  291. {
  292. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  293. TreePop();
  294. }
  295. - When working with trees, ID are used to preserve the opened/closed state of each tree node.
  296. Depending on your use cases you may want to use strings, indices or pointers as ID.
  297. e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change.
  298. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense!
  299. Q: I integrated ImGui in my engine and the text or lines are blurry..
  300. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
  301. Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
  302. Q. I integrated ImGui in my engine and some elements are disappearing when I move windows around..
  303. Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1,y1,x2,y2) and NOT as (x1,y1,width,height).
  304. Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
  305. A: Use the font atlas to load the TTF file you want:
  306. ImGuiIO& io = ImGui::GetIO();
  307. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  308. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  309. Q: How can I load multiple fonts?
  310. A: Use the font atlas to pack them into a single texture:
  311. (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.)
  312. ImGuiIO& io = ImGui::GetIO();
  313. ImFont* font0 = io.Fonts->AddFontDefault();
  314. ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  315. ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
  316. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  317. // the first loaded font gets used by default
  318. // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
  319. // Options
  320. ImFontConfig config;
  321. config.OversampleH = 3;
  322. config.OversampleV = 1;
  323. config.GlyphExtraSpacing.x = 1.0f;
  324. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
  325. // Combine multiple fonts into one
  326. ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
  327. ImFontConfig config;
  328. config.MergeMode = true;
  329. io.Fonts->AddFontDefault();
  330. io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges);
  331. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese());
  332. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  333. A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. ImGui will support UTF-8 encoding across the board.
  334. Character input depends on you passing the right character code to io.AddInputCharacter(). The example applications do that.
  335. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters
  336. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  337. io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application
  338. - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code.
  339. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug"
  340. - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings)
  341. - tip: you can call Render() multiple times (e.g for VR renders).
  342. - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui!
  343. ISSUES & TODO-LIST
  344. ==================
  345. Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues
  346. The list below consist mostly of notes of things to do before they are requested/discussed by users (at that point it usually happens on the github)
  347. - doc: add a proper documentation+regression testing system (#435)
  348. - window: maximum window size settings (per-axis). for large popups in particular user may not want the popup to fill all space.
  349. - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass.
  350. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis).
  351. - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify.
  352. - window: allow resizing of child windows (possibly given min/max for each axis?)
  353. - window: background options for child windows, border option (disable rounding)
  354. - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip)
  355. - window: resizing from any sides? + mouse cursor directives for app.
  356. !- window: begin with *p_opened == false should return false.
  357. - window: get size/pos helpers given names (see discussion in #249)
  358. - window: a collapsed window can be stuck behind the main menu bar?
  359. - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later.
  360. - window: consider renaming "GetWindowFont" which conflict with old Windows #define (#340)
  361. - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic.
  362. - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command).
  363. !- scrolling: allow immediately effective change of scroll if we haven't appended items yet
  364. - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319)
  365. - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc.
  366. - widgets: clean up widgets internal toward exposing everything.
  367. - widgets: add disabled and read-only modes (#211)
  368. - main: considering adding EndFrame()/Init(). some constructs are awkward in the implementation because of the lack of them.
  369. - main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows).
  370. - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes
  371. - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode?
  372. - input text: add ImGuiInputTextFlags_EnterToApply? (off #218)
  373. - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc).
  374. - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200)
  375. - input text multi-line: line numbers? status bar? (follow up on #200)
  376. - input number: optional range min/max for Input*() functions
  377. - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled)
  378. - input number: use mouse wheel to step up/down
  379. - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack.
  380. - text: proper alignment options
  381. - image/image button: misalignment on padded/bordered button?
  382. - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that?
  383. - layout: horizontal layout helper (#97)
  384. - layout: horizontal flow until no space left (#404)
  385. - layout: more generic alignment state (left/right/centered) for single items?
  386. - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding.
  387. - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125)
  388. - columns: add a conditional parameter to SetColumnOffset() (#513, #125)
  389. - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125)
  390. - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125)
  391. - columns: user specify columns size (#513, #125)
  392. - columns: flag to add horizontal separator above/below?
  393. - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets)
  394. - combo: sparse combo boxes (via function call?) / iterators
  395. - combo: contents should extends to fit label if combo widget is small
  396. - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203)
  397. - listbox: multiple selection
  398. - listbox: user may want to initial scroll to focus on the one selected value?
  399. - listbox: keyboard navigation.
  400. - listbox: scrolling should track modified selection.
  401. !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402)
  402. - popups: add variant using global identifier similar to Begin/End (#402)
  403. - popups: border options. richer api like BeginChild() perhaps? (#197)
  404. - menus: local shortcuts, global shortcuts (#456, #126)
  405. - menus: icons
  406. - menus: menubars: some sort of priority / effect of main menu-bar on desktop size?
  407. - statusbar: add a per-window status bar helper similar to what menubar does.
  408. - tabs (#261, #351)
  409. - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y)
  410. - color: the color helpers/typing is a mess and needs sorting out.
  411. - color: add a better color picker (#346)
  412. - node/graph editor (#306)
  413. - pie menus patterns (#434)
  414. - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals)
  415. - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots)
  416. - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value)
  417. - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID)
  418. - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt()
  419. - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar).
  420. - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate.
  421. - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign)
  422. - slider & drag: int data passing through a float
  423. - drag float: up/down axis
  424. - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits)
  425. - text edit: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now.
  426. - text edit: centered text for slider as input text so it matches typical positioning.
  427. - text edit: flag to disable live update of the user buffer.
  428. - text edit: field resize behavior - field could stretch when being edited? hover tooltip shows more text?
  429. - tree node / optimization: avoid formatting when clipped.
  430. - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling.
  431. - tree node: add treenode/treepush int variants? because (void*) cast from int warns on some platforms/settings
  432. - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer)
  433. - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (git issue #249)
  434. - settings: write more decent code to allow saving/loading new fields
  435. - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file
  436. - style: add window shadows.
  437. - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding.
  438. - style: color-box not always square?
  439. - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc.
  440. - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation).
  441. - style: global scale setting.
  442. - text: simple markup language for color change?
  443. - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier.
  444. - font: helper to add glyph redirect/replacements (e.g. redirect alternate apostrophe unicode code points to ascii one, etc.)
  445. - log: LogButtons() options for specifying depth and/or hiding depth slider
  446. - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope)
  447. - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard)
  448. - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs.
  449. - filters: set a current filter that tree node can automatically query to hide themselves
  450. - filters: handle wildcards (with implicit leading/trailing *), regexps
  451. - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus)
  452. !- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing
  453. - keyboard: full keyboard navigation and focus. (#323)
  454. - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame)
  455. - input: rework IO system to be able to pass actual ordered/timestamped events.
  456. - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style).
  457. - input: support track pad style scrolling & slider edit.
  458. - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL)
  459. - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon?
  460. - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438)
  461. - style editor: color child window height expressed in multiple of line height.
  462. - remote: make a system like RemoteImGui first-class citizen/project (#75)
  463. - drawlist: user probably can't call Clear() because we expect a texture to be pushed in the stack.
  464. - examples: directx9/directx11: save/restore device state more thoroughly.
  465. - optimization: use another hash function than crc32, e.g. FNV1a
  466. - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)?
  467. - optimization: turn some the various stack vectors into statically-sized arrays
  468. - optimization: better clipping for multi-component widgets
  469. */
  470. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  471. #define _CRT_SECURE_NO_WARNINGS
  472. #endif
  473. #include "imgui.h"
  474. #define IMGUI_DEFINE_MATH_OPERATORS
  475. #define IMGUI_DEFINE_PLACEMENT_NEW
  476. #include "imgui_internal.h"
  477. #include <ctype.h> // toupper, isprint
  478. #include <math.h> // sqrtf, fabsf, fmodf, powf, cosf, sinf, floorf, ceilf
  479. #include <stdlib.h> // NULL, malloc, free, qsort, atoi
  480. #include <stdio.h> // vsnprintf, sscanf, printf
  481. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  482. #include <stddef.h> // intptr_t
  483. #else
  484. #include <stdint.h> // intptr_t
  485. #endif
  486. #ifdef _MSC_VER
  487. #pragma warning (disable: 4127) // condition expression is constant
  488. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  489. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  490. #define snprintf _snprintf
  491. #endif
  492. // Clang warnings with -Weverything
  493. #ifdef __clang__
  494. #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
  495. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok.
  496. #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.
  497. #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.
  498. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
  499. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
  500. #pragma clang diagnostic ignored "-Wmissing-noreturn" // warning : function xx could be declared with attribute 'noreturn' warning // GetDefaultFontData() asserts which some implementation makes it never return.
  501. #pragma clang diagnostic ignored "-Wdeprecated-declarations"// warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code)
  502. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
  503. #endif
  504. #ifdef __GNUC__
  505. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  506. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  507. #endif
  508. //-------------------------------------------------------------------------
  509. // Forward Declarations
  510. //-------------------------------------------------------------------------
  511. static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL);
  512. static const char* FindTextDisplayEnd(const char* text, const char* text_end = NULL);
  513. static void PushMultiItemsWidths(int components, float w_full = 0.0f);
  514. static float GetDraggedColumnOffset(int column_index);
  515. static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
  516. static void SetCurrentFont(ImFont* font);
  517. static void SetCurrentWindow(ImGuiWindow* window);
  518. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
  519. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond);
  520. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond);
  521. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond);
  522. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs);
  523. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
  524. static inline bool IsWindowContentHoverable(ImGuiWindow* window);
  525. static void ClearSetNextWindowData();
  526. static void CheckStacksSize(ImGuiWindow* window, bool write);
  527. static void Scrollbar(ImGuiWindow* window, bool horizontal);
  528. static bool CloseWindowButton(bool* p_opened);
  529. static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list);
  530. static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window);
  531. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window);
  532. static ImGuiIniData* FindWindowSettings(const char* name);
  533. static ImGuiIniData* AddWindowSettings(const char* name);
  534. static void LoadSettings();
  535. static void SaveSettings();
  536. static void MarkSettingsDirty();
  537. static void PushColumnClipRect(int column_index = -1);
  538. static ImRect GetVisibleRect();
  539. static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags);
  540. static void CloseInactivePopups();
  541. static void ClosePopupToLevel(int remaining);
  542. static void ClosePopup(ImGuiID id);
  543. static bool IsPopupOpen(ImGuiID id);
  544. static ImGuiWindow* GetFrontMostModalRootWindow();
  545. static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid);
  546. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data);
  547. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
  548. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
  549. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
  550. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
  551. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
  552. static void DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
  553. //-----------------------------------------------------------------------------
  554. // Platform dependent default implementations
  555. //-----------------------------------------------------------------------------
  556. static const char* GetClipboardTextFn_DefaultImpl();
  557. static void SetClipboardTextFn_DefaultImpl(const char* text);
  558. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
  559. //-----------------------------------------------------------------------------
  560. // Context
  561. //-----------------------------------------------------------------------------
  562. // We access everything through this pointer (always assumed to be != NULL)
  563. // You can swap the pointer to a different context by calling ImGui::SetInternalState()
  564. static ImGuiState GImDefaultState;
  565. ImGuiState* GImGui = &GImDefaultState;
  566. // Statically allocated default font atlas. This is merely a maneuver to keep ImFontAtlas definition at the bottom of the .h file (otherwise it'd be inside ImGuiIO)
  567. // Also we wouldn't be able to new() one at this point, before users may define IO.MemAllocFn.
  568. static ImFontAtlas GImDefaultFontAtlas;
  569. //-----------------------------------------------------------------------------
  570. // User facing structures
  571. //-----------------------------------------------------------------------------
  572. ImGuiStyle::ImGuiStyle()
  573. {
  574. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  575. WindowPadding = ImVec2(8,8); // Padding within a window
  576. WindowMinSize = ImVec2(32,32); // Minimum window size
  577. WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
  578. WindowTitleAlign = ImGuiAlign_Left; // Alignment for title bar text
  579. ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows
  580. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  581. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  582. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  583. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  584. 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!
  585. WindowFillAlphaDefault = 0.70f; // Default alpha of window background, if not specified in ImGui::Begin()
  586. IndentSpacing = 22.0f; // Horizontal spacing when e.g. entering a tree node
  587. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
  588. ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  589. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  590. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  591. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  592. DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
  593. DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
  594. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
  595. AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
  596. CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
  597. Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  598. Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
  599. Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  600. Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  601. Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f);
  602. Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  603. Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
  604. Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f);
  605. Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f);
  606. Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f);
  607. Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
  608. Colors[ImGuiCol_TitleBgActive] = ImVec4(0.50f, 0.50f, 1.00f, 0.55f);
  609. Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
  610. Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
  611. Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
  612. Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
  613. Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f);
  614. Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f);
  615. Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
  616. Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
  617. Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
  618. Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f);
  619. Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f);
  620. Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
  621. Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
  622. Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
  623. Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);
  624. Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
  625. Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f);
  626. Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f);
  627. Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
  628. Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
  629. Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
  630. Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
  631. Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
  632. Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
  633. Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  634. Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
  635. Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
  636. Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
  637. Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
  638. Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
  639. Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
  640. }
  641. ImGuiIO::ImGuiIO()
  642. {
  643. // Most fields are initialized with zero
  644. memset(this, 0, sizeof(*this));
  645. DisplaySize = ImVec2(-1.0f, -1.0f);
  646. DeltaTime = 1.0f/60.0f;
  647. IniSavingRate = 5.0f;
  648. IniFilename = "imgui.ini";
  649. LogFilename = "imgui_log.txt";
  650. Fonts = &GImDefaultFontAtlas;
  651. FontGlobalScale = 1.0f;
  652. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  653. MousePos = ImVec2(-1,-1);
  654. MousePosPrev = ImVec2(-1,-1);
  655. MouseDoubleClickTime = 0.30f;
  656. MouseDoubleClickMaxDist = 6.0f;
  657. MouseDragThreshold = 6.0f;
  658. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++)
  659. MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  660. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++)
  661. KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  662. for (int i = 0; i < ImGuiKey_COUNT; i++)
  663. KeyMap[i] = -1;
  664. KeyRepeatDelay = 0.250f;
  665. KeyRepeatRate = 0.050f;
  666. UserData = NULL;
  667. // User functions
  668. RenderDrawListsFn = NULL;
  669. MemAllocFn = malloc;
  670. MemFreeFn = free;
  671. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  672. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  673. ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
  674. }
  675. // Pass in translated ASCII characters for text input.
  676. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  677. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  678. void ImGuiIO::AddInputCharacter(ImWchar c)
  679. {
  680. const int n = ImStrlenW(InputCharacters);
  681. if (n + 1 < IM_ARRAYSIZE(InputCharacters))
  682. {
  683. InputCharacters[n] = c;
  684. InputCharacters[n+1] = '\0';
  685. }
  686. }
  687. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  688. {
  689. // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
  690. const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
  691. ImWchar wchars[wchars_buf_len];
  692. ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
  693. for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
  694. AddInputCharacter(wchars[i]);
  695. }
  696. //-----------------------------------------------------------------------------
  697. // HELPERS
  698. //-----------------------------------------------------------------------------
  699. #define IM_F32_TO_INT8(_VAL) ((int)((_VAL) * 255.0f + 0.5f))
  700. #define IM_INT_MIN (-2147483647-1)
  701. #define IM_INT_MAX (2147483647)
  702. // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
  703. #ifdef _WIN32
  704. #define IM_NEWLINE "\r\n"
  705. #else
  706. #define IM_NEWLINE "\n"
  707. #endif
  708. bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c)
  709. {
  710. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  711. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  712. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  713. return ((b1 == b2) && (b2 == b3));
  714. }
  715. int ImStricmp(const char* str1, const char* str2)
  716. {
  717. int d;
  718. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  719. return d;
  720. }
  721. int ImStrnicmp(const char* str1, const char* str2, int count)
  722. {
  723. int d = 0;
  724. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  725. return d;
  726. }
  727. char* ImStrdup(const char *str)
  728. {
  729. size_t len = strlen(str) + 1;
  730. void* buff = ImGui::MemAlloc(len);
  731. return (char*)memcpy(buff, (const void*)str, len);
  732. }
  733. int ImStrlenW(const ImWchar* str)
  734. {
  735. int n = 0;
  736. while (*str++) n++;
  737. return n;
  738. }
  739. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  740. {
  741. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  742. buf_mid_line--;
  743. return buf_mid_line;
  744. }
  745. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  746. {
  747. if (!needle_end)
  748. needle_end = needle + strlen(needle);
  749. const char un0 = (char)toupper(*needle);
  750. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  751. {
  752. if (toupper(*haystack) == un0)
  753. {
  754. const char* b = needle + 1;
  755. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  756. if (toupper(*a) != toupper(*b))
  757. break;
  758. if (b == needle_end)
  759. return haystack;
  760. }
  761. haystack++;
  762. }
  763. return NULL;
  764. }
  765. int ImFormatString(char* buf, int buf_size, const char* fmt, ...)
  766. {
  767. va_list args;
  768. va_start(args, fmt);
  769. int w = vsnprintf(buf, buf_size, fmt, args);
  770. va_end(args);
  771. buf[buf_size-1] = 0;
  772. return (w == -1) ? buf_size : w;
  773. }
  774. int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args)
  775. {
  776. int w = vsnprintf(buf, buf_size, fmt, args);
  777. buf[buf_size-1] = 0;
  778. return (w == -1) ? buf_size : w;
  779. }
  780. // Pass data_size==0 for zero-terminated strings
  781. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  782. ImU32 ImHash(const void* data, int data_size, ImU32 seed)
  783. {
  784. static ImU32 crc32_lut[256] = { 0 };
  785. if (!crc32_lut[1])
  786. {
  787. const ImU32 polynomial = 0xEDB88320;
  788. for (ImU32 i = 0; i < 256; i++)
  789. {
  790. ImU32 crc = i;
  791. for (ImU32 j = 0; j < 8; j++)
  792. crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
  793. crc32_lut[i] = crc;
  794. }
  795. }
  796. seed = ~seed;
  797. ImU32 crc = seed;
  798. const unsigned char* current = (const unsigned char*)data;
  799. if (data_size > 0)
  800. {
  801. // Known size
  802. while (data_size--)
  803. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
  804. }
  805. else
  806. {
  807. // Zero-terminated string
  808. while (unsigned char c = *current++)
  809. {
  810. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  811. // Because this syntax is rarely used we are optimizing for the common case.
  812. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  813. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
  814. if (c == '#' && current[0] == '#' && current[1] == '#')
  815. crc = seed;
  816. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  817. }
  818. }
  819. return ~crc;
  820. }
  821. //-----------------------------------------------------------------------------
  822. // ImText* helpers
  823. //-----------------------------------------------------------------------------
  824. // Convert UTF-8 to 32-bits character, process single character input.
  825. // Based on stb_from_utf8() from github.com/nothings/stb/
  826. // We handle UTF-8 decoding error by skipping forward.
  827. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  828. {
  829. unsigned int c = (unsigned int)-1;
  830. const unsigned char* str = (const unsigned char*)in_text;
  831. if (!(*str & 0x80))
  832. {
  833. c = (unsigned int)(*str++);
  834. *out_char = c;
  835. return 1;
  836. }
  837. if ((*str & 0xe0) == 0xc0)
  838. {
  839. *out_char = 0xFFFD; // will be invalid but not end of string
  840. if (in_text_end && in_text_end - (const char*)str < 2) return 1;
  841. if (*str < 0xc2) return 2;
  842. c = (unsigned int)((*str++ & 0x1f) << 6);
  843. if ((*str & 0xc0) != 0x80) return 2;
  844. c += (*str++ & 0x3f);
  845. *out_char = c;
  846. return 2;
  847. }
  848. if ((*str & 0xf0) == 0xe0)
  849. {
  850. *out_char = 0xFFFD; // will be invalid but not end of string
  851. if (in_text_end && in_text_end - (const char*)str < 3) return 1;
  852. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
  853. if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
  854. c = (unsigned int)((*str++ & 0x0f) << 12);
  855. if ((*str & 0xc0) != 0x80) return 3;
  856. c += (unsigned int)((*str++ & 0x3f) << 6);
  857. if ((*str & 0xc0) != 0x80) return 3;
  858. c += (*str++ & 0x3f);
  859. *out_char = c;
  860. return 3;
  861. }
  862. if ((*str & 0xf8) == 0xf0)
  863. {
  864. *out_char = 0xFFFD; // will be invalid but not end of string
  865. if (in_text_end && in_text_end - (const char*)str < 4) return 1;
  866. if (*str > 0xf4) return 4;
  867. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
  868. if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
  869. c = (unsigned int)((*str++ & 0x07) << 18);
  870. if ((*str & 0xc0) != 0x80) return 4;
  871. c += (unsigned int)((*str++ & 0x3f) << 12);
  872. if ((*str & 0xc0) != 0x80) return 4;
  873. c += (unsigned int)((*str++ & 0x3f) << 6);
  874. if ((*str & 0xc0) != 0x80) return 4;
  875. c += (*str++ & 0x3f);
  876. // utf-8 encodings of values used in surrogate pairs are invalid
  877. if ((c & 0xFFFFF800) == 0xD800) return 4;
  878. *out_char = c;
  879. return 4;
  880. }
  881. *out_char = 0;
  882. return 0;
  883. }
  884. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  885. {
  886. ImWchar* buf_out = buf;
  887. ImWchar* buf_end = buf + buf_size;
  888. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  889. {
  890. unsigned int c;
  891. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  892. if (c == 0)
  893. break;
  894. if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
  895. *buf_out++ = (ImWchar)c;
  896. }
  897. *buf_out = 0;
  898. if (in_text_remaining)
  899. *in_text_remaining = in_text;
  900. return (int)(buf_out - buf);
  901. }
  902. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  903. {
  904. int char_count = 0;
  905. while ((!in_text_end || in_text < in_text_end) && *in_text)
  906. {
  907. unsigned int c;
  908. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  909. if (c == 0)
  910. break;
  911. if (c < 0x10000)
  912. char_count++;
  913. }
  914. return char_count;
  915. }
  916. // Based on stb_to_utf8() from github.com/nothings/stb/
  917. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  918. {
  919. if (c < 0x80)
  920. {
  921. buf[0] = (char)c;
  922. return 1;
  923. }
  924. if (c < 0x800)
  925. {
  926. if (buf_size < 2) return 0;
  927. buf[0] = (char)(0xc0 + (c >> 6));
  928. buf[1] = (char)(0x80 + (c & 0x3f));
  929. return 2;
  930. }
  931. if (c >= 0xdc00 && c < 0xe000)
  932. {
  933. return 0;
  934. }
  935. if (c >= 0xd800 && c < 0xdc00)
  936. {
  937. if (buf_size < 4) return 0;
  938. buf[0] = (char)(0xf0 + (c >> 18));
  939. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  940. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  941. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  942. return 4;
  943. }
  944. //else if (c < 0x10000)
  945. {
  946. if (buf_size < 3) return 0;
  947. buf[0] = (char)(0xe0 + (c >> 12));
  948. buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
  949. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  950. return 3;
  951. }
  952. }
  953. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  954. {
  955. if (c < 0x80) return 1;
  956. if (c < 0x800) return 2;
  957. if (c >= 0xdc00 && c < 0xe000) return 0;
  958. if (c >= 0xd800 && c < 0xdc00) return 4;
  959. return 3;
  960. }
  961. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  962. {
  963. char* buf_out = buf;
  964. const char* buf_end = buf + buf_size;
  965. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  966. {
  967. unsigned int c = (unsigned int)(*in_text++);
  968. if (c < 0x80)
  969. *buf_out++ = (char)c;
  970. else
  971. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
  972. }
  973. *buf_out = 0;
  974. return (int)(buf_out - buf);
  975. }
  976. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  977. {
  978. int bytes_count = 0;
  979. while ((!in_text_end || in_text < in_text_end) && *in_text)
  980. {
  981. unsigned int c = (unsigned int)(*in_text++);
  982. if (c < 0x80)
  983. bytes_count++;
  984. else
  985. bytes_count += ImTextCountUtf8BytesFromChar(c);
  986. }
  987. return bytes_count;
  988. }
  989. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  990. {
  991. float s = 1.0f/255.0f;
  992. return ImVec4((in & 0xFF) * s, ((in >> 8) & 0xFF) * s, ((in >> 16) & 0xFF) * s, (in >> 24) * s);
  993. }
  994. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  995. {
  996. ImU32 out;
  997. out = ((ImU32)IM_F32_TO_INT8(ImSaturate(in.x)));
  998. out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.y))) << 8;
  999. out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.z))) << 16;
  1000. out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.w))) << 24;
  1001. return out;
  1002. }
  1003. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1004. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1005. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1006. {
  1007. float K = 0.f;
  1008. if (g < b)
  1009. {
  1010. const float tmp = g; g = b; b = tmp;
  1011. K = -1.f;
  1012. }
  1013. if (r < g)
  1014. {
  1015. const float tmp = r; r = g; g = tmp;
  1016. K = -2.f / 6.f - K;
  1017. }
  1018. const float chroma = r - (g < b ? g : b);
  1019. out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f));
  1020. out_s = chroma / (r + 1e-20f);
  1021. out_v = r;
  1022. }
  1023. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1024. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1025. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1026. {
  1027. if (s == 0.0f)
  1028. {
  1029. // gray
  1030. out_r = out_g = out_b = v;
  1031. return;
  1032. }
  1033. h = fmodf(h, 1.0f) / (60.0f/360.0f);
  1034. int i = (int)h;
  1035. float f = h - (float)i;
  1036. float p = v * (1.0f - s);
  1037. float q = v * (1.0f - s * f);
  1038. float t = v * (1.0f - s * (1.0f - f));
  1039. switch (i)
  1040. {
  1041. case 0: out_r = v; out_g = t; out_b = p; break;
  1042. case 1: out_r = q; out_g = v; out_b = p; break;
  1043. case 2: out_r = p; out_g = v; out_b = t; break;
  1044. case 3: out_r = p; out_g = q; out_b = v; break;
  1045. case 4: out_r = t; out_g = p; out_b = v; break;
  1046. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1047. }
  1048. }
  1049. // Load file content into memory
  1050. // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
  1051. void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
  1052. {
  1053. IM_ASSERT(filename && file_open_mode);
  1054. if (out_file_size)
  1055. *out_file_size = 0;
  1056. FILE* f;
  1057. if ((f = fopen(filename, file_open_mode)) == NULL)
  1058. return NULL;
  1059. long file_size_signed;
  1060. if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
  1061. {
  1062. fclose(f);
  1063. return NULL;
  1064. }
  1065. int file_size = (int)file_size_signed;
  1066. void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
  1067. if (file_data == NULL)
  1068. {
  1069. fclose(f);
  1070. return NULL;
  1071. }
  1072. if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size)
  1073. {
  1074. fclose(f);
  1075. ImGui::MemFree(file_data);
  1076. return NULL;
  1077. }
  1078. if (padding_bytes > 0)
  1079. memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
  1080. fclose(f);
  1081. if (out_file_size)
  1082. *out_file_size = file_size;
  1083. return file_data;
  1084. }
  1085. //-----------------------------------------------------------------------------
  1086. // ImGuiStorage
  1087. //-----------------------------------------------------------------------------
  1088. // Helper: Key->value storage
  1089. void ImGuiStorage::Clear()
  1090. {
  1091. Data.clear();
  1092. }
  1093. // std::lower_bound but without the bullshit
  1094. static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImU32 key)
  1095. {
  1096. ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
  1097. ImVector<ImGuiStorage::Pair>::iterator last = data.end();
  1098. int count = (int)(last - first);
  1099. while (count > 0)
  1100. {
  1101. int count2 = count / 2;
  1102. ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
  1103. if (mid->key < key)
  1104. {
  1105. first = ++mid;
  1106. count -= count2 + 1;
  1107. }
  1108. else
  1109. {
  1110. count = count2;
  1111. }
  1112. }
  1113. return first;
  1114. }
  1115. int ImGuiStorage::GetInt(ImU32 key, int default_val) const
  1116. {
  1117. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1118. if (it == Data.end() || it->key != key)
  1119. return default_val;
  1120. return it->val_i;
  1121. }
  1122. float ImGuiStorage::GetFloat(ImU32 key, float default_val) const
  1123. {
  1124. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1125. if (it == Data.end() || it->key != key)
  1126. return default_val;
  1127. return it->val_f;
  1128. }
  1129. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1130. {
  1131. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1132. if (it == Data.end() || it->key != key)
  1133. return NULL;
  1134. return it->val_p;
  1135. }
  1136. // 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.
  1137. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1138. {
  1139. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1140. if (it == Data.end() || it->key != key)
  1141. it = Data.insert(it, Pair(key, default_val));
  1142. return &it->val_i;
  1143. }
  1144. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1145. {
  1146. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1147. if (it == Data.end() || it->key != key)
  1148. it = Data.insert(it, Pair(key, default_val));
  1149. return &it->val_f;
  1150. }
  1151. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1152. {
  1153. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1154. if (it == Data.end() || it->key != key)
  1155. it = Data.insert(it, Pair(key, default_val));
  1156. return &it->val_p;
  1157. }
  1158. // 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)
  1159. void ImGuiStorage::SetInt(ImU32 key, int val)
  1160. {
  1161. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1162. if (it == Data.end() || it->key != key)
  1163. {
  1164. Data.insert(it, Pair(key, val));
  1165. return;
  1166. }
  1167. it->val_i = val;
  1168. }
  1169. void ImGuiStorage::SetFloat(ImU32 key, float val)
  1170. {
  1171. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1172. if (it == Data.end() || it->key != key)
  1173. {
  1174. Data.insert(it, Pair(key, val));
  1175. return;
  1176. }
  1177. it->val_f = val;
  1178. }
  1179. void ImGuiStorage::SetVoidPtr(ImU32 key, void* val)
  1180. {
  1181. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1182. if (it == Data.end() || it->key != key)
  1183. {
  1184. Data.insert(it, Pair(key, val));
  1185. return;
  1186. }
  1187. it->val_p = val;
  1188. }
  1189. void ImGuiStorage::SetAllInt(int v)
  1190. {
  1191. for (int i = 0; i < Data.Size; i++)
  1192. Data[i].val_i = v;
  1193. }
  1194. //-----------------------------------------------------------------------------
  1195. // ImGuiTextFilter
  1196. //-----------------------------------------------------------------------------
  1197. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1198. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1199. {
  1200. if (default_filter)
  1201. {
  1202. ImFormatString(InputBuf, IM_ARRAYSIZE(InputBuf), "%s", default_filter);
  1203. Build();
  1204. }
  1205. else
  1206. {
  1207. InputBuf[0] = 0;
  1208. CountGrep = 0;
  1209. }
  1210. }
  1211. bool ImGuiTextFilter::Draw(const char* label, float width)
  1212. {
  1213. if (width != 0.0f)
  1214. ImGui::PushItemWidth(width);
  1215. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1216. if (width != 0.0f)
  1217. ImGui::PopItemWidth();
  1218. if (value_changed)
  1219. Build();
  1220. return value_changed;
  1221. }
  1222. void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
  1223. {
  1224. out.resize(0);
  1225. const char* wb = b;
  1226. const char* we = wb;
  1227. while (we < e)
  1228. {
  1229. if (*we == separator)
  1230. {
  1231. out.push_back(TextRange(wb, we));
  1232. wb = we + 1;
  1233. }
  1234. we++;
  1235. }
  1236. if (wb != we)
  1237. out.push_back(TextRange(wb, we));
  1238. }
  1239. void ImGuiTextFilter::Build()
  1240. {
  1241. Filters.resize(0);
  1242. TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
  1243. input_range.split(',', Filters);
  1244. CountGrep = 0;
  1245. for (int i = 0; i != Filters.Size; i++)
  1246. {
  1247. Filters[i].trim_blanks();
  1248. if (Filters[i].empty())
  1249. continue;
  1250. if (Filters[i].front() != '-')
  1251. CountGrep += 1;
  1252. }
  1253. }
  1254. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1255. {
  1256. if (Filters.empty())
  1257. return true;
  1258. if (text == NULL)
  1259. text = "";
  1260. for (int i = 0; i != Filters.Size; i++)
  1261. {
  1262. const TextRange& f = Filters[i];
  1263. if (f.empty())
  1264. continue;
  1265. if (f.front() == '-')
  1266. {
  1267. // Subtract
  1268. if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
  1269. return false;
  1270. }
  1271. else
  1272. {
  1273. // Grep
  1274. if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
  1275. return true;
  1276. }
  1277. }
  1278. // Implicit * grep
  1279. if (CountGrep == 0)
  1280. return true;
  1281. return false;
  1282. }
  1283. //-----------------------------------------------------------------------------
  1284. // ImGuiTextBuffer
  1285. //-----------------------------------------------------------------------------
  1286. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1287. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1288. #ifndef va_copy
  1289. #define va_copy(dest, src) (dest = src)
  1290. #endif
  1291. // Helper: Text buffer for logging/accumulating text
  1292. void ImGuiTextBuffer::appendv(const char* fmt, va_list args)
  1293. {
  1294. va_list args_copy;
  1295. va_copy(args_copy, args);
  1296. int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1297. if (len <= 0)
  1298. return;
  1299. const int write_off = Buf.Size;
  1300. const int needed_sz = write_off + len;
  1301. if (write_off + len >= Buf.Capacity)
  1302. {
  1303. int double_capacity = Buf.Capacity * 2;
  1304. Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
  1305. }
  1306. Buf.resize(needed_sz);
  1307. ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy);
  1308. }
  1309. void ImGuiTextBuffer::append(const char* fmt, ...)
  1310. {
  1311. va_list args;
  1312. va_start(args, fmt);
  1313. appendv(fmt, args);
  1314. va_end(args);
  1315. }
  1316. //-----------------------------------------------------------------------------
  1317. // ImGuiSimpleColumns
  1318. //-----------------------------------------------------------------------------
  1319. ImGuiSimpleColumns::ImGuiSimpleColumns()
  1320. {
  1321. Count = 0;
  1322. Spacing = Width = NextWidth = 0.0f;
  1323. memset(Pos, 0, sizeof(Pos));
  1324. memset(NextWidths, 0, sizeof(NextWidths));
  1325. }
  1326. void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
  1327. {
  1328. IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
  1329. Count = count;
  1330. Width = NextWidth = 0.0f;
  1331. Spacing = spacing;
  1332. if (clear) memset(NextWidths, 0, sizeof(NextWidths));
  1333. for (int i = 0; i < Count; i++)
  1334. {
  1335. if (i > 0 && NextWidths[i] > 0.0f)
  1336. Width += Spacing;
  1337. Pos[i] = (float)(int)Width;
  1338. Width += NextWidths[i];
  1339. NextWidths[i] = 0.0f;
  1340. }
  1341. }
  1342. float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
  1343. {
  1344. NextWidth = 0.0f;
  1345. NextWidths[0] = ImMax(NextWidths[0], w0);
  1346. NextWidths[1] = ImMax(NextWidths[1], w1);
  1347. NextWidths[2] = ImMax(NextWidths[2], w2);
  1348. for (int i = 0; i < 3; i++)
  1349. NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
  1350. return ImMax(Width, NextWidth);
  1351. }
  1352. float ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
  1353. {
  1354. return ImMax(0.0f, avail_w - Width);
  1355. }
  1356. //-----------------------------------------------------------------------------
  1357. // ImGuiWindow
  1358. //-----------------------------------------------------------------------------
  1359. ImGuiWindow::ImGuiWindow(const char* name)
  1360. {
  1361. Name = ImStrdup(name);
  1362. ID = ImHash(name, 0);
  1363. IDStack.push_back(ID);
  1364. MoveID = GetID("#MOVE");
  1365. Flags = 0;
  1366. PosFloat = Pos = ImVec2(0.0f, 0.0f);
  1367. Size = SizeFull = ImVec2(0.0f, 0.0f);
  1368. SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  1369. WindowPadding = ImVec2(0.0f, 0.0f);
  1370. Scroll = ImVec2(0.0f, 0.0f);
  1371. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  1372. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  1373. ScrollbarX = ScrollbarY = false;
  1374. ScrollbarSizes = ImVec2(0.0f, 0.0f);
  1375. BorderSize = 0.0f;
  1376. Active = WasActive = false;
  1377. Accessed = false;
  1378. Collapsed = false;
  1379. SkipItems = false;
  1380. BeginCount = 0;
  1381. PopupID = 0;
  1382. AutoFitFramesX = AutoFitFramesY = -1;
  1383. AutoFitOnlyGrows = false;
  1384. AutoPosLastDirection = -1;
  1385. HiddenFrames = 0;
  1386. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing;
  1387. SetWindowPosCenterWanted = false;
  1388. LastFrameActive = -1;
  1389. ItemWidthDefault = 0.0f;
  1390. FontWindowScale = 1.0f;
  1391. DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList));
  1392. IM_PLACEMENT_NEW(DrawList) ImDrawList();
  1393. DrawList->_OwnerName = Name;
  1394. RootWindow = NULL;
  1395. RootNonPopupWindow = NULL;
  1396. FocusIdxAllCounter = FocusIdxTabCounter = -1;
  1397. FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = IM_INT_MAX;
  1398. FocusIdxAllRequestNext = FocusIdxTabRequestNext = IM_INT_MAX;
  1399. }
  1400. ImGuiWindow::~ImGuiWindow()
  1401. {
  1402. DrawList->~ImDrawList();
  1403. ImGui::MemFree(DrawList);
  1404. DrawList = NULL;
  1405. ImGui::MemFree(Name);
  1406. Name = NULL;
  1407. }
  1408. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  1409. {
  1410. ImGuiID seed = IDStack.back();
  1411. ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1412. ImGui::KeepAliveID(id);
  1413. return id;
  1414. }
  1415. ImGuiID ImGuiWindow::GetID(const void* ptr)
  1416. {
  1417. ImGuiID seed = IDStack.back();
  1418. ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
  1419. ImGui::KeepAliveID(id);
  1420. return id;
  1421. }
  1422. //-----------------------------------------------------------------------------
  1423. // Internal API exposed in imgui_internal.h
  1424. //-----------------------------------------------------------------------------
  1425. static void SetCurrentWindow(ImGuiWindow* window)
  1426. {
  1427. ImGuiState& g = *GImGui;
  1428. g.CurrentWindow = window;
  1429. if (window)
  1430. g.FontSize = window->CalcFontSize();
  1431. }
  1432. ImGuiWindow* ImGui::GetParentWindow()
  1433. {
  1434. ImGuiState& g = *GImGui;
  1435. IM_ASSERT(g.CurrentWindowStack.Size >= 2);
  1436. return g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
  1437. }
  1438. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window = NULL)
  1439. {
  1440. ImGuiState& g = *GImGui;
  1441. g.ActiveId = id;
  1442. g.ActiveIdAllowOverlap = false;
  1443. g.ActiveIdIsJustActivated = true;
  1444. g.ActiveIdWindow = window;
  1445. }
  1446. void ImGui::SetHoveredID(ImGuiID id)
  1447. {
  1448. ImGuiState& g = *GImGui;
  1449. g.HoveredId = id;
  1450. g.HoveredIdAllowOverlap = false;
  1451. }
  1452. void ImGui::KeepAliveID(ImGuiID id)
  1453. {
  1454. ImGuiState& g = *GImGui;
  1455. if (g.ActiveId == id)
  1456. g.ActiveIdIsAlive = true;
  1457. }
  1458. // Advance cursor given item size for layout.
  1459. void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
  1460. {
  1461. ImGuiWindow* window = GetCurrentWindow();
  1462. if (window->SkipItems)
  1463. return;
  1464. // Always align ourselves on pixel boundaries
  1465. ImGuiState& g = *GImGui;
  1466. const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
  1467. const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
  1468. window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
  1469. window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y));
  1470. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  1471. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  1472. //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, 0xFF0000FF, 4); // Debug
  1473. window->DC.PrevLineHeight = line_height;
  1474. window->DC.PrevLineTextBaseOffset = text_base_offset;
  1475. window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
  1476. }
  1477. void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
  1478. {
  1479. ItemSize(bb.GetSize(), text_offset_y);
  1480. }
  1481. // Declare item bounding box for clipping and interaction.
  1482. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  1483. // declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
  1484. bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id)
  1485. {
  1486. ImGuiWindow* window = GetCurrentWindow();
  1487. window->DC.LastItemID = id ? *id : 0;
  1488. window->DC.LastItemRect = bb;
  1489. if (IsClippedEx(bb, id, false))
  1490. {
  1491. window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false;
  1492. return false;
  1493. }
  1494. // This is a sensible default, but widgets are free to override it after calling ItemAdd()
  1495. ImGuiState& g = *GImGui;
  1496. if (IsMouseHoveringRect(bb.Min, bb.Max))
  1497. {
  1498. // Matching the behavior of IsHovered() but ignore if ActiveId==window->MoveID (we clicked on the window background)
  1499. // So that clicking on items with no active id such as Text() still returns true with IsItemHovered()
  1500. window->DC.LastItemHoveredRect = true;
  1501. window->DC.LastItemHoveredAndUsable = false;
  1502. if (g.HoveredRootWindow == window->RootWindow)
  1503. if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveID))
  1504. if (IsWindowContentHoverable(window))
  1505. window->DC.LastItemHoveredAndUsable = true;
  1506. }
  1507. else
  1508. {
  1509. window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false;
  1510. }
  1511. return true;
  1512. }
  1513. bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged)
  1514. {
  1515. ImGuiState& g = *GImGui;
  1516. ImGuiWindow* window = GetCurrentWindowRead();
  1517. if (!bb.Overlaps(window->ClipRect))
  1518. {
  1519. if (!id || *id != GImGui->ActiveId)
  1520. if (clip_even_when_logged || !g.LogEnabled)
  1521. return true;
  1522. }
  1523. return false;
  1524. }
  1525. bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs)
  1526. {
  1527. ImGuiState& g = *GImGui;
  1528. if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap)
  1529. {
  1530. ImGuiWindow* window = GetCurrentWindowRead();
  1531. if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow))
  1532. if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && ImGui::IsMouseHoveringRect(bb.Min, bb.Max))
  1533. if (IsWindowContentHoverable(g.HoveredRootWindow))
  1534. return true;
  1535. }
  1536. return false;
  1537. }
  1538. bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop)
  1539. {
  1540. ImGuiState& g = *GImGui;
  1541. const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus;
  1542. window->FocusIdxAllCounter++;
  1543. if (allow_keyboard_focus)
  1544. window->FocusIdxTabCounter++;
  1545. // Process keyboard input at this point: TAB, Shift-TAB switch focus
  1546. // We can always TAB out of a widget that doesn't allow tabbing in.
  1547. if (tab_stop && window->FocusIdxAllRequestNext == IM_INT_MAX && window->FocusIdxTabRequestNext == IM_INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab))
  1548. {
  1549. // Modulo on index will be applied at the end of frame once we've got the total counter of items.
  1550. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1);
  1551. }
  1552. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
  1553. return true;
  1554. if (allow_keyboard_focus)
  1555. if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
  1556. return true;
  1557. return false;
  1558. }
  1559. void ImGui::FocusableItemUnregister(ImGuiWindow* window)
  1560. {
  1561. window->FocusIdxAllCounter--;
  1562. window->FocusIdxTabCounter--;
  1563. }
  1564. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
  1565. {
  1566. ImGuiState& g = *GImGui;
  1567. ImVec2 content_max;
  1568. if (size.x < 0.0f || size.y < 0.0f)
  1569. content_max = g.CurrentWindow->Pos + ImGui::GetContentRegionMax();
  1570. if (size.x <= 0.0f)
  1571. size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
  1572. if (size.y <= 0.0f)
  1573. size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
  1574. return size;
  1575. }
  1576. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  1577. {
  1578. if (wrap_pos_x < 0.0f)
  1579. return 0.0f;
  1580. ImGuiWindow* window = GetCurrentWindowRead();
  1581. if (wrap_pos_x == 0.0f)
  1582. wrap_pos_x = ImGui::GetContentRegionMax().x + window->Pos.x;
  1583. else if (wrap_pos_x > 0.0f)
  1584. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  1585. const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f;
  1586. return wrap_width;
  1587. }
  1588. //-----------------------------------------------------------------------------
  1589. void* ImGui::MemAlloc(size_t sz)
  1590. {
  1591. GImGui->IO.MetricsAllocs++;
  1592. return GImGui->IO.MemAllocFn(sz);
  1593. }
  1594. void ImGui::MemFree(void* ptr)
  1595. {
  1596. if (ptr) GImGui->IO.MetricsAllocs--;
  1597. return GImGui->IO.MemFreeFn(ptr);
  1598. }
  1599. const char* ImGui::GetClipboardText()
  1600. {
  1601. return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn() : "";
  1602. }
  1603. void ImGui::SetClipboardText(const char* text)
  1604. {
  1605. if (GImGui->IO.SetClipboardTextFn)
  1606. GImGui->IO.SetClipboardTextFn(text);
  1607. }
  1608. const char* ImGui::GetVersion()
  1609. {
  1610. return IMGUI_VERSION;
  1611. }
  1612. // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
  1613. // 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
  1614. void* ImGui::GetInternalState()
  1615. {
  1616. return GImGui;
  1617. }
  1618. size_t ImGui::GetInternalStateSize()
  1619. {
  1620. return sizeof(ImGuiState);
  1621. }
  1622. void ImGui::SetInternalState(void* state, bool construct)
  1623. {
  1624. if (construct)
  1625. IM_PLACEMENT_NEW(state) ImGuiState();
  1626. GImGui = (ImGuiState*)state;
  1627. }
  1628. ImGuiIO& ImGui::GetIO()
  1629. {
  1630. return GImGui->IO;
  1631. }
  1632. ImGuiStyle& ImGui::GetStyle()
  1633. {
  1634. return GImGui->Style;
  1635. }
  1636. // Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
  1637. ImDrawData* ImGui::GetDrawData()
  1638. {
  1639. return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL;
  1640. }
  1641. float ImGui::GetTime()
  1642. {
  1643. return GImGui->Time;
  1644. }
  1645. int ImGui::GetFrameCount()
  1646. {
  1647. return GImGui->FrameCount;
  1648. }
  1649. void ImGui::NewFrame()
  1650. {
  1651. ImGuiState& g = *GImGui;
  1652. // Check user data
  1653. IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues)
  1654. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f);
  1655. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  1656. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  1657. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting
  1658. if (!g.Initialized)
  1659. {
  1660. // Initialize on first frame
  1661. g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer));
  1662. IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer();
  1663. IM_ASSERT(g.Settings.empty());
  1664. LoadSettings();
  1665. g.Initialized = true;
  1666. }
  1667. SetCurrentFont(g.IO.Fonts->Fonts[0]);
  1668. g.Time += g.IO.DeltaTime;
  1669. g.FrameCount += 1;
  1670. g.Tooltip[0] = '\0';
  1671. g.OverlayDrawList.Clear();
  1672. g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
  1673. g.OverlayDrawList.PushClipRectFullScreen();
  1674. g.OverlayDrawList.AddDrawCmd();
  1675. // Mark rendering data as invalid to prevent user who may have a handle on it to use it
  1676. g.RenderDrawData.Valid = false;
  1677. g.RenderDrawData.CmdLists = NULL;
  1678. g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0;
  1679. // Update inputs state
  1680. if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0)
  1681. g.IO.MousePos = ImVec2(-9999.0f, -9999.0f);
  1682. if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta
  1683. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  1684. else
  1685. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  1686. g.IO.MousePosPrev = g.IO.MousePos;
  1687. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  1688. {
  1689. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  1690. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  1691. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  1692. 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;
  1693. g.IO.MouseDoubleClicked[i] = false;
  1694. if (g.IO.MouseClicked[i])
  1695. {
  1696. if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
  1697. {
  1698. if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  1699. g.IO.MouseDoubleClicked[i] = true;
  1700. g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
  1701. }
  1702. else
  1703. {
  1704. g.IO.MouseClickedTime[i] = g.Time;
  1705. }
  1706. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  1707. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  1708. }
  1709. else if (g.IO.MouseDown[i])
  1710. {
  1711. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]));
  1712. }
  1713. }
  1714. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  1715. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  1716. 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;
  1717. // Calculate frame-rate for the user, as a purely luxurious feature
  1718. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  1719. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  1720. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  1721. g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
  1722. // Clear reference to active widget if the widget isn't alive anymore
  1723. g.HoveredIdPreviousFrame = g.HoveredId;
  1724. g.HoveredId = 0;
  1725. g.HoveredIdAllowOverlap = false;
  1726. if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  1727. SetActiveID(0);
  1728. g.ActiveIdPreviousFrame = g.ActiveId;
  1729. g.ActiveIdIsAlive = false;
  1730. g.ActiveIdIsJustActivated = false;
  1731. if (!g.ActiveId)
  1732. g.MovedWindow = NULL;
  1733. // Delay saving settings so we don't spam disk too much
  1734. if (g.SettingsDirtyTimer > 0.0f)
  1735. {
  1736. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  1737. if (g.SettingsDirtyTimer <= 0.0f)
  1738. SaveSettings();
  1739. }
  1740. // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow
  1741. g.HoveredWindow = FindHoveredWindow(g.IO.MousePos, false);
  1742. if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow))
  1743. g.HoveredRootWindow = g.HoveredWindow->RootWindow;
  1744. else
  1745. g.HoveredRootWindow = FindHoveredWindow(g.IO.MousePos, true);
  1746. if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow())
  1747. {
  1748. g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  1749. if (g.HoveredRootWindow != modal_window)
  1750. g.HoveredRootWindow = g.HoveredWindow = NULL;
  1751. }
  1752. else
  1753. {
  1754. g.ModalWindowDarkeningRatio = 0.0f;
  1755. }
  1756. // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application.
  1757. // When clicking outside of a window we assume the click is owned by the application and won't request capture.
  1758. int mouse_earliest_button_down = -1;
  1759. bool mouse_any_down = false;
  1760. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  1761. {
  1762. if (g.IO.MouseClicked[i])
  1763. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenedPopupStack.empty());
  1764. mouse_any_down |= g.IO.MouseDown[i];
  1765. if (g.IO.MouseDown[i])
  1766. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i])
  1767. mouse_earliest_button_down = i;
  1768. }
  1769. bool mouse_owned_by_application = mouse_earliest_button_down != -1 && !g.IO.MouseDownOwned[mouse_earliest_button_down];
  1770. g.IO.WantCaptureMouse = (!mouse_owned_by_application && g.HoveredWindow != NULL) || (!mouse_owned_by_application && mouse_any_down) || (g.ActiveId != 0) || (!g.OpenedPopupStack.empty()) || (g.CaptureMouseNextFrame);
  1771. g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (g.CaptureKeyboardNextFrame);
  1772. g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId);
  1773. g.MouseCursor = ImGuiMouseCursor_Arrow;
  1774. g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = false;
  1775. g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  1776. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  1777. if (mouse_owned_by_application)
  1778. g.HoveredWindow = g.HoveredRootWindow = NULL;
  1779. // Scale & Scrolling
  1780. if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed)
  1781. {
  1782. ImGuiWindow* window = g.HoveredWindow;
  1783. if (g.IO.KeyCtrl)
  1784. {
  1785. if (g.IO.FontAllowUserScaling)
  1786. {
  1787. // Zoom / Scale window
  1788. float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  1789. float scale = new_font_scale / window->FontWindowScale;
  1790. window->FontWindowScale = new_font_scale;
  1791. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  1792. window->Pos += offset;
  1793. window->PosFloat += offset;
  1794. window->Size *= scale;
  1795. window->SizeFull *= scale;
  1796. }
  1797. }
  1798. else
  1799. {
  1800. // Scroll
  1801. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
  1802. {
  1803. const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5;
  1804. SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines);
  1805. }
  1806. }
  1807. }
  1808. // Pressing TAB activate widget focus
  1809. // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus.
  1810. if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
  1811. g.FocusedWindow->FocusIdxTabRequestNext = 0;
  1812. // Mark all windows as not visible
  1813. for (int i = 0; i != g.Windows.Size; i++)
  1814. {
  1815. ImGuiWindow* window = g.Windows[i];
  1816. window->WasActive = window->Active;
  1817. window->Active = false;
  1818. window->Accessed = false;
  1819. }
  1820. // No window should be open at the beginning of the frame.
  1821. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  1822. g.CurrentWindowStack.resize(0);
  1823. g.CurrentPopupStack.resize(0);
  1824. CloseInactivePopups();
  1825. // Create implicit window - we will only render it if the user has added something to it.
  1826. ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver);
  1827. ImGui::Begin("Debug");
  1828. }
  1829. // NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations.
  1830. void ImGui::Shutdown()
  1831. {
  1832. ImGuiState& g = *GImGui;
  1833. // 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)
  1834. if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky.
  1835. g.IO.Fonts->Clear();
  1836. // Cleanup of other data are conditional on actually having used ImGui.
  1837. if (!g.Initialized)
  1838. return;
  1839. SaveSettings();
  1840. for (int i = 0; i < g.Windows.Size; i++)
  1841. {
  1842. g.Windows[i]->~ImGuiWindow();
  1843. ImGui::MemFree(g.Windows[i]);
  1844. }
  1845. g.Windows.clear();
  1846. g.WindowsSortBuffer.clear();
  1847. g.CurrentWindowStack.clear();
  1848. g.FocusedWindow = NULL;
  1849. g.HoveredWindow = NULL;
  1850. g.HoveredRootWindow = NULL;
  1851. for (int i = 0; i < g.Settings.Size; i++)
  1852. ImGui::MemFree(g.Settings[i].Name);
  1853. g.Settings.clear();
  1854. g.ColorModifiers.clear();
  1855. g.StyleModifiers.clear();
  1856. g.FontStack.clear();
  1857. g.OpenedPopupStack.clear();
  1858. g.CurrentPopupStack.clear();
  1859. for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  1860. g.RenderDrawLists[i].clear();
  1861. g.OverlayDrawList.ClearFreeMemory();
  1862. g.ColorEditModeStorage.Clear();
  1863. if (g.PrivateClipboard)
  1864. {
  1865. ImGui::MemFree(g.PrivateClipboard);
  1866. g.PrivateClipboard = NULL;
  1867. }
  1868. g.InputTextState.Text.clear();
  1869. g.InputTextState.InitialText.clear();
  1870. g.InputTextState.TempTextBuffer.clear();
  1871. if (g.LogFile && g.LogFile != stdout)
  1872. {
  1873. fclose(g.LogFile);
  1874. g.LogFile = NULL;
  1875. }
  1876. if (g.LogClipboard)
  1877. {
  1878. g.LogClipboard->~ImGuiTextBuffer();
  1879. ImGui::MemFree(g.LogClipboard);
  1880. }
  1881. g.Initialized = false;
  1882. }
  1883. static ImGuiIniData* FindWindowSettings(const char* name)
  1884. {
  1885. ImGuiState& g = *GImGui;
  1886. ImGuiID id = ImHash(name, 0);
  1887. for (int i = 0; i != g.Settings.Size; i++)
  1888. {
  1889. ImGuiIniData* ini = &g.Settings[i];
  1890. if (ini->ID == id)
  1891. return ini;
  1892. }
  1893. return NULL;
  1894. }
  1895. static ImGuiIniData* AddWindowSettings(const char* name)
  1896. {
  1897. GImGui->Settings.resize(GImGui->Settings.Size + 1);
  1898. ImGuiIniData* ini = &GImGui->Settings.back();
  1899. ini->Name = ImStrdup(name);
  1900. ini->ID = ImHash(name, 0);
  1901. ini->Collapsed = false;
  1902. ini->Pos = ImVec2(FLT_MAX,FLT_MAX);
  1903. ini->Size = ImVec2(0,0);
  1904. return ini;
  1905. }
  1906. // Zero-tolerance, poor-man .ini parsing
  1907. // FIXME: Write something less rubbish
  1908. static void LoadSettings()
  1909. {
  1910. ImGuiState& g = *GImGui;
  1911. const char* filename = g.IO.IniFilename;
  1912. if (!filename)
  1913. return;
  1914. int file_size;
  1915. char* file_data = (char*)ImLoadFileToMemory(filename, "rb", &file_size, 1);
  1916. if (!file_data)
  1917. return;
  1918. ImGuiIniData* settings = NULL;
  1919. const char* buf_end = file_data + file_size;
  1920. for (const char* line_start = file_data; line_start < buf_end; )
  1921. {
  1922. const char* line_end = line_start;
  1923. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  1924. line_end++;
  1925. if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']')
  1926. {
  1927. char name[64];
  1928. ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1);
  1929. settings = FindWindowSettings(name);
  1930. if (!settings)
  1931. settings = AddWindowSettings(name);
  1932. }
  1933. else if (settings)
  1934. {
  1935. float x, y;
  1936. int i;
  1937. if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2)
  1938. settings->Pos = ImVec2(x, y);
  1939. else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2)
  1940. settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
  1941. else if (sscanf(line_start, "Collapsed=%d", &i) == 1)
  1942. settings->Collapsed = (i != 0);
  1943. }
  1944. line_start = line_end+1;
  1945. }
  1946. ImGui::MemFree(file_data);
  1947. }
  1948. static void SaveSettings()
  1949. {
  1950. ImGuiState& g = *GImGui;
  1951. const char* filename = g.IO.IniFilename;
  1952. if (!filename)
  1953. return;
  1954. // Gather data from windows that were active during this session
  1955. for (int i = 0; i != g.Windows.Size; i++)
  1956. {
  1957. ImGuiWindow* window = g.Windows[i];
  1958. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  1959. continue;
  1960. ImGuiIniData* settings = FindWindowSettings(window->Name);
  1961. settings->Pos = window->Pos;
  1962. settings->Size = window->SizeFull;
  1963. settings->Collapsed = window->Collapsed;
  1964. }
  1965. // Write .ini file
  1966. // If a window wasn't opened in this session we preserve its settings
  1967. FILE* f = fopen(filename, "wt");
  1968. if (!f)
  1969. return;
  1970. for (int i = 0; i != g.Settings.Size; i++)
  1971. {
  1972. const ImGuiIniData* settings = &g.Settings[i];
  1973. if (settings->Pos.x == FLT_MAX)
  1974. continue;
  1975. const char* name = settings->Name;
  1976. if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  1977. name = p;
  1978. fprintf(f, "[%s]\n", name);
  1979. fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
  1980. fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
  1981. fprintf(f, "Collapsed=%d\n", settings->Collapsed);
  1982. fprintf(f, "\n");
  1983. }
  1984. fclose(f);
  1985. }
  1986. static void MarkSettingsDirty()
  1987. {
  1988. ImGuiState& g = *GImGui;
  1989. if (g.SettingsDirtyTimer <= 0.0f)
  1990. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  1991. }
  1992. // FIXME: Add a more explicit sort order in the window structure.
  1993. static int ChildWindowComparer(const void* lhs, const void* rhs)
  1994. {
  1995. const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
  1996. const ImGuiWindow* b = *(const ImGuiWindow**)rhs;
  1997. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  1998. return d;
  1999. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  2000. return d;
  2001. if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox))
  2002. return d;
  2003. return 0;
  2004. }
  2005. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window)
  2006. {
  2007. out_sorted_windows.push_back(window);
  2008. if (window->Active)
  2009. {
  2010. int count = window->DC.ChildWindows.Size;
  2011. if (count > 1)
  2012. qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  2013. for (int i = 0; i < count; i++)
  2014. {
  2015. ImGuiWindow* child = window->DC.ChildWindows[i];
  2016. if (child->Active)
  2017. AddWindowToSortedBuffer(out_sorted_windows, child);
  2018. }
  2019. }
  2020. }
  2021. static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list)
  2022. {
  2023. if (draw_list->CmdBuffer.empty())
  2024. return;
  2025. // Remove trailing command if unused
  2026. ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
  2027. if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
  2028. {
  2029. draw_list->CmdBuffer.pop_back();
  2030. if (draw_list->CmdBuffer.empty())
  2031. return;
  2032. }
  2033. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices)
  2034. // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly.
  2035. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); // Sanity check. Bug or mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
  2036. IM_ASSERT((unsigned long long int)draw_list->_VtxCurrentIdx <= ((unsigned long long int)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above.
  2037. out_render_list.push_back(draw_list);
  2038. GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size;
  2039. GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size;
  2040. }
  2041. static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window)
  2042. {
  2043. AddDrawListToRenderList(out_render_list, window->DrawList);
  2044. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  2045. {
  2046. ImGuiWindow* child = window->DC.ChildWindows[i];
  2047. if (!child->Active) // clipped children may have been marked not active
  2048. continue;
  2049. if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0)
  2050. continue;
  2051. AddWindowToRenderList(out_render_list, child);
  2052. }
  2053. }
  2054. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_existing_clip_rect)
  2055. {
  2056. ImGuiWindow* window = GetCurrentWindow();
  2057. ImRect cr(clip_rect_min, clip_rect_max);
  2058. if (intersect_with_existing_clip_rect)
  2059. {
  2060. // Clip our argument with the current clip rect
  2061. cr.Clip(window->ClipRect);
  2062. }
  2063. cr.Max.x = ImMax(cr.Min.x, cr.Max.x);
  2064. cr.Max.y = ImMax(cr.Min.y, cr.Max.y);
  2065. IM_ASSERT(cr.Min.x <= cr.Max.x && cr.Min.y <= cr.Max.y);
  2066. window->ClipRect = cr;
  2067. window->DrawList->PushClipRect(ImVec4(cr.Min.x, cr.Min.y, cr.Max.x, cr.Max.y));
  2068. }
  2069. void ImGui::PopClipRect()
  2070. {
  2071. ImGuiWindow* window = GetCurrentWindow();
  2072. window->DrawList->PopClipRect();
  2073. window->ClipRect = window->DrawList->_ClipRectStack.back();
  2074. }
  2075. // 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.
  2076. void ImGui::EndFrame()
  2077. {
  2078. ImGuiState& g = *GImGui;
  2079. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2080. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again
  2081. // Render tooltip
  2082. if (g.Tooltip[0])
  2083. {
  2084. ImGui::BeginTooltip();
  2085. ImGui::TextUnformatted(g.Tooltip);
  2086. ImGui::EndTooltip();
  2087. }
  2088. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  2089. if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
  2090. {
  2091. g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
  2092. g.OsImePosSet = g.OsImePosRequest;
  2093. }
  2094. // Hide implicit "Debug" window if it hasn't been used
  2095. IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
  2096. if (g.CurrentWindow && !g.CurrentWindow->Accessed)
  2097. g.CurrentWindow->Active = false;
  2098. ImGui::End();
  2099. // Click to focus window and start moving (after we're done with all our widgets)
  2100. if (!g.ActiveId)
  2101. g.MovedWindow = NULL;
  2102. if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0])
  2103. {
  2104. if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear
  2105. {
  2106. if (g.HoveredRootWindow != NULL)
  2107. {
  2108. FocusWindow(g.HoveredWindow);
  2109. if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove))
  2110. {
  2111. g.MovedWindow = g.HoveredWindow;
  2112. SetActiveID(g.HoveredRootWindow->MoveID, g.HoveredRootWindow);
  2113. }
  2114. }
  2115. else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL)
  2116. {
  2117. // Clicking on void disable focus
  2118. FocusWindow(NULL);
  2119. }
  2120. }
  2121. }
  2122. // Sort the window list so that all child windows are after their parent
  2123. // We cannot do that on FocusWindow() because childs may not exist yet
  2124. g.WindowsSortBuffer.resize(0);
  2125. g.WindowsSortBuffer.reserve(g.Windows.Size);
  2126. for (int i = 0; i != g.Windows.Size; i++)
  2127. {
  2128. ImGuiWindow* window = g.Windows[i];
  2129. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  2130. continue;
  2131. AddWindowToSortedBuffer(g.WindowsSortBuffer, window);
  2132. }
  2133. IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
  2134. g.Windows.swap(g.WindowsSortBuffer);
  2135. // Clear Input data for next frame
  2136. g.IO.MouseWheel = 0.0f;
  2137. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  2138. g.FrameCountEnded = g.FrameCount;
  2139. }
  2140. void ImGui::Render()
  2141. {
  2142. ImGuiState& g = *GImGui;
  2143. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2144. if (g.FrameCountEnded != g.FrameCount)
  2145. ImGui::EndFrame();
  2146. g.FrameCountRendered = g.FrameCount;
  2147. // Skip render altogether if alpha is 0.0
  2148. // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false.
  2149. if (g.Style.Alpha > 0.0f)
  2150. {
  2151. // Gather windows to render
  2152. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
  2153. for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2154. g.RenderDrawLists[i].resize(0);
  2155. for (int i = 0; i != g.Windows.Size; i++)
  2156. {
  2157. ImGuiWindow* window = g.Windows[i];
  2158. if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
  2159. {
  2160. // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, ..
  2161. g.IO.MetricsActiveWindows++;
  2162. if (window->Flags & ImGuiWindowFlags_Popup)
  2163. AddWindowToRenderList(g.RenderDrawLists[1], window);
  2164. else if (window->Flags & ImGuiWindowFlags_Tooltip)
  2165. AddWindowToRenderList(g.RenderDrawLists[2], window);
  2166. else
  2167. AddWindowToRenderList(g.RenderDrawLists[0], window);
  2168. }
  2169. }
  2170. // Flatten layers
  2171. int n = g.RenderDrawLists[0].Size;
  2172. int flattened_size = n;
  2173. for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2174. flattened_size += g.RenderDrawLists[i].Size;
  2175. g.RenderDrawLists[0].resize(flattened_size);
  2176. for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2177. {
  2178. ImVector<ImDrawList*>& layer = g.RenderDrawLists[i];
  2179. if (layer.empty())
  2180. continue;
  2181. memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  2182. n += layer.Size;
  2183. }
  2184. // Draw software mouse cursor if requested
  2185. if (g.IO.MouseDrawCursor)
  2186. {
  2187. const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor];
  2188. const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset;
  2189. const ImVec2 size = cursor_data.Size;
  2190. const ImTextureID tex_id = g.IO.Fonts->TexID;
  2191. g.OverlayDrawList.PushTextureID(tex_id);
  2192. g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow
  2193. g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow
  2194. g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0xFF000000); // Black border
  2195. g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], 0xFFFFFFFF); // White fill
  2196. g.OverlayDrawList.PopTextureID();
  2197. }
  2198. if (!g.OverlayDrawList.VtxBuffer.empty())
  2199. AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList);
  2200. // Setup draw data
  2201. g.RenderDrawData.Valid = true;
  2202. g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL;
  2203. g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size;
  2204. g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices;
  2205. g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices;
  2206. // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
  2207. if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
  2208. g.IO.RenderDrawListsFn(&g.RenderDrawData);
  2209. }
  2210. }
  2211. // Find the optional ## from which we stop displaying text.
  2212. static const char* FindTextDisplayEnd(const char* text, const char* text_end)
  2213. {
  2214. const char* text_display_end = text;
  2215. if (!text_end)
  2216. text_end = (const char*)-1;
  2217. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2218. text_display_end++;
  2219. return text_display_end;
  2220. }
  2221. // Pass text data straight to log (without being displayed)
  2222. void ImGui::LogText(const char* fmt, ...)
  2223. {
  2224. ImGuiState& g = *GImGui;
  2225. if (!g.LogEnabled)
  2226. return;
  2227. va_list args;
  2228. va_start(args, fmt);
  2229. if (g.LogFile)
  2230. {
  2231. vfprintf(g.LogFile, fmt, args);
  2232. }
  2233. else
  2234. {
  2235. g.LogClipboard->appendv(fmt, args);
  2236. }
  2237. va_end(args);
  2238. }
  2239. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  2240. // We split text into individual lines to add current tree level padding
  2241. static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end)
  2242. {
  2243. ImGuiState& g = *GImGui;
  2244. ImGuiWindow* window = ImGui::GetCurrentWindowRead();
  2245. if (!text_end)
  2246. text_end = FindTextDisplayEnd(text, text_end);
  2247. const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1;
  2248. window->DC.LogLinePosY = ref_pos.y;
  2249. const char* text_remaining = text;
  2250. if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
  2251. g.LogStartDepth = window->DC.TreeDepth;
  2252. const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
  2253. for (;;)
  2254. {
  2255. // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
  2256. const char* line_end = text_remaining;
  2257. while (line_end < text_end)
  2258. if (*line_end == '\n')
  2259. break;
  2260. else
  2261. line_end++;
  2262. if (line_end >= text_end)
  2263. line_end = NULL;
  2264. const bool is_first_line = (text == text_remaining);
  2265. bool is_last_line = false;
  2266. if (line_end == NULL)
  2267. {
  2268. is_last_line = true;
  2269. line_end = text_end;
  2270. }
  2271. if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
  2272. {
  2273. const int char_count = (int)(line_end - text_remaining);
  2274. if (log_new_line || !is_first_line)
  2275. ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining);
  2276. else
  2277. ImGui::LogText(" %.*s", char_count, text_remaining);
  2278. }
  2279. if (is_last_line)
  2280. break;
  2281. text_remaining = line_end + 1;
  2282. }
  2283. }
  2284. // Internal ImGui functions to render text
  2285. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  2286. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  2287. {
  2288. ImGuiState& g = *GImGui;
  2289. ImGuiWindow* window = GetCurrentWindow();
  2290. // Hide anything after a '##' string
  2291. const char* text_display_end;
  2292. if (hide_text_after_hash)
  2293. {
  2294. text_display_end = FindTextDisplayEnd(text, text_end);
  2295. }
  2296. else
  2297. {
  2298. if (!text_end)
  2299. text_end = text + strlen(text); // FIXME-OPT
  2300. text_display_end = text_end;
  2301. }
  2302. const int text_len = (int)(text_display_end - text);
  2303. if (text_len > 0)
  2304. {
  2305. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  2306. if (g.LogEnabled)
  2307. LogRenderedText(pos, text, text_display_end);
  2308. }
  2309. }
  2310. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  2311. {
  2312. ImGuiState& g = *GImGui;
  2313. ImGuiWindow* window = GetCurrentWindow();
  2314. if (!text_end)
  2315. text_end = text + strlen(text); // FIXME-OPT
  2316. const int text_len = (int)(text_end - text);
  2317. if (text_len > 0)
  2318. {
  2319. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  2320. if (g.LogEnabled)
  2321. LogRenderedText(pos, text, text_end);
  2322. }
  2323. }
  2324. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  2325. void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, ImGuiAlign align, const ImVec2* clip_min, const ImVec2* clip_max)
  2326. {
  2327. // Hide anything after a '##' string
  2328. const char* text_display_end = FindTextDisplayEnd(text, text_end);
  2329. const int text_len = (int)(text_display_end - text);
  2330. if (text_len == 0)
  2331. return;
  2332. ImGuiState& g = *GImGui;
  2333. ImGuiWindow* window = GetCurrentWindow();
  2334. // Perform CPU side clipping for single clipped element to avoid using scissor state
  2335. ImVec2 pos = pos_min;
  2336. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : ImGui::CalcTextSize(text, text_display_end, false, 0.0f);
  2337. if (!clip_max) clip_max = &pos_max;
  2338. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  2339. if (!clip_min) clip_min = &pos_min; else need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  2340. // Align
  2341. if (align & ImGuiAlign_Center) pos.x = ImMax(pos.x, (pos.x + pos_max.x - text_size.x) * 0.5f);
  2342. else if (align & ImGuiAlign_Right) pos.x = ImMax(pos.x, pos_max.x - text_size.x);
  2343. if (align & ImGuiAlign_VCenter) pos.y = ImMax(pos.y, (pos.y + pos_max.y - text_size.y) * 0.5f);
  2344. // Render
  2345. if (need_clipping)
  2346. {
  2347. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  2348. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  2349. }
  2350. else
  2351. {
  2352. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2353. }
  2354. if (g.LogEnabled)
  2355. LogRenderedText(pos, text, text_display_end);
  2356. }
  2357. // Render a rectangle shaped with optional rounding and borders
  2358. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2359. {
  2360. ImGuiWindow* window = GetCurrentWindow();
  2361. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2362. if (border && (window->Flags & ImGuiWindowFlags_ShowBorders))
  2363. {
  2364. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding);
  2365. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding);
  2366. }
  2367. }
  2368. // Render a triangle to denote expanded/collapsed state
  2369. void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool shadow)
  2370. {
  2371. ImGuiState& g = *GImGui;
  2372. ImGuiWindow* window = GetCurrentWindow();
  2373. const float h = g.FontSize * 1.00f;
  2374. const float r = h * 0.40f * scale;
  2375. ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale);
  2376. ImVec2 a, b, c;
  2377. if (opened)
  2378. {
  2379. center.y -= r*0.25f;
  2380. a = center + ImVec2(0,1)*r;
  2381. b = center + ImVec2(-0.866f,-0.5f)*r;
  2382. c = center + ImVec2(0.866f,-0.5f)*r;
  2383. }
  2384. else
  2385. {
  2386. a = center + ImVec2(1,0)*r;
  2387. b = center + ImVec2(-0.500f,0.866f)*r;
  2388. c = center + ImVec2(-0.500f,-0.866f)*r;
  2389. }
  2390. if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0)
  2391. window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), GetColorU32(ImGuiCol_BorderShadow));
  2392. window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text));
  2393. }
  2394. void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col)
  2395. {
  2396. ImGuiState& g = *GImGui;
  2397. ImGuiWindow* window = GetCurrentWindow();
  2398. ImVec2 a, b, c;
  2399. float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f);
  2400. float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f);
  2401. a.x = pos.x + 0.5f + start_x;
  2402. b.x = a.x + rem_third;
  2403. c.x = a.x + rem_third * 3.0f;
  2404. b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y);
  2405. a.y = b.y - rem_third;
  2406. c.y = b.y - rem_third * 2.0f;
  2407. window->DrawList->PathLineTo(a);
  2408. window->DrawList->PathLineTo(b);
  2409. window->DrawList->PathLineTo(c);
  2410. window->DrawList->PathStroke(col, false);
  2411. }
  2412. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  2413. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
  2414. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  2415. {
  2416. ImGuiState& g = *GImGui;
  2417. const char* text_display_end;
  2418. if (hide_text_after_double_hash)
  2419. text_display_end = FindTextDisplayEnd(text, text_end); // Hide anything after a '##' string
  2420. else
  2421. text_display_end = text_end;
  2422. ImFont* font = g.Font;
  2423. const float font_size = g.FontSize;
  2424. if (text == text_display_end)
  2425. return ImVec2(0.0f, font_size);
  2426. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  2427. // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field)
  2428. const float font_scale = font_size / font->FontSize;
  2429. const float character_spacing_x = 1.0f * font_scale;
  2430. if (text_size.x > 0.0f)
  2431. text_size.x -= character_spacing_x;
  2432. text_size.x = (float)(int)(text_size.x + 0.95f);
  2433. return text_size;
  2434. }
  2435. // Helper to calculate coarse clipping of large list of evenly sized items.
  2436. // NB: Prefer using the ImGuiListClipper higher-level helper if you can!
  2437. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  2438. // If you are displaying thousands of items and you have a random access to the list, you can perform clipping yourself to save on CPU.
  2439. // {
  2440. // float item_height = ImGui::GetTextLineHeightWithSpacing();
  2441. // int display_start, display_end;
  2442. // ImGui::CalcListClipping(count, item_height, &display_start, &display_end); // calculate how many to clip/display
  2443. // ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (display_start) * item_height); // advance cursor
  2444. // for (int i = display_start; i < display_end; i++) // display only visible items
  2445. // // TODO: display visible item
  2446. // ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (count - display_end) * item_height); // advance cursor
  2447. // }
  2448. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  2449. {
  2450. ImGuiState& g = *GImGui;
  2451. ImGuiWindow* window = GetCurrentWindowRead();
  2452. if (g.LogEnabled)
  2453. {
  2454. // If logging is active, do not perform any clipping
  2455. *out_items_display_start = 0;
  2456. *out_items_display_end = items_count;
  2457. return;
  2458. }
  2459. const ImVec2 pos = window->DC.CursorPos;
  2460. int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
  2461. int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
  2462. start = ImClamp(start, 0, items_count);
  2463. end = ImClamp(end + 1, start, items_count);
  2464. *out_items_display_start = start;
  2465. *out_items_display_end = end;
  2466. }
  2467. // Find window given position, search front-to-back
  2468. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs)
  2469. {
  2470. ImGuiState& g = *GImGui;
  2471. for (int i = g.Windows.Size-1; i >= 0; i--)
  2472. {
  2473. ImGuiWindow* window = g.Windows[i];
  2474. if (!window->Active)
  2475. continue;
  2476. if (window->Flags & ImGuiWindowFlags_NoInputs)
  2477. continue;
  2478. if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0)
  2479. continue;
  2480. // Using the clipped AABB so a child window will typically be clipped by its parent.
  2481. ImRect bb(window->ClippedWindowRect.Min - g.Style.TouchExtraPadding, window->ClippedWindowRect.Max + g.Style.TouchExtraPadding);
  2482. if (bb.Contains(pos))
  2483. return window;
  2484. }
  2485. return NULL;
  2486. }
  2487. // Test if mouse cursor is hovering given rectangle
  2488. // NB- Rectangle is clipped by our current clip setting
  2489. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  2490. bool ImGui::IsMouseHoveringRect(const ImVec2& pos_min, const ImVec2& pos_max, bool clip)
  2491. {
  2492. ImGuiState& g = *GImGui;
  2493. ImGuiWindow* window = GetCurrentWindowRead();
  2494. // Clip
  2495. ImRect rect_clipped(pos_min, pos_max);
  2496. if (clip)
  2497. rect_clipped.Clip(window->ClipRect);
  2498. // Expand for touch input
  2499. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  2500. return rect_for_touch.Contains(g.IO.MousePos);
  2501. }
  2502. bool ImGui::IsMouseHoveringWindow()
  2503. {
  2504. ImGuiState& g = *GImGui;
  2505. return g.HoveredWindow == g.CurrentWindow;
  2506. }
  2507. bool ImGui::IsMouseHoveringAnyWindow()
  2508. {
  2509. ImGuiState& g = *GImGui;
  2510. return g.HoveredWindow != NULL;
  2511. }
  2512. bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos)
  2513. {
  2514. return FindHoveredWindow(pos, false) != NULL;
  2515. }
  2516. static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
  2517. {
  2518. const int key_index = GImGui->IO.KeyMap[key];
  2519. return ImGui::IsKeyPressed(key_index, repeat);
  2520. }
  2521. int ImGui::GetKeyIndex(ImGuiKey key)
  2522. {
  2523. IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT);
  2524. return GImGui->IO.KeyMap[key];
  2525. }
  2526. bool ImGui::IsKeyDown(int key_index)
  2527. {
  2528. if (key_index < 0) return false;
  2529. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
  2530. return GImGui->IO.KeysDown[key_index];
  2531. }
  2532. bool ImGui::IsKeyPressed(int key_index, bool repeat)
  2533. {
  2534. ImGuiState& g = *GImGui;
  2535. if (key_index < 0) return false;
  2536. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  2537. const float t = g.IO.KeysDownDuration[key_index];
  2538. if (t == 0.0f)
  2539. return true;
  2540. if (repeat && t > g.IO.KeyRepeatDelay)
  2541. {
  2542. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  2543. if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  2544. return true;
  2545. }
  2546. return false;
  2547. }
  2548. bool ImGui::IsKeyReleased(int key_index)
  2549. {
  2550. ImGuiState& g = *GImGui;
  2551. if (key_index < 0) return false;
  2552. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  2553. if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index])
  2554. return true;
  2555. return false;
  2556. }
  2557. bool ImGui::IsMouseDown(int button)
  2558. {
  2559. ImGuiState& g = *GImGui;
  2560. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  2561. return g.IO.MouseDown[button];
  2562. }
  2563. bool ImGui::IsMouseClicked(int button, bool repeat)
  2564. {
  2565. ImGuiState& g = *GImGui;
  2566. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  2567. const float t = g.IO.MouseDownDuration[button];
  2568. if (t == 0.0f)
  2569. return true;
  2570. if (repeat && t > g.IO.KeyRepeatDelay)
  2571. {
  2572. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  2573. if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  2574. return true;
  2575. }
  2576. return false;
  2577. }
  2578. bool ImGui::IsMouseReleased(int button)
  2579. {
  2580. ImGuiState& g = *GImGui;
  2581. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  2582. return g.IO.MouseReleased[button];
  2583. }
  2584. bool ImGui::IsMouseDoubleClicked(int button)
  2585. {
  2586. ImGuiState& g = *GImGui;
  2587. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  2588. return g.IO.MouseDoubleClicked[button];
  2589. }
  2590. bool ImGui::IsMouseDragging(int button, float lock_threshold)
  2591. {
  2592. ImGuiState& g = *GImGui;
  2593. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  2594. if (!g.IO.MouseDown[button])
  2595. return false;
  2596. if (lock_threshold < 0.0f)
  2597. lock_threshold = g.IO.MouseDragThreshold;
  2598. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  2599. }
  2600. ImVec2 ImGui::GetMousePos()
  2601. {
  2602. return GImGui->IO.MousePos;
  2603. }
  2604. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  2605. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  2606. {
  2607. ImGuiState& g = *GImGui;
  2608. if (g.CurrentPopupStack.Size > 0)
  2609. return g.OpenedPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen;
  2610. return g.IO.MousePos;
  2611. }
  2612. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
  2613. {
  2614. ImGuiState& g = *GImGui;
  2615. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  2616. if (lock_threshold < 0.0f)
  2617. lock_threshold = g.IO.MouseDragThreshold;
  2618. if (g.IO.MouseDown[button])
  2619. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  2620. return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
  2621. return ImVec2(0.0f, 0.0f);
  2622. }
  2623. void ImGui::ResetMouseDragDelta(int button)
  2624. {
  2625. ImGuiState& g = *GImGui;
  2626. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  2627. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  2628. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  2629. }
  2630. ImGuiMouseCursor ImGui::GetMouseCursor()
  2631. {
  2632. return GImGui->MouseCursor;
  2633. }
  2634. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  2635. {
  2636. GImGui->MouseCursor = cursor_type;
  2637. }
  2638. void ImGui::CaptureKeyboardFromApp()
  2639. {
  2640. GImGui->CaptureKeyboardNextFrame = true;
  2641. }
  2642. void ImGui::CaptureMouseFromApp()
  2643. {
  2644. GImGui->CaptureMouseNextFrame = true;
  2645. }
  2646. bool ImGui::IsItemHovered()
  2647. {
  2648. ImGuiWindow* window = GetCurrentWindowRead();
  2649. return window->DC.LastItemHoveredAndUsable;
  2650. }
  2651. bool ImGui::IsItemHoveredRect()
  2652. {
  2653. ImGuiWindow* window = GetCurrentWindowRead();
  2654. return window->DC.LastItemHoveredRect;
  2655. }
  2656. bool ImGui::IsItemActive()
  2657. {
  2658. ImGuiState& g = *GImGui;
  2659. if (g.ActiveId)
  2660. {
  2661. ImGuiWindow* window = GetCurrentWindowRead();
  2662. return g.ActiveId == window->DC.LastItemID;
  2663. }
  2664. return false;
  2665. }
  2666. bool ImGui::IsAnyItemHovered()
  2667. {
  2668. return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0;
  2669. }
  2670. bool ImGui::IsAnyItemActive()
  2671. {
  2672. return GImGui->ActiveId != 0;
  2673. }
  2674. bool ImGui::IsItemVisible()
  2675. {
  2676. ImGuiWindow* window = GetCurrentWindowRead();
  2677. ImRect r(window->ClipRect);
  2678. return r.Overlaps(window->DC.LastItemRect);
  2679. }
  2680. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  2681. void ImGui::SetItemAllowOverlap()
  2682. {
  2683. ImGuiState& g = *GImGui;
  2684. if (g.HoveredId == g.CurrentWindow->DC.LastItemID)
  2685. g.HoveredIdAllowOverlap = true;
  2686. if (g.ActiveId == g.CurrentWindow->DC.LastItemID)
  2687. g.ActiveIdAllowOverlap = true;
  2688. }
  2689. ImVec2 ImGui::GetItemRectMin()
  2690. {
  2691. ImGuiWindow* window = GetCurrentWindowRead();
  2692. return window->DC.LastItemRect.Min;
  2693. }
  2694. ImVec2 ImGui::GetItemRectMax()
  2695. {
  2696. ImGuiWindow* window = GetCurrentWindowRead();
  2697. return window->DC.LastItemRect.Max;
  2698. }
  2699. ImVec2 ImGui::GetItemRectSize()
  2700. {
  2701. ImGuiWindow* window = GetCurrentWindowRead();
  2702. return window->DC.LastItemRect.GetSize();
  2703. }
  2704. ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward)
  2705. {
  2706. ImGuiWindow* window = GetCurrentWindowRead();
  2707. ImRect rect = window->DC.LastItemRect;
  2708. rect.Expand(outward);
  2709. return rect.GetClosestPoint(pos, on_edge);
  2710. }
  2711. // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value.
  2712. void ImGui::SetTooltipV(const char* fmt, va_list args)
  2713. {
  2714. ImGuiState& g = *GImGui;
  2715. ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args);
  2716. }
  2717. void ImGui::SetTooltip(const char* fmt, ...)
  2718. {
  2719. va_list args;
  2720. va_start(args, fmt);
  2721. SetTooltipV(fmt, args);
  2722. va_end(args);
  2723. }
  2724. static ImRect GetVisibleRect()
  2725. {
  2726. ImGuiState& g = *GImGui;
  2727. if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
  2728. return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
  2729. return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
  2730. }
  2731. void ImGui::BeginTooltip()
  2732. {
  2733. ImGuiState& g = *GImGui;
  2734. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
  2735. ImGui::Begin("##Tooltip", NULL, ImVec2(0,0), g.Style.Colors[ImGuiCol_TooltipBg].w, flags);
  2736. }
  2737. void ImGui::EndTooltip()
  2738. {
  2739. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  2740. ImGui::End();
  2741. }
  2742. static bool IsPopupOpen(ImGuiID id)
  2743. {
  2744. ImGuiState& g = *GImGui;
  2745. const bool opened = g.OpenedPopupStack.Size > g.CurrentPopupStack.Size && g.OpenedPopupStack[g.CurrentPopupStack.Size].PopupID == id;
  2746. return opened;
  2747. }
  2748. // Mark popup as open (toggle toward open state).
  2749. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  2750. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  2751. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  2752. void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing)
  2753. {
  2754. ImGuiState& g = *GImGui;
  2755. ImGuiWindow* window = g.CurrentWindow;
  2756. ImGuiID id = window->GetID(str_id);
  2757. int current_stack_size = g.CurrentPopupStack.Size;
  2758. ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here)
  2759. if (g.OpenedPopupStack.Size < current_stack_size + 1)
  2760. g.OpenedPopupStack.push_back(popup_ref);
  2761. else if (reopen_existing || g.OpenedPopupStack[current_stack_size].PopupID != id)
  2762. {
  2763. g.OpenedPopupStack.resize(current_stack_size+1);
  2764. g.OpenedPopupStack[current_stack_size] = popup_ref;
  2765. }
  2766. }
  2767. void ImGui::OpenPopup(const char* str_id)
  2768. {
  2769. ImGui::OpenPopupEx(str_id, false);
  2770. }
  2771. static void CloseInactivePopups()
  2772. {
  2773. ImGuiState& g = *GImGui;
  2774. if (g.OpenedPopupStack.empty())
  2775. return;
  2776. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  2777. // Don't close our own child popup windows
  2778. int n = 0;
  2779. if (g.FocusedWindow)
  2780. {
  2781. for (n = 0; n < g.OpenedPopupStack.Size; n++)
  2782. {
  2783. ImGuiPopupRef& popup = g.OpenedPopupStack[n];
  2784. if (!popup.Window)
  2785. continue;
  2786. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  2787. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  2788. continue;
  2789. bool has_focus = false;
  2790. for (int m = n; m < g.OpenedPopupStack.Size && !has_focus; m++)
  2791. has_focus = (g.OpenedPopupStack[m].Window && g.OpenedPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow);
  2792. if (!has_focus)
  2793. break;
  2794. }
  2795. }
  2796. if (n < g.OpenedPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below
  2797. g.OpenedPopupStack.resize(n);
  2798. }
  2799. static ImGuiWindow* GetFrontMostModalRootWindow()
  2800. {
  2801. ImGuiState& g = *GImGui;
  2802. if (!g.OpenedPopupStack.empty())
  2803. if (ImGuiWindow* front_most_popup = g.OpenedPopupStack.back().Window)
  2804. if (front_most_popup->Flags & ImGuiWindowFlags_Modal)
  2805. return front_most_popup;
  2806. return NULL;
  2807. }
  2808. static void ClosePopupToLevel(int remaining)
  2809. {
  2810. ImGuiState& g = *GImGui;
  2811. if (remaining > 0)
  2812. ImGui::FocusWindow(g.OpenedPopupStack[remaining-1].Window);
  2813. else
  2814. ImGui::FocusWindow(g.OpenedPopupStack[0].ParentWindow);
  2815. g.OpenedPopupStack.resize(remaining);
  2816. }
  2817. static void ClosePopup(ImGuiID id)
  2818. {
  2819. if (!IsPopupOpen(id))
  2820. return;
  2821. ImGuiState& g = *GImGui;
  2822. ClosePopupToLevel(g.OpenedPopupStack.Size - 1);
  2823. }
  2824. // Close the popup we have begin-ed into.
  2825. void ImGui::CloseCurrentPopup()
  2826. {
  2827. ImGuiState& g = *GImGui;
  2828. int popup_idx = g.CurrentPopupStack.Size - 1;
  2829. if (popup_idx < 0 || popup_idx > g.OpenedPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupID != g.OpenedPopupStack[popup_idx].PopupID)
  2830. return;
  2831. while (popup_idx > 0 && g.OpenedPopupStack[popup_idx].Window && (g.OpenedPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
  2832. popup_idx--;
  2833. ClosePopupToLevel(popup_idx);
  2834. }
  2835. static inline void ClearSetNextWindowData()
  2836. {
  2837. ImGuiState& g = *GImGui;
  2838. g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0;
  2839. g.SetNextWindowFocus = false;
  2840. }
  2841. static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags)
  2842. {
  2843. ImGuiState& g = *GImGui;
  2844. ImGuiWindow* window = g.CurrentWindow;
  2845. const ImGuiID id = window->GetID(str_id);
  2846. if (!IsPopupOpen(id))
  2847. {
  2848. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  2849. return false;
  2850. }
  2851. ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  2852. ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
  2853. char name[32];
  2854. if (flags & ImGuiWindowFlags_ChildMenu)
  2855. ImFormatString(name, 20, "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth
  2856. else
  2857. ImFormatString(name, 20, "##popup_%08x", id); // Not recycling, so we can close/open during the same frame
  2858. float alpha = 1.0f;
  2859. bool opened = ImGui::Begin(name, NULL, ImVec2(0.0f, 0.0f), alpha, flags);
  2860. if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
  2861. g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders;
  2862. if (!opened) // opened can be 'false' when the popup is completely clipped (e.g. zero size display)
  2863. ImGui::EndPopup();
  2864. return opened;
  2865. }
  2866. bool ImGui::BeginPopup(const char* str_id)
  2867. {
  2868. if (GImGui->OpenedPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance
  2869. {
  2870. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  2871. return false;
  2872. }
  2873. return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders);
  2874. }
  2875. bool ImGui::BeginPopupModal(const char* name, bool* p_opened, ImGuiWindowFlags extra_flags)
  2876. {
  2877. ImGuiState& g = *GImGui;
  2878. ImGuiWindow* window = g.CurrentWindow;
  2879. const ImGuiID id = window->GetID(name);
  2880. if (!IsPopupOpen(id))
  2881. {
  2882. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  2883. return false;
  2884. }
  2885. ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings;
  2886. bool opened = ImGui::Begin(name, p_opened, ImVec2(0.0f, 0.0f), -1.0f, flags);
  2887. if (!opened || (p_opened && !*p_opened)) // Opened can be 'false' when the popup is completely clipped (e.g. zero size display)
  2888. {
  2889. ImGui::EndPopup();
  2890. if (opened)
  2891. ClosePopup(id);
  2892. return false;
  2893. }
  2894. return opened;
  2895. }
  2896. void ImGui::EndPopup()
  2897. {
  2898. ImGuiWindow* window = GetCurrentWindow();
  2899. IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  2900. IM_ASSERT(GImGui->CurrentPopupStack.Size > 0);
  2901. ImGui::End();
  2902. if (!(window->Flags & ImGuiWindowFlags_Modal))
  2903. ImGui::PopStyleVar();
  2904. }
  2905. // This is a helper to handle the most simple case of associating one named popup to one given widget.
  2906. // 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling
  2907. // this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers.
  2908. // 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect()
  2909. // and passing true to the OpenPopupEx().
  2910. // Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that
  2911. // the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu
  2912. // driven by click position.
  2913. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
  2914. {
  2915. if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(mouse_button))
  2916. ImGui::OpenPopupEx(str_id, false);
  2917. return ImGui::BeginPopup(str_id);
  2918. }
  2919. bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button)
  2920. {
  2921. if (!str_id) str_id = "window_context_menu";
  2922. if (ImGui::IsMouseHoveringWindow() && ImGui::IsMouseClicked(mouse_button))
  2923. if (also_over_items || !ImGui::IsAnyItemHovered())
  2924. ImGui::OpenPopupEx(str_id, true);
  2925. return ImGui::BeginPopup(str_id);
  2926. }
  2927. bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
  2928. {
  2929. if (!str_id) str_id = "void_context_menu";
  2930. if (!ImGui::IsMouseHoveringAnyWindow() && ImGui::IsMouseClicked(mouse_button))
  2931. ImGui::OpenPopupEx(str_id, true);
  2932. return ImGui::BeginPopup(str_id);
  2933. }
  2934. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  2935. {
  2936. ImGuiWindow* window = GetCurrentWindow();
  2937. ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
  2938. const ImVec2 content_avail = ImGui::GetContentRegionAvail();
  2939. ImVec2 size = ImRound(size_arg);
  2940. if (size.x <= 0.0f)
  2941. {
  2942. if (size.x == 0.0f)
  2943. flags |= ImGuiWindowFlags_ChildWindowAutoFitX;
  2944. size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues)
  2945. }
  2946. if (size.y <= 0.0f)
  2947. {
  2948. if (size.y == 0.0f)
  2949. flags |= ImGuiWindowFlags_ChildWindowAutoFitY;
  2950. size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y);
  2951. }
  2952. if (border)
  2953. flags |= ImGuiWindowFlags_ShowBorders;
  2954. flags |= extra_flags;
  2955. char title[256];
  2956. ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id);
  2957. const float alpha = 1.0f;
  2958. bool ret = ImGui::Begin(title, NULL, size, alpha, flags);
  2959. if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
  2960. GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders;
  2961. return ret;
  2962. }
  2963. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags extra_flags)
  2964. {
  2965. char str_id[32];
  2966. ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%08x", id);
  2967. bool ret = ImGui::BeginChild(str_id, size, border, extra_flags);
  2968. return ret;
  2969. }
  2970. void ImGui::EndChild()
  2971. {
  2972. ImGuiWindow* window = GetCurrentWindow();
  2973. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
  2974. if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1)
  2975. {
  2976. ImGui::End();
  2977. }
  2978. else
  2979. {
  2980. // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting.
  2981. ImVec2 sz = ImGui::GetWindowSize();
  2982. if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  2983. sz.x = ImMax(4.0f, sz.x);
  2984. if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY)
  2985. sz.y = ImMax(4.0f, sz.y);
  2986. ImGui::End();
  2987. window = GetCurrentWindow();
  2988. ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz);
  2989. ItemSize(sz);
  2990. ItemAdd(bb, NULL);
  2991. }
  2992. }
  2993. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  2994. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  2995. {
  2996. ImGuiState& g = *GImGui;
  2997. const ImGuiStyle& style = g.Style;
  2998. ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]);
  2999. ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding);
  3000. return ImGui::BeginChild(id, size, false, ImGuiWindowFlags_NoMove | extra_flags);
  3001. }
  3002. void ImGui::EndChildFrame()
  3003. {
  3004. ImGui::EndChild();
  3005. ImGui::PopStyleVar();
  3006. ImGui::PopStyleColor();
  3007. }
  3008. // Save and compare stack sizes on Begin()/End() to detect usage errors
  3009. static void CheckStacksSize(ImGuiWindow* window, bool write)
  3010. {
  3011. // 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)
  3012. ImGuiState& g = *GImGui;
  3013. int* p_backup = &window->DC.StackSizesBackup[0];
  3014. { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopID()
  3015. { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot EndGroup()
  3016. { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot EndPopup()/EndMenu()
  3017. { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopStyleColor()
  3018. { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopStyleVar()
  3019. { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current); p_backup++; } // User forgot PopFont()
  3020. IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
  3021. }
  3022. static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner)
  3023. {
  3024. const ImGuiStyle& style = GImGui->Style;
  3025. // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it.
  3026. ImVec2 safe_padding = style.DisplaySafeAreaPadding;
  3027. ImRect r_outer(GetVisibleRect());
  3028. r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f));
  3029. ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size);
  3030. for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction).
  3031. {
  3032. const int dir = (n == -1) ? *last_dir : n;
  3033. ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y);
  3034. if (rect.GetWidth() < size.x || rect.GetHeight() < size.y)
  3035. continue;
  3036. *last_dir = dir;
  3037. return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y);
  3038. }
  3039. // Fallback, try to keep within display
  3040. *last_dir = -1;
  3041. ImVec2 pos = base_pos;
  3042. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  3043. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  3044. return pos;
  3045. }
  3046. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  3047. {
  3048. // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block
  3049. ImGuiState& g = *GImGui;
  3050. ImGuiID id = ImHash(name, 0);
  3051. for (int i = 0; i < g.Windows.Size; i++)
  3052. if (g.Windows[i]->ID == id)
  3053. return g.Windows[i];
  3054. return NULL;
  3055. }
  3056. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
  3057. {
  3058. ImGuiState& g = *GImGui;
  3059. // Create window the first time
  3060. ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow));
  3061. IM_PLACEMENT_NEW(window) ImGuiWindow(name);
  3062. window->Flags = flags;
  3063. if (flags & ImGuiWindowFlags_NoSavedSettings)
  3064. {
  3065. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  3066. window->Size = window->SizeFull = size;
  3067. }
  3068. else
  3069. {
  3070. // Retrieve settings from .ini file
  3071. // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  3072. window->PosFloat = ImVec2(60, 60);
  3073. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  3074. ImGuiIniData* settings = FindWindowSettings(name);
  3075. if (!settings)
  3076. {
  3077. settings = AddWindowSettings(name);
  3078. }
  3079. else
  3080. {
  3081. window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver;
  3082. window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver;
  3083. window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver;
  3084. }
  3085. if (settings->Pos.x != FLT_MAX)
  3086. {
  3087. window->PosFloat = settings->Pos;
  3088. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  3089. window->Collapsed = settings->Collapsed;
  3090. }
  3091. if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize))
  3092. size = settings->Size;
  3093. window->Size = window->SizeFull = size;
  3094. }
  3095. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  3096. {
  3097. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  3098. window->AutoFitOnlyGrows = false;
  3099. }
  3100. else
  3101. {
  3102. if (window->Size.x <= 0.0f)
  3103. window->AutoFitFramesX = 2;
  3104. if (window->Size.y <= 0.0f)
  3105. window->AutoFitFramesY = 2;
  3106. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  3107. }
  3108. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  3109. g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
  3110. else
  3111. g.Windows.push_back(window);
  3112. return window;
  3113. }
  3114. // Push a new ImGui window to add widgets to.
  3115. // - 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.
  3116. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  3117. // - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation.
  3118. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  3119. // 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.
  3120. // - 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.
  3121. // - Passing 'bool* p_opened' 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.
  3122. // - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin().
  3123. bool ImGui::Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags)
  3124. {
  3125. return ImGui::Begin(name, p_opened, ImVec2(0.f, 0.f), -1.0f, flags);
  3126. }
  3127. bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags)
  3128. {
  3129. ImGuiState& g = *GImGui;
  3130. const ImGuiStyle& style = g.Style;
  3131. IM_ASSERT(name != NULL); // Window name required
  3132. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  3133. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  3134. if (flags & ImGuiWindowFlags_NoInputs)
  3135. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  3136. // Find or create
  3137. bool window_is_new = false;
  3138. ImGuiWindow* window = FindWindowByName(name);
  3139. if (!window)
  3140. {
  3141. window = CreateNewWindow(name, size_on_first_use, flags);
  3142. window_is_new = true;
  3143. }
  3144. const int current_frame = ImGui::GetFrameCount();
  3145. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  3146. if (first_begin_of_the_frame)
  3147. window->Flags = (ImGuiWindowFlags)flags;
  3148. else
  3149. flags = window->Flags;
  3150. // Add to stack
  3151. ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL;
  3152. g.CurrentWindowStack.push_back(window);
  3153. SetCurrentWindow(window);
  3154. CheckStacksSize(window, true);
  3155. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  3156. bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  3157. if (flags & ImGuiWindowFlags_Popup)
  3158. {
  3159. ImGuiPopupRef& popup_ref = g.OpenedPopupStack[g.CurrentPopupStack.Size];
  3160. window_was_active &= (window->PopupID == popup_ref.PopupID);
  3161. window_was_active &= (window == popup_ref.Window);
  3162. popup_ref.Window = window;
  3163. g.CurrentPopupStack.push_back(popup_ref);
  3164. window->PopupID = popup_ref.PopupID;
  3165. }
  3166. const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1);
  3167. // Process SetNextWindow***() calls
  3168. bool window_pos_set_by_api = false, window_size_set_by_api = false;
  3169. if (g.SetNextWindowPosCond)
  3170. {
  3171. const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this anymore :( need to look into that.
  3172. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing;
  3173. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0;
  3174. if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f)
  3175. {
  3176. window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size
  3177. window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  3178. }
  3179. else
  3180. {
  3181. SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond);
  3182. }
  3183. window->DC.CursorPos = backup_cursor_pos;
  3184. g.SetNextWindowPosCond = 0;
  3185. }
  3186. if (g.SetNextWindowSizeCond)
  3187. {
  3188. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing;
  3189. window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0;
  3190. SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond);
  3191. g.SetNextWindowSizeCond = 0;
  3192. }
  3193. if (g.SetNextWindowContentSizeCond)
  3194. {
  3195. window->SizeContentsExplicit = g.SetNextWindowContentSizeVal;
  3196. g.SetNextWindowContentSizeCond = 0;
  3197. }
  3198. else if (first_begin_of_the_frame)
  3199. {
  3200. window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  3201. }
  3202. if (g.SetNextWindowCollapsedCond)
  3203. {
  3204. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing;
  3205. SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond);
  3206. g.SetNextWindowCollapsedCond = 0;
  3207. }
  3208. if (g.SetNextWindowFocus)
  3209. {
  3210. ImGui::SetWindowFocus();
  3211. g.SetNextWindowFocus = false;
  3212. }
  3213. // Update known root window (if we are a child window, otherwise window == window->RootWindow)
  3214. int root_idx, root_non_popup_idx;
  3215. for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--)
  3216. if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow))
  3217. break;
  3218. for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--)
  3219. if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  3220. break;
  3221. window->RootWindow = g.CurrentWindowStack[root_idx];
  3222. window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color.
  3223. // Default alpha
  3224. if (bg_alpha < 0.0f)
  3225. bg_alpha = style.WindowFillAlphaDefault;
  3226. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  3227. if (first_begin_of_the_frame)
  3228. {
  3229. window->Active = true;
  3230. window->BeginCount = 0;
  3231. window->DrawList->Clear();
  3232. window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
  3233. window->LastFrameActive = current_frame;
  3234. window->IDStack.resize(1);
  3235. // Setup texture, outer clipping rectangle
  3236. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  3237. ImRect fullscreen_rect(GetVisibleRect());
  3238. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup)))
  3239. PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
  3240. else
  3241. PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
  3242. // New windows appears in front
  3243. if (!window_was_active)
  3244. {
  3245. window->AutoPosLastDirection = -1;
  3246. if (!(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  3247. if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
  3248. FocusWindow(window);
  3249. // Popup first latch mouse position, will position itself when it appears next frame
  3250. if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
  3251. window->PosFloat = g.IO.MousePos;
  3252. }
  3253. // Collapse window by double-clicking on title bar
  3254. // 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
  3255. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  3256. {
  3257. ImRect title_bar_rect = window->TitleBarRect();
  3258. if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
  3259. {
  3260. window->Collapsed = !window->Collapsed;
  3261. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  3262. MarkSettingsDirty();
  3263. FocusWindow(window);
  3264. }
  3265. }
  3266. else
  3267. {
  3268. window->Collapsed = false;
  3269. }
  3270. // SIZE
  3271. // Save contents size from last frame for auto-fitting (unless explicitly specified)
  3272. window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x));
  3273. window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y));
  3274. // Hide popup/tooltip window when first appearing while we measure size (because we recycle them)
  3275. if (window->HiddenFrames > 0)
  3276. window->HiddenFrames--;
  3277. if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active)
  3278. {
  3279. window->HiddenFrames = 1;
  3280. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  3281. {
  3282. if (!window_size_set_by_api)
  3283. window->Size = window->SizeFull = ImVec2(0.f, 0.f);
  3284. window->SizeContents = ImVec2(0.f, 0.f);
  3285. }
  3286. }
  3287. // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects.
  3288. window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding;
  3289. // Calculate auto-fit size
  3290. ImVec2 size_auto_fit;
  3291. if ((flags & ImGuiWindowFlags_Tooltip) != 0)
  3292. {
  3293. // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
  3294. size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y);
  3295. }
  3296. else
  3297. {
  3298. size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
  3299. // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
  3300. if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
  3301. size_auto_fit.y += style.ScrollbarSize;
  3302. if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
  3303. size_auto_fit.x += style.ScrollbarSize;
  3304. size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f);
  3305. }
  3306. // Handle automatic resize
  3307. if (window->Collapsed)
  3308. {
  3309. // We still process initial auto-fit on collapsed windows to get a window width,
  3310. // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  3311. if (window->AutoFitFramesX > 0)
  3312. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  3313. if (window->AutoFitFramesY > 0)
  3314. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  3315. window->Size = window->TitleBarRect().GetSize();
  3316. }
  3317. else
  3318. {
  3319. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api)
  3320. {
  3321. window->SizeFull = size_auto_fit;
  3322. }
  3323. else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api)
  3324. {
  3325. // Auto-fit only grows during the first few frames
  3326. if (window->AutoFitFramesX > 0)
  3327. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  3328. if (window->AutoFitFramesY > 0)
  3329. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  3330. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  3331. MarkSettingsDirty();
  3332. }
  3333. window->Size = window->SizeFull;
  3334. }
  3335. // Minimum window size
  3336. if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  3337. {
  3338. window->SizeFull = ImMax(window->SizeFull, style.WindowMinSize);
  3339. if (!window->Collapsed)
  3340. window->Size = window->SizeFull;
  3341. }
  3342. // POSITION
  3343. // Position child window
  3344. if (flags & ImGuiWindowFlags_ChildWindow)
  3345. parent_window->DC.ChildWindows.push_back(window);
  3346. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
  3347. {
  3348. window->Pos = window->PosFloat = parent_window->DC.CursorPos;
  3349. window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user.
  3350. }
  3351. bool window_pos_center = false;
  3352. window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0);
  3353. window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden);
  3354. if (window_pos_center)
  3355. {
  3356. // Center (any sort of window)
  3357. SetWindowPos(ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f));
  3358. }
  3359. else if (flags & ImGuiWindowFlags_ChildMenu)
  3360. {
  3361. IM_ASSERT(window_pos_set_by_api);
  3362. ImRect rect_to_avoid;
  3363. if (parent_window->DC.MenuBarAppending)
  3364. rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
  3365. else
  3366. rect_to_avoid = ImRect(parent_window->Pos.x + style.ItemSpacing.x, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - style.ItemSpacing.x - parent_window->ScrollbarSizes.x, FLT_MAX); // We want some overlap to convey the relative depth of each popup (here hard-coded to 4)
  3367. window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  3368. }
  3369. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden)
  3370. {
  3371. ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
  3372. window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  3373. }
  3374. // Position tooltip (always follows mouse)
  3375. if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api)
  3376. {
  3377. ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead?
  3378. window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  3379. if (window->AutoPosLastDirection == -1)
  3380. window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  3381. }
  3382. // User moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows.
  3383. KeepAliveID(window->MoveID);
  3384. if (g.ActiveId == window->MoveID)
  3385. {
  3386. if (g.IO.MouseDown[0])
  3387. {
  3388. if (!(flags & ImGuiWindowFlags_NoMove))
  3389. {
  3390. window->PosFloat += g.IO.MouseDelta;
  3391. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  3392. MarkSettingsDirty();
  3393. }
  3394. IM_ASSERT(g.MovedWindow != NULL);
  3395. FocusWindow(g.MovedWindow);
  3396. }
  3397. else
  3398. {
  3399. SetActiveID(0);
  3400. g.MovedWindow = NULL; // Not strictly necessary but doing it for sanity.
  3401. }
  3402. }
  3403. // Clamp position so it stays visible
  3404. if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  3405. {
  3406. 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.
  3407. {
  3408. ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  3409. window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size;
  3410. window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
  3411. }
  3412. }
  3413. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  3414. // Default item width. Make it proportional to window size if window manually resizes
  3415. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  3416. window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
  3417. else
  3418. window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
  3419. // Prepare for focus requests
  3420. window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == IM_INT_MAX || window->FocusIdxAllCounter == -1) ? IM_INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
  3421. window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == IM_INT_MAX || window->FocusIdxTabCounter == -1) ? IM_INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
  3422. window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
  3423. window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = IM_INT_MAX;
  3424. // Apply scrolling
  3425. if (window->ScrollTarget.x < FLT_MAX)
  3426. {
  3427. window->Scroll.x = window->ScrollTarget.x;
  3428. window->ScrollTarget.x = FLT_MAX;
  3429. }
  3430. if (window->ScrollTarget.y < FLT_MAX)
  3431. {
  3432. float center_ratio = window->ScrollTargetCenterRatio.y;
  3433. window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * window->TitleBarHeight()) - (center_ratio * window->SizeFull.y);
  3434. window->ScrollTarget.y = FLT_MAX;
  3435. }
  3436. window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f));
  3437. if (!window->Collapsed && !window->SkipItems)
  3438. window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes));
  3439. // Modal window darkens what is behind them
  3440. if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
  3441. window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
  3442. // Draw window + handle manual resize
  3443. ImRect title_bar_rect = window->TitleBarRect();
  3444. const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
  3445. if (window->Collapsed)
  3446. {
  3447. // Draw title bar only
  3448. RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
  3449. }
  3450. else
  3451. {
  3452. ImU32 resize_col = 0;
  3453. const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f);
  3454. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize))
  3455. {
  3456. // Manual resize
  3457. const ImVec2 br = window->Rect().GetBR();
  3458. const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br);
  3459. const ImGuiID resize_id = window->GetID("#RESIZE");
  3460. bool hovered, held;
  3461. ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds);
  3462. resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  3463. if (hovered || held)
  3464. g.MouseCursor = ImGuiMouseCursor_ResizeNWSE;
  3465. if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0])
  3466. {
  3467. // Manual auto-fit when double-clicking
  3468. window->SizeFull = size_auto_fit;
  3469. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  3470. MarkSettingsDirty();
  3471. SetActiveID(0);
  3472. }
  3473. else if (held)
  3474. {
  3475. window->SizeFull = ImMax(window->SizeFull + g.IO.MouseDelta, style.WindowMinSize);
  3476. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  3477. MarkSettingsDirty();
  3478. }
  3479. window->Size = window->SizeFull;
  3480. title_bar_rect = window->TitleBarRect();
  3481. }
  3482. // Scrollbars
  3483. window->ScrollbarY = (flags & ImGuiWindowFlags_ForceVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar));
  3484. window->ScrollbarX = (flags & ImGuiWindowFlags_ForceHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
  3485. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  3486. window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f;
  3487. // Window background
  3488. if (bg_alpha > 0.0f)
  3489. {
  3490. ImGuiCol col_idx;
  3491. if ((flags & ImGuiWindowFlags_ComboBox) != 0)
  3492. col_idx = ImGuiCol_ComboBg;
  3493. else if ((flags & ImGuiWindowFlags_Tooltip) != 0)
  3494. col_idx = ImGuiCol_TooltipBg;
  3495. else if ((flags & ImGuiWindowFlags_Popup) != 0)
  3496. col_idx = ImGuiCol_WindowBg;
  3497. else if ((flags & ImGuiWindowFlags_ChildWindow) != 0)
  3498. col_idx = ImGuiCol_ChildWindowBg;
  3499. else
  3500. col_idx = ImGuiCol_WindowBg;
  3501. window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, GetColorU32(col_idx, bg_alpha), window_rounding);
  3502. }
  3503. // Title bar
  3504. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  3505. window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, 1|2);
  3506. // Menu bar
  3507. if (flags & ImGuiWindowFlags_MenuBar)
  3508. {
  3509. ImRect menu_bar_rect = window->MenuBarRect();
  3510. window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, 1|2);
  3511. }
  3512. // Scrollbars
  3513. if (window->ScrollbarX)
  3514. Scrollbar(window, true);
  3515. if (window->ScrollbarY)
  3516. Scrollbar(window, false);
  3517. // Render resize grip
  3518. // (after the input handling so we don't have a frame of latency)
  3519. if (!(flags & ImGuiWindowFlags_NoResize))
  3520. {
  3521. const ImVec2 br = window->Rect().GetBR();
  3522. window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize));
  3523. window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size));
  3524. window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3);
  3525. window->DrawList->PathFill(resize_col);
  3526. }
  3527. // Borders
  3528. if (flags & ImGuiWindowFlags_ShowBorders)
  3529. {
  3530. window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding);
  3531. window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding);
  3532. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  3533. window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border));
  3534. }
  3535. }
  3536. // Setup drawing context
  3537. window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
  3538. window->DC.ColumnsOffsetX = 0.0f;
  3539. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
  3540. window->DC.CursorPos = window->DC.CursorStartPos;
  3541. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  3542. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  3543. window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
  3544. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  3545. window->DC.MenuBarAppending = false;
  3546. window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
  3547. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  3548. window->DC.ChildWindows.resize(0);
  3549. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  3550. window->DC.ItemWidth = window->ItemWidthDefault;
  3551. window->DC.TextWrapPos = -1.0f; // disabled
  3552. window->DC.AllowKeyboardFocus = true;
  3553. window->DC.ButtonRepeat = false;
  3554. window->DC.ItemWidthStack.resize(0);
  3555. window->DC.TextWrapPosStack.resize(0);
  3556. window->DC.AllowKeyboardFocusStack.resize(0);
  3557. window->DC.ButtonRepeatStack.resize(0);
  3558. window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect;
  3559. window->DC.ColumnsCurrent = 0;
  3560. window->DC.ColumnsCount = 1;
  3561. window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
  3562. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY;
  3563. window->DC.TreeDepth = 0;
  3564. window->DC.StateStorage = &window->StateStorage;
  3565. window->DC.GroupStack.resize(0);
  3566. window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active);
  3567. if (window->AutoFitFramesX > 0)
  3568. window->AutoFitFramesX--;
  3569. if (window->AutoFitFramesY > 0)
  3570. window->AutoFitFramesY--;
  3571. // Title bar
  3572. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  3573. {
  3574. if (p_opened != NULL)
  3575. CloseWindowButton(p_opened);
  3576. const ImVec2 text_size = CalcTextSize(name, NULL, true);
  3577. if (!(flags & ImGuiWindowFlags_NoCollapse))
  3578. RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true);
  3579. ImVec2 text_min = window->Pos + style.FramePadding;
  3580. ImVec2 text_max = window->Pos + ImVec2(window->Size.x - style.FramePadding.x, style.FramePadding.y*2 + text_size.y);
  3581. ImVec2 clip_max = ImVec2(window->Pos.x + window->Size.x - (p_opened ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton()
  3582. bool pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0;
  3583. bool pad_right = (p_opened != NULL);
  3584. if (style.WindowTitleAlign & ImGuiAlign_Center) pad_right = pad_left;
  3585. if (pad_left) text_min.x += g.FontSize + style.ItemInnerSpacing.x;
  3586. if (pad_right) text_max.x -= g.FontSize + style.ItemInnerSpacing.x;
  3587. RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, NULL, &clip_max);
  3588. }
  3589. // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
  3590. window->ClippedWindowRect = window->Rect();
  3591. window->ClippedWindowRect.Clip(window->ClipRect);
  3592. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  3593. // 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.
  3594. // Maybe we can support CTRL+C on every element?
  3595. /*
  3596. if (g.ActiveId == move_id)
  3597. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  3598. ImGui::LogToClipboard();
  3599. */
  3600. }
  3601. // Inner clipping rectangle
  3602. // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
  3603. // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
  3604. const ImRect title_bar_rect = window->TitleBarRect();
  3605. const float border_size = window->BorderSize;
  3606. ImRect clip_rect;
  3607. clip_rect.Min.x = title_bar_rect.Min.x + 0.5f + ImMax(border_size, window->WindowPadding.x*0.5f);
  3608. clip_rect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + 0.5f + border_size;
  3609. clip_rect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, window->WindowPadding.x*0.5f);
  3610. clip_rect.Max.y = window->Pos.y + window->Size.y - border_size - window->ScrollbarSizes.y;
  3611. PushClipRect(clip_rect.Min, clip_rect.Max, true);
  3612. // Clear 'accessed' flag last thing
  3613. if (first_begin_of_the_frame)
  3614. window->Accessed = false;
  3615. window->BeginCount++;
  3616. // Child window can be out of sight and have "negative" clip windows.
  3617. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
  3618. if (flags & ImGuiWindowFlags_ChildWindow)
  3619. {
  3620. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  3621. window->Collapsed = parent_window && parent_window->Collapsed;
  3622. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  3623. window->Collapsed |= (window->ClippedWindowRect.Min.x >= window->ClippedWindowRect.Max.x || window->ClippedWindowRect.Min.y >= window->ClippedWindowRect.Max.y);
  3624. // We also hide the window from rendering because we've already added its border to the command list.
  3625. // (we could perform the check earlier in the function but it is simpler at this point)
  3626. if (window->Collapsed)
  3627. window->Active = false;
  3628. }
  3629. if (style.Alpha <= 0.0f)
  3630. window->Active = false;
  3631. // Return false if we don't intend to display anything to allow user to perform an early out optimization
  3632. window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
  3633. return !window->SkipItems;
  3634. }
  3635. void ImGui::End()
  3636. {
  3637. ImGuiState& g = *GImGui;
  3638. ImGuiWindow* window = g.CurrentWindow;
  3639. ImGui::Columns(1, "#CloseColumns");
  3640. PopClipRect(); // inner window clip rectangle
  3641. // Stop logging
  3642. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  3643. ImGui::LogFinish();
  3644. // Pop
  3645. // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin().
  3646. g.CurrentWindowStack.pop_back();
  3647. if (window->Flags & ImGuiWindowFlags_Popup)
  3648. g.CurrentPopupStack.pop_back();
  3649. CheckStacksSize(window, false);
  3650. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  3651. }
  3652. // Vertical scrollbar
  3653. // The entire piece of code below is rather confusing because:
  3654. // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
  3655. // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
  3656. // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
  3657. static void Scrollbar(ImGuiWindow* window, bool horizontal)
  3658. {
  3659. ImGuiState& g = *GImGui;
  3660. const ImGuiStyle& style = g.Style;
  3661. const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
  3662. // Render background
  3663. bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
  3664. float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
  3665. const ImRect window_rect = window->Rect();
  3666. const float border_size = window->BorderSize;
  3667. ImRect bb = horizontal
  3668. ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size)
  3669. : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size);
  3670. if (!horizontal)
  3671. bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() - border_size : 0.0f);
  3672. float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
  3673. int window_rounding_corners;
  3674. if (horizontal)
  3675. window_rounding_corners = 8 | (other_scrollbar ? 0 : 4);
  3676. else
  3677. window_rounding_corners = ((window->Flags & ImGuiWindowFlags_NoTitleBar) ? 2 : 0) | (other_scrollbar ? 0 : 4);
  3678. window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners);
  3679. bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
  3680. // V denote the main axis of the scrollbar
  3681. float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
  3682. float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
  3683. float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w;
  3684. float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
  3685. // The grabable box size generally represent the amount visible (vs the total scrollable amount)
  3686. // But we maintain a minimum size in pixel to allow for the user to still aim inside.
  3687. const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v);
  3688. const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
  3689. // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
  3690. bool held = false;
  3691. bool hovered = false;
  3692. const bool previously_held = (g.ActiveId == id);
  3693. ImGui::ButtonBehavior(bb, id, &hovered, &held);
  3694. float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
  3695. float scroll_ratio = ImSaturate(scroll_v / scroll_max);
  3696. float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  3697. if (held && grab_h_norm < 1.0f)
  3698. {
  3699. float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
  3700. float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  3701. float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y;
  3702. // Click position in scrollbar normalized space (0.0f->1.0f)
  3703. const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
  3704. ImGui::SetHoveredID(id);
  3705. bool seek_absolute = false;
  3706. if (!previously_held)
  3707. {
  3708. // On initial click calculate the distance between mouse and the center of the grab
  3709. if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
  3710. {
  3711. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  3712. }
  3713. else
  3714. {
  3715. seek_absolute = true;
  3716. *click_delta_to_grab_center_v = 0.0f;
  3717. }
  3718. }
  3719. // Apply scroll
  3720. // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position
  3721. const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm));
  3722. scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
  3723. if (horizontal)
  3724. window->Scroll.x = scroll_v;
  3725. else
  3726. window->Scroll.y = scroll_v;
  3727. // Update values for rendering
  3728. scroll_ratio = ImSaturate(scroll_v / scroll_max);
  3729. grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  3730. // Update distance to grab now that we have seeked and saturated
  3731. if (seek_absolute)
  3732. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  3733. }
  3734. // Render
  3735. const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
  3736. if (horizontal)
  3737. window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding);
  3738. else
  3739. window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding);
  3740. }
  3741. // Moving window to front of display (which happens to be back of our sorted list)
  3742. void ImGui::FocusWindow(ImGuiWindow* window)
  3743. {
  3744. ImGuiState& g = *GImGui;
  3745. // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
  3746. g.FocusedWindow = window;
  3747. // Passing NULL allow to disable keyboard focus
  3748. if (!window)
  3749. return;
  3750. // And move its root window to the top of the pile
  3751. if (window->RootWindow)
  3752. window = window->RootWindow;
  3753. // Steal focus on active widgets
  3754. if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
  3755. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
  3756. ImGui::SetActiveID(0);
  3757. // Bring to front
  3758. if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window)
  3759. return;
  3760. for (int i = 0; i < g.Windows.Size; i++)
  3761. if (g.Windows[i] == window)
  3762. {
  3763. g.Windows.erase(g.Windows.begin() + i);
  3764. break;
  3765. }
  3766. g.Windows.push_back(window);
  3767. }
  3768. void ImGui::PushItemWidth(float item_width)
  3769. {
  3770. ImGuiWindow* window = GetCurrentWindow();
  3771. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  3772. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
  3773. }
  3774. static void PushMultiItemsWidths(int components, float w_full)
  3775. {
  3776. ImGuiWindow* window = ImGui::GetCurrentWindow();
  3777. const ImGuiStyle& style = GImGui->Style;
  3778. if (w_full <= 0.0f)
  3779. w_full = ImGui::CalcItemWidth();
  3780. const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  3781. const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  3782. window->DC.ItemWidthStack.push_back(w_item_last);
  3783. for (int i = 0; i < components-1; i++)
  3784. window->DC.ItemWidthStack.push_back(w_item_one);
  3785. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  3786. }
  3787. void ImGui::PopItemWidth()
  3788. {
  3789. ImGuiWindow* window = GetCurrentWindow();
  3790. window->DC.ItemWidthStack.pop_back();
  3791. window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
  3792. }
  3793. float ImGui::CalcItemWidth()
  3794. {
  3795. ImGuiWindow* window = GetCurrentWindowRead();
  3796. float w = window->DC.ItemWidth;
  3797. if (w < 0.0f)
  3798. {
  3799. // 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.
  3800. float width_to_right_edge = ImGui::GetContentRegionAvail().x;
  3801. w = ImMax(1.0f, width_to_right_edge + w);
  3802. }
  3803. w = (float)(int)w;
  3804. return w;
  3805. }
  3806. static void SetCurrentFont(ImFont* font)
  3807. {
  3808. ImGuiState& g = *GImGui;
  3809. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  3810. IM_ASSERT(font->Scale > 0.0f);
  3811. g.Font = font;
  3812. g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
  3813. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  3814. g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel;
  3815. }
  3816. void ImGui::PushFont(ImFont* font)
  3817. {
  3818. ImGuiState& g = *GImGui;
  3819. if (!font)
  3820. font = g.IO.Fonts->Fonts[0];
  3821. SetCurrentFont(font);
  3822. g.FontStack.push_back(font);
  3823. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  3824. }
  3825. void ImGui::PopFont()
  3826. {
  3827. ImGuiState& g = *GImGui;
  3828. g.CurrentWindow->DrawList->PopTextureID();
  3829. g.FontStack.pop_back();
  3830. SetCurrentFont(g.FontStack.empty() ? g.IO.Fonts->Fonts[0] : g.FontStack.back());
  3831. }
  3832. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  3833. {
  3834. ImGuiWindow* window = GetCurrentWindow();
  3835. window->DC.AllowKeyboardFocus = allow_keyboard_focus;
  3836. window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus);
  3837. }
  3838. void ImGui::PopAllowKeyboardFocus()
  3839. {
  3840. ImGuiWindow* window = GetCurrentWindow();
  3841. window->DC.AllowKeyboardFocusStack.pop_back();
  3842. window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back();
  3843. }
  3844. void ImGui::PushButtonRepeat(bool repeat)
  3845. {
  3846. ImGuiWindow* window = GetCurrentWindow();
  3847. window->DC.ButtonRepeat = repeat;
  3848. window->DC.ButtonRepeatStack.push_back(repeat);
  3849. }
  3850. void ImGui::PopButtonRepeat()
  3851. {
  3852. ImGuiWindow* window = GetCurrentWindow();
  3853. window->DC.ButtonRepeatStack.pop_back();
  3854. window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back();
  3855. }
  3856. void ImGui::PushTextWrapPos(float wrap_pos_x)
  3857. {
  3858. ImGuiWindow* window = GetCurrentWindow();
  3859. window->DC.TextWrapPos = wrap_pos_x;
  3860. window->DC.TextWrapPosStack.push_back(wrap_pos_x);
  3861. }
  3862. void ImGui::PopTextWrapPos()
  3863. {
  3864. ImGuiWindow* window = GetCurrentWindow();
  3865. window->DC.TextWrapPosStack.pop_back();
  3866. window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
  3867. }
  3868. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  3869. {
  3870. ImGuiState& g = *GImGui;
  3871. ImGuiColMod backup;
  3872. backup.Col = idx;
  3873. backup.PreviousValue = g.Style.Colors[idx];
  3874. g.ColorModifiers.push_back(backup);
  3875. g.Style.Colors[idx] = col;
  3876. }
  3877. void ImGui::PopStyleColor(int count)
  3878. {
  3879. ImGuiState& g = *GImGui;
  3880. while (count > 0)
  3881. {
  3882. ImGuiColMod& backup = g.ColorModifiers.back();
  3883. g.Style.Colors[backup.Col] = backup.PreviousValue;
  3884. g.ColorModifiers.pop_back();
  3885. count--;
  3886. }
  3887. }
  3888. static float* GetStyleVarFloatAddr(ImGuiStyleVar idx)
  3889. {
  3890. ImGuiState& g = *GImGui;
  3891. switch (idx)
  3892. {
  3893. case ImGuiStyleVar_Alpha: return &g.Style.Alpha;
  3894. case ImGuiStyleVar_WindowRounding: return &g.Style.WindowRounding;
  3895. case ImGuiStyleVar_ChildWindowRounding: return &g.Style.ChildWindowRounding;
  3896. case ImGuiStyleVar_FrameRounding: return &g.Style.FrameRounding;
  3897. case ImGuiStyleVar_IndentSpacing: return &g.Style.IndentSpacing;
  3898. case ImGuiStyleVar_GrabMinSize: return &g.Style.GrabMinSize;
  3899. }
  3900. return NULL;
  3901. }
  3902. static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx)
  3903. {
  3904. ImGuiState& g = *GImGui;
  3905. switch (idx)
  3906. {
  3907. case ImGuiStyleVar_WindowPadding: return &g.Style.WindowPadding;
  3908. case ImGuiStyleVar_WindowMinSize: return &g.Style.WindowMinSize;
  3909. case ImGuiStyleVar_FramePadding: return &g.Style.FramePadding;
  3910. case ImGuiStyleVar_ItemSpacing: return &g.Style.ItemSpacing;
  3911. case ImGuiStyleVar_ItemInnerSpacing: return &g.Style.ItemInnerSpacing;
  3912. }
  3913. return NULL;
  3914. }
  3915. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  3916. {
  3917. ImGuiState& g = *GImGui;
  3918. float* pvar = GetStyleVarFloatAddr(idx);
  3919. IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a float.
  3920. ImGuiStyleMod backup;
  3921. backup.Var = idx;
  3922. backup.PreviousValue = ImVec2(*pvar, 0.0f);
  3923. g.StyleModifiers.push_back(backup);
  3924. *pvar = val;
  3925. }
  3926. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  3927. {
  3928. ImGuiState& g = *GImGui;
  3929. ImVec2* pvar = GetStyleVarVec2Addr(idx);
  3930. IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a ImVec2.
  3931. ImGuiStyleMod backup;
  3932. backup.Var = idx;
  3933. backup.PreviousValue = *pvar;
  3934. g.StyleModifiers.push_back(backup);
  3935. *pvar = val;
  3936. }
  3937. void ImGui::PopStyleVar(int count)
  3938. {
  3939. ImGuiState& g = *GImGui;
  3940. while (count > 0)
  3941. {
  3942. ImGuiStyleMod& backup = g.StyleModifiers.back();
  3943. if (float* pvar_f = GetStyleVarFloatAddr(backup.Var))
  3944. *pvar_f = backup.PreviousValue.x;
  3945. else if (ImVec2* pvar_v = GetStyleVarVec2Addr(backup.Var))
  3946. *pvar_v = backup.PreviousValue;
  3947. g.StyleModifiers.pop_back();
  3948. count--;
  3949. }
  3950. }
  3951. const char* ImGui::GetStyleColName(ImGuiCol idx)
  3952. {
  3953. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  3954. switch (idx)
  3955. {
  3956. case ImGuiCol_Text: return "Text";
  3957. case ImGuiCol_TextDisabled: return "TextDisabled";
  3958. case ImGuiCol_WindowBg: return "WindowBg";
  3959. case ImGuiCol_ChildWindowBg: return "ChildWindowBg";
  3960. case ImGuiCol_Border: return "Border";
  3961. case ImGuiCol_BorderShadow: return "BorderShadow";
  3962. case ImGuiCol_FrameBg: return "FrameBg";
  3963. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  3964. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  3965. case ImGuiCol_TitleBg: return "TitleBg";
  3966. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  3967. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  3968. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  3969. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  3970. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  3971. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  3972. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  3973. case ImGuiCol_ComboBg: return "ComboBg";
  3974. case ImGuiCol_CheckMark: return "CheckMark";
  3975. case ImGuiCol_SliderGrab: return "SliderGrab";
  3976. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  3977. case ImGuiCol_Button: return "Button";
  3978. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  3979. case ImGuiCol_ButtonActive: return "ButtonActive";
  3980. case ImGuiCol_Header: return "Header";
  3981. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  3982. case ImGuiCol_HeaderActive: return "HeaderActive";
  3983. case ImGuiCol_Column: return "Column";
  3984. case ImGuiCol_ColumnHovered: return "ColumnHovered";
  3985. case ImGuiCol_ColumnActive: return "ColumnActive";
  3986. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  3987. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  3988. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  3989. case ImGuiCol_CloseButton: return "CloseButton";
  3990. case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered";
  3991. case ImGuiCol_CloseButtonActive: return "CloseButtonActive";
  3992. case ImGuiCol_PlotLines: return "PlotLines";
  3993. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  3994. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  3995. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  3996. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  3997. case ImGuiCol_TooltipBg: return "TooltipBg";
  3998. case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
  3999. }
  4000. IM_ASSERT(0);
  4001. return "Unknown";
  4002. }
  4003. bool ImGui::IsWindowHovered()
  4004. {
  4005. ImGuiState& g = *GImGui;
  4006. return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow);
  4007. }
  4008. bool ImGui::IsWindowFocused()
  4009. {
  4010. ImGuiState& g = *GImGui;
  4011. return g.FocusedWindow == g.CurrentWindow;
  4012. }
  4013. bool ImGui::IsRootWindowFocused()
  4014. {
  4015. ImGuiState& g = *GImGui;
  4016. ImGuiWindow* root_window = g.CurrentWindow->RootWindow;
  4017. return g.FocusedWindow == root_window;
  4018. }
  4019. bool ImGui::IsRootWindowOrAnyChildFocused()
  4020. {
  4021. ImGuiState& g = *GImGui;
  4022. ImGuiWindow* root_window = g.CurrentWindow->RootWindow;
  4023. return g.FocusedWindow && g.FocusedWindow->RootWindow == root_window;
  4024. }
  4025. float ImGui::GetWindowWidth()
  4026. {
  4027. ImGuiWindow* window = GImGui->CurrentWindow;
  4028. return window->Size.x;
  4029. }
  4030. float ImGui::GetWindowHeight()
  4031. {
  4032. ImGuiWindow* window = GImGui->CurrentWindow;
  4033. return window->Size.y;
  4034. }
  4035. ImVec2 ImGui::GetWindowPos()
  4036. {
  4037. ImGuiState& g = *GImGui;
  4038. ImGuiWindow* window = g.CurrentWindow;
  4039. return window->Pos;
  4040. }
  4041. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
  4042. {
  4043. window->DC.CursorMaxPos.y += window->Scroll.y;
  4044. window->Scroll.y = new_scroll_y;
  4045. window->DC.CursorMaxPos.y -= window->Scroll.y;
  4046. }
  4047. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond)
  4048. {
  4049. // Test condition (NB: bit 0 is always true) and clear flags for next time
  4050. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  4051. return;
  4052. window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  4053. window->SetWindowPosCenterWanted = false;
  4054. // Set
  4055. const ImVec2 old_pos = window->Pos;
  4056. window->PosFloat = pos;
  4057. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  4058. 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
  4059. window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
  4060. }
  4061. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond)
  4062. {
  4063. ImGuiWindow* window = GetCurrentWindow();
  4064. SetWindowPos(window, pos, cond);
  4065. }
  4066. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond)
  4067. {
  4068. ImGuiWindow* window = FindWindowByName(name);
  4069. if (window)
  4070. SetWindowPos(window, pos, cond);
  4071. }
  4072. ImVec2 ImGui::GetWindowSize()
  4073. {
  4074. ImGuiWindow* window = GetCurrentWindowRead();
  4075. return window->Size;
  4076. }
  4077. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond)
  4078. {
  4079. // Test condition (NB: bit 0 is always true) and clear flags for next time
  4080. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  4081. return;
  4082. window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  4083. // Set
  4084. if (size.x > 0.0f)
  4085. {
  4086. window->AutoFitFramesX = 0;
  4087. window->SizeFull.x = size.x;
  4088. }
  4089. else
  4090. {
  4091. window->AutoFitFramesX = 2;
  4092. window->AutoFitOnlyGrows = false;
  4093. }
  4094. if (size.y > 0.0f)
  4095. {
  4096. window->AutoFitFramesY = 0;
  4097. window->SizeFull.y = size.y;
  4098. }
  4099. else
  4100. {
  4101. window->AutoFitFramesY = 2;
  4102. window->AutoFitOnlyGrows = false;
  4103. }
  4104. }
  4105. void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond)
  4106. {
  4107. SetWindowSize(GImGui->CurrentWindow, size, cond);
  4108. }
  4109. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond)
  4110. {
  4111. ImGuiWindow* window = FindWindowByName(name);
  4112. if (window)
  4113. SetWindowSize(window, size, cond);
  4114. }
  4115. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond)
  4116. {
  4117. // Test condition (NB: bit 0 is always true) and clear flags for next time
  4118. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  4119. return;
  4120. window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  4121. // Set
  4122. window->Collapsed = collapsed;
  4123. }
  4124. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond)
  4125. {
  4126. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  4127. }
  4128. bool ImGui::IsWindowCollapsed()
  4129. {
  4130. return GImGui->CurrentWindow->Collapsed;
  4131. }
  4132. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond)
  4133. {
  4134. ImGuiWindow* window = FindWindowByName(name);
  4135. if (window)
  4136. SetWindowCollapsed(window, collapsed, cond);
  4137. }
  4138. void ImGui::SetWindowFocus()
  4139. {
  4140. FocusWindow(GImGui->CurrentWindow);
  4141. }
  4142. void ImGui::SetWindowFocus(const char* name)
  4143. {
  4144. if (name)
  4145. {
  4146. ImGuiWindow* window = FindWindowByName(name);
  4147. if (window)
  4148. FocusWindow(window);
  4149. }
  4150. else
  4151. {
  4152. FocusWindow(NULL);
  4153. }
  4154. }
  4155. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond)
  4156. {
  4157. ImGuiState& g = *GImGui;
  4158. g.SetNextWindowPosVal = pos;
  4159. g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
  4160. }
  4161. void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond)
  4162. {
  4163. ImGuiState& g = *GImGui;
  4164. g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX);
  4165. g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
  4166. }
  4167. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond)
  4168. {
  4169. ImGuiState& g = *GImGui;
  4170. g.SetNextWindowSizeVal = size;
  4171. g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always;
  4172. }
  4173. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  4174. {
  4175. ImGuiState& g = *GImGui;
  4176. g.SetNextWindowContentSizeVal = size;
  4177. g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
  4178. }
  4179. void ImGui::SetNextWindowContentWidth(float width)
  4180. {
  4181. ImGuiState& g = *GImGui;
  4182. g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f);
  4183. g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
  4184. }
  4185. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond)
  4186. {
  4187. ImGuiState& g = *GImGui;
  4188. g.SetNextWindowCollapsedVal = collapsed;
  4189. g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always;
  4190. }
  4191. void ImGui::SetNextWindowFocus()
  4192. {
  4193. ImGuiState& g = *GImGui;
  4194. g.SetNextWindowFocus = true;
  4195. }
  4196. // In window space (not screen space!)
  4197. // FIXME-OPT: Could cache and maintain it (pretty much only change on columns change)
  4198. ImVec2 ImGui::GetContentRegionMax()
  4199. {
  4200. ImGuiWindow* window = GetCurrentWindowRead();
  4201. ImVec2 content_region_size = ImVec2(window->SizeContentsExplicit.x ? window->SizeContentsExplicit.x : window->Size.x - window->ScrollbarSizes.x, window->SizeContentsExplicit.y ? window->SizeContentsExplicit.y : window->Size.y - window->ScrollbarSizes.y);
  4202. ImVec2 mx = content_region_size - window->Scroll - window->WindowPadding;
  4203. if (window->DC.ColumnsCount != 1)
  4204. mx.x = ImGui::GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x;
  4205. return mx;
  4206. }
  4207. ImVec2 ImGui::GetContentRegionAvail()
  4208. {
  4209. ImGuiWindow* window = GetCurrentWindowRead();
  4210. return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
  4211. }
  4212. float ImGui::GetContentRegionAvailWidth()
  4213. {
  4214. return GetContentRegionAvail().x;
  4215. }
  4216. // In window space (not screen space!)
  4217. ImVec2 ImGui::GetWindowContentRegionMin()
  4218. {
  4219. ImGuiWindow* window = GetCurrentWindowRead();
  4220. return ImVec2(-window->Scroll.x, -window->Scroll.y + window->TitleBarHeight() + window->MenuBarHeight()) + window->WindowPadding;
  4221. }
  4222. ImVec2 ImGui::GetWindowContentRegionMax()
  4223. {
  4224. ImGuiWindow* window = GetCurrentWindowRead();
  4225. ImVec2 content_region_size = ImVec2(window->SizeContentsExplicit.x ? window->SizeContentsExplicit.x : window->Size.x, window->SizeContentsExplicit.y ? window->SizeContentsExplicit.y : window->Size.y);
  4226. ImVec2 m = content_region_size - window->Scroll - window->WindowPadding - window->ScrollbarSizes;
  4227. return m;
  4228. }
  4229. float ImGui::GetWindowContentRegionWidth()
  4230. {
  4231. return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x;
  4232. }
  4233. float ImGui::GetTextLineHeight()
  4234. {
  4235. ImGuiState& g = *GImGui;
  4236. return g.FontSize;
  4237. }
  4238. float ImGui::GetTextLineHeightWithSpacing()
  4239. {
  4240. ImGuiState& g = *GImGui;
  4241. return g.FontSize + g.Style.ItemSpacing.y;
  4242. }
  4243. float ImGui::GetItemsLineHeightWithSpacing()
  4244. {
  4245. ImGuiState& g = *GImGui;
  4246. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  4247. }
  4248. ImDrawList* ImGui::GetWindowDrawList()
  4249. {
  4250. ImGuiWindow* window = GetCurrentWindow();
  4251. return window->DrawList;
  4252. }
  4253. ImFont* ImGui::GetWindowFont()
  4254. {
  4255. ImGuiState& g = *GImGui;
  4256. return g.Font;
  4257. }
  4258. float ImGui::GetWindowFontSize()
  4259. {
  4260. ImGuiState& g = *GImGui;
  4261. return g.FontSize;
  4262. }
  4263. void ImGui::SetWindowFontScale(float scale)
  4264. {
  4265. ImGuiState& g = *GImGui;
  4266. ImGuiWindow* window = GetCurrentWindow();
  4267. window->FontWindowScale = scale;
  4268. g.FontSize = window->CalcFontSize();
  4269. }
  4270. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  4271. // 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'.
  4272. ImVec2 ImGui::GetCursorPos()
  4273. {
  4274. ImGuiWindow* window = GetCurrentWindowRead();
  4275. return window->DC.CursorPos - window->Pos + window->Scroll;
  4276. }
  4277. float ImGui::GetCursorPosX()
  4278. {
  4279. ImGuiWindow* window = GetCurrentWindow();
  4280. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  4281. }
  4282. float ImGui::GetCursorPosY()
  4283. {
  4284. ImGuiWindow* window = GetCurrentWindow();
  4285. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  4286. }
  4287. void ImGui::SetCursorPos(const ImVec2& local_pos)
  4288. {
  4289. ImGuiWindow* window = GetCurrentWindow();
  4290. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  4291. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  4292. }
  4293. void ImGui::SetCursorPosX(float x)
  4294. {
  4295. ImGuiWindow* window = GetCurrentWindow();
  4296. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  4297. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  4298. }
  4299. void ImGui::SetCursorPosY(float y)
  4300. {
  4301. ImGuiWindow* window = GetCurrentWindow();
  4302. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  4303. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  4304. }
  4305. ImVec2 ImGui::GetCursorStartPos()
  4306. {
  4307. ImGuiWindow* window = GetCurrentWindowRead();
  4308. return window->DC.CursorStartPos - window->Pos;
  4309. }
  4310. ImVec2 ImGui::GetCursorScreenPos()
  4311. {
  4312. ImGuiWindow* window = GetCurrentWindowRead();
  4313. return window->DC.CursorPos;
  4314. }
  4315. void ImGui::SetCursorScreenPos(const ImVec2& screen_pos)
  4316. {
  4317. ImGuiWindow* window = GetCurrentWindow();
  4318. window->DC.CursorPos = screen_pos;
  4319. }
  4320. float ImGui::GetScrollX()
  4321. {
  4322. return GImGui->CurrentWindow->Scroll.x;
  4323. }
  4324. float ImGui::GetScrollY()
  4325. {
  4326. return GImGui->CurrentWindow->Scroll.y;
  4327. }
  4328. float ImGui::GetScrollMaxX()
  4329. {
  4330. ImGuiWindow* window = GetCurrentWindowRead();
  4331. return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x;
  4332. }
  4333. float ImGui::GetScrollMaxY()
  4334. {
  4335. ImGuiWindow* window = GetCurrentWindowRead();
  4336. return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y;
  4337. }
  4338. void ImGui::SetScrollX(float scroll_x)
  4339. {
  4340. ImGuiWindow* window = GetCurrentWindow();
  4341. window->ScrollTarget.x = scroll_x;
  4342. window->ScrollTargetCenterRatio.x = 0.0f;
  4343. }
  4344. void ImGui::SetScrollY(float scroll_y)
  4345. {
  4346. ImGuiWindow* window = GetCurrentWindow();
  4347. window->ScrollTarget.y = scroll_y + window->TitleBarHeight(); // title bar height canceled out when using ScrollTargetRelY
  4348. window->ScrollTargetCenterRatio.y = 0.0f;
  4349. }
  4350. void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
  4351. {
  4352. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  4353. ImGuiWindow* window = GetCurrentWindow();
  4354. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  4355. window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
  4356. if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y)
  4357. window->ScrollTarget.y = 0.0f;
  4358. window->ScrollTargetCenterRatio.y = center_y_ratio;
  4359. }
  4360. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  4361. void ImGui::SetScrollHere(float center_y_ratio)
  4362. {
  4363. ImGuiWindow* window = GetCurrentWindow();
  4364. float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
  4365. ImGui::SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio);
  4366. }
  4367. void ImGui::SetKeyboardFocusHere(int offset)
  4368. {
  4369. ImGuiWindow* window = GetCurrentWindow();
  4370. window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
  4371. window->FocusIdxTabRequestNext = IM_INT_MAX;
  4372. }
  4373. void ImGui::SetStateStorage(ImGuiStorage* tree)
  4374. {
  4375. ImGuiWindow* window = GetCurrentWindow();
  4376. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  4377. }
  4378. ImGuiStorage* ImGui::GetStateStorage()
  4379. {
  4380. ImGuiWindow* window = GetCurrentWindowRead();
  4381. return window->DC.StateStorage;
  4382. }
  4383. void ImGui::TextV(const char* fmt, va_list args)
  4384. {
  4385. ImGuiWindow* window = GetCurrentWindow();
  4386. if (window->SkipItems)
  4387. return;
  4388. ImGuiState& g = *GImGui;
  4389. const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  4390. TextUnformatted(g.TempBuffer, text_end);
  4391. }
  4392. void ImGui::Text(const char* fmt, ...)
  4393. {
  4394. va_list args;
  4395. va_start(args, fmt);
  4396. TextV(fmt, args);
  4397. va_end(args);
  4398. }
  4399. void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
  4400. {
  4401. ImGui::PushStyleColor(ImGuiCol_Text, col);
  4402. TextV(fmt, args);
  4403. ImGui::PopStyleColor();
  4404. }
  4405. void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
  4406. {
  4407. va_list args;
  4408. va_start(args, fmt);
  4409. TextColoredV(col, fmt, args);
  4410. va_end(args);
  4411. }
  4412. void ImGui::TextDisabledV(const char* fmt, va_list args)
  4413. {
  4414. ImGui::PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
  4415. TextV(fmt, args);
  4416. ImGui::PopStyleColor();
  4417. }
  4418. void ImGui::TextDisabled(const char* fmt, ...)
  4419. {
  4420. va_list args;
  4421. va_start(args, fmt);
  4422. TextDisabledV(fmt, args);
  4423. va_end(args);
  4424. }
  4425. void ImGui::TextWrappedV(const char* fmt, va_list args)
  4426. {
  4427. ImGui::PushTextWrapPos(0.0f);
  4428. TextV(fmt, args);
  4429. ImGui::PopTextWrapPos();
  4430. }
  4431. void ImGui::TextWrapped(const char* fmt, ...)
  4432. {
  4433. va_list args;
  4434. va_start(args, fmt);
  4435. TextWrappedV(fmt, args);
  4436. va_end(args);
  4437. }
  4438. void ImGui::TextUnformatted(const char* text, const char* text_end)
  4439. {
  4440. ImGuiWindow* window = GetCurrentWindow();
  4441. if (window->SkipItems)
  4442. return;
  4443. ImGuiState& g = *GImGui;
  4444. IM_ASSERT(text != NULL);
  4445. const char* text_begin = text;
  4446. if (text_end == NULL)
  4447. text_end = text + strlen(text); // FIXME-OPT
  4448. const float wrap_pos_x = window->DC.TextWrapPos;
  4449. const bool wrap_enabled = wrap_pos_x >= 0.0f;
  4450. if (text_end - text > 2000 && !wrap_enabled)
  4451. {
  4452. // Long text!
  4453. // Perform manual coarse clipping to optimize for long multi-line text
  4454. // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
  4455. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
  4456. const char* line = text;
  4457. const float line_height = ImGui::GetTextLineHeight();
  4458. const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset);
  4459. const ImRect clip_rect = window->ClipRect;
  4460. ImVec2 text_size(0,0);
  4461. if (text_pos.y <= clip_rect.Max.y)
  4462. {
  4463. ImVec2 pos = text_pos;
  4464. // Lines to skip (can't skip when logging text)
  4465. if (!g.LogEnabled)
  4466. {
  4467. int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height);
  4468. if (lines_skippable > 0)
  4469. {
  4470. int lines_skipped = 0;
  4471. while (line < text_end && lines_skipped < lines_skippable)
  4472. {
  4473. const char* line_end = strchr(line, '\n');
  4474. if (!line_end)
  4475. line_end = text_end;
  4476. line = line_end + 1;
  4477. lines_skipped++;
  4478. }
  4479. pos.y += lines_skipped * line_height;
  4480. }
  4481. }
  4482. // Lines to render
  4483. if (line < text_end)
  4484. {
  4485. ImRect line_rect(pos, pos + ImVec2(ImGui::GetWindowWidth(), line_height));
  4486. while (line < text_end)
  4487. {
  4488. const char* line_end = strchr(line, '\n');
  4489. if (IsClippedEx(line_rect, NULL, false))
  4490. break;
  4491. const ImVec2 line_size = CalcTextSize(line, line_end, false);
  4492. text_size.x = ImMax(text_size.x, line_size.x);
  4493. RenderText(pos, line, line_end, false);
  4494. if (!line_end)
  4495. line_end = text_end;
  4496. line = line_end + 1;
  4497. line_rect.Min.y += line_height;
  4498. line_rect.Max.y += line_height;
  4499. pos.y += line_height;
  4500. }
  4501. // Count remaining lines
  4502. int lines_skipped = 0;
  4503. while (line < text_end)
  4504. {
  4505. const char* line_end = strchr(line, '\n');
  4506. if (!line_end)
  4507. line_end = text_end;
  4508. line = line_end + 1;
  4509. lines_skipped++;
  4510. }
  4511. pos.y += lines_skipped * line_height;
  4512. }
  4513. text_size.y += (pos - text_pos).y;
  4514. }
  4515. ImRect bb(text_pos, text_pos + text_size);
  4516. ItemSize(bb);
  4517. ItemAdd(bb, NULL);
  4518. }
  4519. else
  4520. {
  4521. const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
  4522. const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
  4523. // Account of baseline offset
  4524. ImVec2 text_pos = window->DC.CursorPos;
  4525. text_pos.y += window->DC.CurrentLineTextBaseOffset;
  4526. ImRect bb(text_pos, text_pos + text_size);
  4527. ItemSize(text_size);
  4528. if (!ItemAdd(bb, NULL))
  4529. return;
  4530. // Render (we don't hide text after ## in this end-user function)
  4531. RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
  4532. }
  4533. }
  4534. void ImGui::AlignFirstTextHeightToWidgets()
  4535. {
  4536. ImGuiWindow* window = GetCurrentWindow();
  4537. if (window->SkipItems)
  4538. return;
  4539. // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height.
  4540. ImGuiState& g = *GImGui;
  4541. ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y);
  4542. ImGui::SameLine(0, 0);
  4543. }
  4544. // Add a label+text combo aligned to other label+value widgets
  4545. void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
  4546. {
  4547. ImGuiWindow* window = GetCurrentWindow();
  4548. if (window->SkipItems)
  4549. return;
  4550. ImGuiState& g = *GImGui;
  4551. const ImGuiStyle& style = g.Style;
  4552. const float w = CalcItemWidth();
  4553. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  4554. const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
  4555. const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size);
  4556. ItemSize(total_bb, style.FramePadding.y);
  4557. if (!ItemAdd(total_bb, NULL))
  4558. return;
  4559. // Render
  4560. const char* value_text_begin = &g.TempBuffer[0];
  4561. const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  4562. RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImGuiAlign_VCenter);
  4563. if (label_size.x > 0.0f)
  4564. RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
  4565. }
  4566. void ImGui::LabelText(const char* label, const char* fmt, ...)
  4567. {
  4568. va_list args;
  4569. va_start(args, fmt);
  4570. LabelTextV(label, fmt, args);
  4571. va_end(args);
  4572. }
  4573. static inline bool IsWindowContentHoverable(ImGuiWindow* window)
  4574. {
  4575. // An active popup disable hovering on other windows (apart from its own children)
  4576. ImGuiState& g = *GImGui;
  4577. if (ImGuiWindow* focused_window = g.FocusedWindow)
  4578. if (ImGuiWindow* focused_root_window = focused_window->RootWindow)
  4579. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow)
  4580. return false;
  4581. return true;
  4582. }
  4583. bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
  4584. {
  4585. ImGuiState& g = *GImGui;
  4586. ImGuiWindow* window = GetCurrentWindow();
  4587. if (flags & ImGuiButtonFlags_Disabled)
  4588. {
  4589. if (out_hovered) *out_hovered = false;
  4590. if (out_held) *out_held = false;
  4591. if (g.ActiveId == id) SetActiveID(0);
  4592. return false;
  4593. }
  4594. bool pressed = false;
  4595. const bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0);
  4596. if (hovered)
  4597. {
  4598. SetHoveredID(id);
  4599. if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
  4600. {
  4601. if (g.IO.MouseClicked[0])
  4602. {
  4603. if (flags & ImGuiButtonFlags_PressedOnClick)
  4604. {
  4605. pressed = true;
  4606. SetActiveID(0);
  4607. }
  4608. else
  4609. {
  4610. SetActiveID(id, window);
  4611. }
  4612. FocusWindow(window);
  4613. }
  4614. else if (g.IO.MouseReleased[0] && (flags & ImGuiButtonFlags_PressedOnRelease))
  4615. {
  4616. pressed = true;
  4617. SetActiveID(0);
  4618. }
  4619. else if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && ImGui::IsMouseClicked(0, true))
  4620. {
  4621. pressed = true;
  4622. }
  4623. }
  4624. }
  4625. bool held = false;
  4626. if (g.ActiveId == id)
  4627. {
  4628. if (g.IO.MouseDown[0])
  4629. {
  4630. held = true;
  4631. }
  4632. else
  4633. {
  4634. if (hovered)
  4635. pressed = true;
  4636. SetActiveID(0);
  4637. }
  4638. }
  4639. if (out_hovered) *out_hovered = hovered;
  4640. if (out_held) *out_held = held;
  4641. return pressed;
  4642. }
  4643. bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
  4644. {
  4645. ImGuiWindow* window = GetCurrentWindow();
  4646. if (window->SkipItems)
  4647. return false;
  4648. ImGuiState& g = *GImGui;
  4649. const ImGuiStyle& style = g.Style;
  4650. const ImGuiID id = window->GetID(label);
  4651. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  4652. ImVec2 pos = window->DC.CursorPos;
  4653. if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset)
  4654. pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;
  4655. ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
  4656. const ImRect bb(pos, pos + size);
  4657. ItemSize(bb, style.FramePadding.y);
  4658. if (!ItemAdd(bb, &id))
  4659. return false;
  4660. if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;
  4661. bool hovered, held;
  4662. bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
  4663. // Render
  4664. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  4665. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  4666. RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, ImGuiAlign_Center | ImGuiAlign_VCenter);
  4667. // Automatically close popups
  4668. //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  4669. // ImGui::CloseCurrentPopup();
  4670. return pressed;
  4671. }
  4672. bool ImGui::Button(const char* label, const ImVec2& size_arg)
  4673. {
  4674. return ButtonEx(label, size_arg, 0);
  4675. }
  4676. // Small buttons fits within text without additional vertical spacing.
  4677. bool ImGui::SmallButton(const char* label)
  4678. {
  4679. ImGuiState& g = *GImGui;
  4680. float backup_padding_y = g.Style.FramePadding.y;
  4681. g.Style.FramePadding.y = 0.0f;
  4682. bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine);
  4683. g.Style.FramePadding.y = backup_padding_y;
  4684. return pressed;
  4685. }
  4686. // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
  4687. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
  4688. bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
  4689. {
  4690. ImGuiWindow* window = GetCurrentWindow();
  4691. if (window->SkipItems)
  4692. return false;
  4693. const ImGuiID id = window->GetID(str_id);
  4694. ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
  4695. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  4696. ItemSize(bb);
  4697. if (!ItemAdd(bb, &id))
  4698. return false;
  4699. bool hovered, held;
  4700. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  4701. return pressed;
  4702. }
  4703. // Upper-right button to close a window.
  4704. static bool CloseWindowButton(bool* p_opened)
  4705. {
  4706. ImGuiWindow* window = ImGui::GetCurrentWindow();
  4707. const ImGuiID id = window->GetID("#CLOSE");
  4708. const float size = window->TitleBarHeight() - 4.0f;
  4709. const ImRect bb(window->Rect().GetTR() + ImVec2(-2.0f-size,2.0f), window->Rect().GetTR() + ImVec2(-2.0f,2.0f+size));
  4710. bool hovered, held;
  4711. bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held);
  4712. // Render
  4713. const ImU32 col = ImGui::GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
  4714. const ImVec2 center = bb.GetCenter();
  4715. window->DrawList->AddCircleFilled(center, ImMax(2.0f,size*0.5f), col, 16);
  4716. const float cross_extent = (size * 0.5f * 0.7071f) - 1.0f;
  4717. if (hovered)
  4718. {
  4719. window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), ImGui::GetColorU32(ImGuiCol_Text));
  4720. window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), ImGui::GetColorU32(ImGuiCol_Text));
  4721. }
  4722. if (p_opened != NULL && pressed)
  4723. *p_opened = false;
  4724. return pressed;
  4725. }
  4726. void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
  4727. {
  4728. ImGuiWindow* window = GetCurrentWindow();
  4729. if (window->SkipItems)
  4730. return;
  4731. ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  4732. if (border_col.w > 0.0f)
  4733. bb.Max += ImVec2(2,2);
  4734. ItemSize(bb);
  4735. if (!ItemAdd(bb, NULL))
  4736. return;
  4737. if (border_col.w > 0.0f)
  4738. {
  4739. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
  4740. window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col));
  4741. }
  4742. else
  4743. {
  4744. window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
  4745. }
  4746. }
  4747. // frame_padding < 0: uses FramePadding from style (default)
  4748. // frame_padding = 0: no framing
  4749. // frame_padding > 0: set framing size
  4750. // The color used are the button colors.
  4751. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
  4752. {
  4753. ImGuiWindow* window = GetCurrentWindow();
  4754. if (window->SkipItems)
  4755. return false;
  4756. ImGuiState& g = *GImGui;
  4757. const ImGuiStyle& style = g.Style;
  4758. // Default to using texture ID as ID. User can still push string/integer prefixes.
  4759. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
  4760. ImGui::PushID((void *)user_texture_id);
  4761. const ImGuiID id = window->GetID("#image");
  4762. ImGui::PopID();
  4763. const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
  4764. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2);
  4765. const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
  4766. ItemSize(bb);
  4767. if (!ItemAdd(bb, &id))
  4768. return false;
  4769. bool hovered, held;
  4770. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  4771. // Render
  4772. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  4773. RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
  4774. if (bg_col.w > 0.0f)
  4775. window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
  4776. window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
  4777. return pressed;
  4778. }
  4779. // Start logging ImGui output to TTY
  4780. void ImGui::LogToTTY(int max_depth)
  4781. {
  4782. ImGuiState& g = *GImGui;
  4783. if (g.LogEnabled)
  4784. return;
  4785. ImGuiWindow* window = GetCurrentWindowRead();
  4786. g.LogEnabled = true;
  4787. g.LogFile = stdout;
  4788. g.LogStartDepth = window->DC.TreeDepth;
  4789. if (max_depth >= 0)
  4790. g.LogAutoExpandMaxDepth = max_depth;
  4791. }
  4792. // Start logging ImGui output to given file
  4793. void ImGui::LogToFile(int max_depth, const char* filename)
  4794. {
  4795. ImGuiState& g = *GImGui;
  4796. if (g.LogEnabled)
  4797. return;
  4798. ImGuiWindow* window = GetCurrentWindowRead();
  4799. if (!filename)
  4800. {
  4801. filename = g.IO.LogFilename;
  4802. if (!filename)
  4803. return;
  4804. }
  4805. g.LogFile = fopen(filename, "ab");
  4806. if (!g.LogFile)
  4807. {
  4808. IM_ASSERT(g.LogFile != NULL); // Consider this an error
  4809. return;
  4810. }
  4811. g.LogEnabled = true;
  4812. g.LogStartDepth = window->DC.TreeDepth;
  4813. if (max_depth >= 0)
  4814. g.LogAutoExpandMaxDepth = max_depth;
  4815. }
  4816. // Start logging ImGui output to clipboard
  4817. void ImGui::LogToClipboard(int max_depth)
  4818. {
  4819. ImGuiState& g = *GImGui;
  4820. if (g.LogEnabled)
  4821. return;
  4822. ImGuiWindow* window = GetCurrentWindowRead();
  4823. g.LogEnabled = true;
  4824. g.LogFile = NULL;
  4825. g.LogStartDepth = window->DC.TreeDepth;
  4826. if (max_depth >= 0)
  4827. g.LogAutoExpandMaxDepth = max_depth;
  4828. }
  4829. void ImGui::LogFinish()
  4830. {
  4831. ImGuiState& g = *GImGui;
  4832. if (!g.LogEnabled)
  4833. return;
  4834. ImGui::LogText(IM_NEWLINE);
  4835. g.LogEnabled = false;
  4836. if (g.LogFile != NULL)
  4837. {
  4838. if (g.LogFile == stdout)
  4839. fflush(g.LogFile);
  4840. else
  4841. fclose(g.LogFile);
  4842. g.LogFile = NULL;
  4843. }
  4844. if (g.LogClipboard->size() > 1)
  4845. {
  4846. if (g.IO.SetClipboardTextFn)
  4847. g.IO.SetClipboardTextFn(g.LogClipboard->begin());
  4848. g.LogClipboard->clear();
  4849. }
  4850. }
  4851. // Helper to display logging buttons
  4852. void ImGui::LogButtons()
  4853. {
  4854. ImGuiState& g = *GImGui;
  4855. ImGui::PushID("LogButtons");
  4856. const bool log_to_tty = ImGui::Button("Log To TTY");
  4857. ImGui::SameLine();
  4858. const bool log_to_file = ImGui::Button("Log To File");
  4859. ImGui::SameLine();
  4860. const bool log_to_clipboard = ImGui::Button("Log To Clipboard");
  4861. ImGui::SameLine();
  4862. ImGui::PushItemWidth(80.0f);
  4863. ImGui::PushAllowKeyboardFocus(false);
  4864. ImGui::SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
  4865. ImGui::PopAllowKeyboardFocus();
  4866. ImGui::PopItemWidth();
  4867. ImGui::PopID();
  4868. // Start logging at the end of the function so that the buttons don't appear in the log
  4869. if (log_to_tty)
  4870. LogToTTY(g.LogAutoExpandMaxDepth);
  4871. if (log_to_file)
  4872. LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
  4873. if (log_to_clipboard)
  4874. LogToClipboard(g.LogAutoExpandMaxDepth);
  4875. }
  4876. bool ImGui::TreeNodeBehaviorIsOpened(ImGuiID id, ImGuiTreeNodeFlags flags)
  4877. {
  4878. // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions)
  4879. ImGuiState& g = *GImGui;
  4880. ImGuiWindow* window = g.CurrentWindow;
  4881. ImGuiStorage* storage = window->DC.StateStorage;
  4882. bool opened;
  4883. if (g.SetNextTreeNodeOpenedCond != 0)
  4884. {
  4885. if (g.SetNextTreeNodeOpenedCond & ImGuiSetCond_Always)
  4886. {
  4887. opened = g.SetNextTreeNodeOpenedVal;
  4888. storage->SetInt(id, opened);
  4889. }
  4890. else
  4891. {
  4892. // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently.
  4893. const int stored_value = storage->GetInt(id, -1);
  4894. if (stored_value == -1)
  4895. {
  4896. opened = g.SetNextTreeNodeOpenedVal;
  4897. storage->SetInt(id, opened);
  4898. }
  4899. else
  4900. {
  4901. opened = stored_value != 0;
  4902. }
  4903. }
  4904. g.SetNextTreeNodeOpenedCond = 0;
  4905. }
  4906. else
  4907. {
  4908. opened = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
  4909. }
  4910. // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
  4911. // NB- If we are above max depth we still allow manually opened nodes to be logged.
  4912. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoExpandOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth)
  4913. opened = true;
  4914. return opened;
  4915. }
  4916. // FIXME: Split into CollapsingHeader(label, default_open?) and TreeNodeBehavior(label), obsolete the 4 parameters function.
  4917. bool ImGui::CollapsingHeader(const char* label, const char* str_id, bool display_frame, bool default_open)
  4918. {
  4919. ImGuiWindow* window = GetCurrentWindow();
  4920. if (window->SkipItems)
  4921. return false;
  4922. ImGuiState& g = *GImGui;
  4923. const ImGuiStyle& style = g.Style;
  4924. const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
  4925. IM_ASSERT(str_id != NULL || label != NULL);
  4926. if (str_id == NULL)
  4927. str_id = label;
  4928. if (label == NULL)
  4929. label = str_id;
  4930. const bool label_hide_text_after_double_hash = (label == str_id); // Only search and hide text after ## if we have passed label and ID separately, otherwise allow "##" within format string.
  4931. const ImGuiID id = window->GetID(str_id);
  4932. const ImVec2 label_size = CalcTextSize(label, NULL, label_hide_text_after_double_hash);
  4933. // We vertically grow up to current line height up the typical widget height.
  4934. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it
  4935. const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), label_size.y + padding.y*2);
  4936. ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
  4937. if (display_frame)
  4938. {
  4939. // Framed header expand a little outside the default padding
  4940. bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
  4941. bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
  4942. }
  4943. const float collapser_width = g.FontSize + (display_frame ? padding.x*2 : padding.x);
  4944. const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
  4945. ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
  4946. // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
  4947. // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not)
  4948. const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y);
  4949. bool opened = TreeNodeBehaviorIsOpened(id, (default_open ? ImGuiTreeNodeFlags_DefaultOpen : 0) | (display_frame ? ImGuiTreeNodeFlags_NoAutoExpandOnLog : 0));
  4950. if (!ItemAdd(interact_bb, &id))
  4951. return opened;
  4952. bool hovered, held;
  4953. bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, ImGuiButtonFlags_NoKeyModifiers);
  4954. if (pressed)
  4955. {
  4956. opened = !opened;
  4957. window->DC.StateStorage->SetInt(id, opened);
  4958. }
  4959. // Render
  4960. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  4961. const ImVec2 text_pos = bb.Min + padding + ImVec2(collapser_width, text_base_offset_y);
  4962. if (display_frame)
  4963. {
  4964. // Framed type
  4965. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  4966. RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), opened, 1.0f, true);
  4967. if (g.LogEnabled)
  4968. {
  4969. // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
  4970. const char log_prefix[] = "\n##";
  4971. const char log_suffix[] = "##";
  4972. LogRenderedText(text_pos, log_prefix, log_prefix+3);
  4973. RenderTextClipped(text_pos, bb.Max, label, NULL, &label_size);
  4974. LogRenderedText(text_pos, log_suffix+1, log_suffix+3);
  4975. }
  4976. else
  4977. {
  4978. RenderTextClipped(text_pos, bb.Max, label, NULL, &label_size);
  4979. }
  4980. }
  4981. else
  4982. {
  4983. // Unframed typed for tree nodes
  4984. if (hovered)
  4985. RenderFrame(bb.Min, bb.Max, col, false);
  4986. RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), opened, 0.70f, false);
  4987. if (g.LogEnabled)
  4988. LogRenderedText(text_pos, ">");
  4989. RenderText(text_pos, label, NULL, label_hide_text_after_double_hash);
  4990. }
  4991. return opened;
  4992. }
  4993. void ImGui::Bullet()
  4994. {
  4995. ImGuiWindow* window = GetCurrentWindow();
  4996. if (window->SkipItems)
  4997. return;
  4998. ImGuiState& g = *GImGui;
  4999. const ImGuiStyle& style = g.Style;
  5000. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  5001. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
  5002. ItemSize(bb);
  5003. if (!ItemAdd(bb, NULL))
  5004. {
  5005. ImGui::SameLine(0, style.FramePadding.x*2);
  5006. return;
  5007. }
  5008. // Render
  5009. const float bullet_size = g.FontSize*0.15f;
  5010. window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), bullet_size, GetColorU32(ImGuiCol_Text));
  5011. // Stay on same line
  5012. ImGui::SameLine(0, style.FramePadding.x*2);
  5013. }
  5014. // Text with a little bullet aligned to the typical tree node.
  5015. void ImGui::BulletTextV(const char* fmt, va_list args)
  5016. {
  5017. ImGuiWindow* window = GetCurrentWindow();
  5018. if (window->SkipItems)
  5019. return;
  5020. ImGuiState& g = *GImGui;
  5021. const ImGuiStyle& style = g.Style;
  5022. const char* text_begin = g.TempBuffer;
  5023. const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5024. const ImVec2 label_size = CalcTextSize(text_begin, text_end, true);
  5025. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
  5026. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  5027. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding
  5028. ItemSize(bb);
  5029. if (!ItemAdd(bb, NULL))
  5030. return;
  5031. // Render
  5032. const float bullet_size = g.FontSize*0.15f;
  5033. window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), bullet_size, GetColorU32(ImGuiCol_Text));
  5034. RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end);
  5035. }
  5036. void ImGui::BulletText(const char* fmt, ...)
  5037. {
  5038. va_list args;
  5039. va_start(args, fmt);
  5040. BulletTextV(fmt, args);
  5041. va_end(args);
  5042. }
  5043. // If returning 'true' the node is open and the user is responsible for calling TreePop
  5044. bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
  5045. {
  5046. ImGuiWindow* window = GetCurrentWindow();
  5047. if (window->SkipItems)
  5048. return false;
  5049. ImGuiState& g = *GImGui;
  5050. ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5051. if (!str_id || !str_id[0])
  5052. str_id = fmt;
  5053. ImGui::PushID(str_id);
  5054. const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false);
  5055. ImGui::PopID();
  5056. if (opened)
  5057. ImGui::TreePush(str_id);
  5058. return opened;
  5059. }
  5060. bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
  5061. {
  5062. va_list args;
  5063. va_start(args, fmt);
  5064. bool s = TreeNodeV(str_id, fmt, args);
  5065. va_end(args);
  5066. return s;
  5067. }
  5068. // If returning 'true' the node is open and the user is responsible for calling TreePop
  5069. bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
  5070. {
  5071. ImGuiWindow* window = GetCurrentWindow();
  5072. if (window->SkipItems)
  5073. return false;
  5074. ImGuiState& g = *GImGui;
  5075. ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5076. if (!ptr_id)
  5077. ptr_id = fmt;
  5078. ImGui::PushID(ptr_id);
  5079. const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false);
  5080. ImGui::PopID();
  5081. if (opened)
  5082. ImGui::TreePush(ptr_id);
  5083. return opened;
  5084. }
  5085. bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
  5086. {
  5087. va_list args;
  5088. va_start(args, fmt);
  5089. bool s = TreeNodeV(ptr_id, fmt, args);
  5090. va_end(args);
  5091. return s;
  5092. }
  5093. bool ImGui::TreeNode(const char* str_label_id)
  5094. {
  5095. return TreeNode(str_label_id, "%s", str_label_id);
  5096. }
  5097. void ImGui::SetNextTreeNodeOpened(bool opened, ImGuiSetCond cond)
  5098. {
  5099. ImGuiState& g = *GImGui;
  5100. g.SetNextTreeNodeOpenedVal = opened;
  5101. g.SetNextTreeNodeOpenedCond = cond ? cond : ImGuiSetCond_Always;
  5102. }
  5103. void ImGui::PushID(const char* str_id)
  5104. {
  5105. ImGuiWindow* window = GetCurrentWindow();
  5106. window->IDStack.push_back(window->GetID(str_id));
  5107. }
  5108. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  5109. {
  5110. ImGuiWindow* window = GetCurrentWindow();
  5111. window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
  5112. }
  5113. void ImGui::PushID(const void* ptr_id)
  5114. {
  5115. ImGuiWindow* window = GetCurrentWindow();
  5116. window->IDStack.push_back(window->GetID(ptr_id));
  5117. }
  5118. void ImGui::PushID(int int_id)
  5119. {
  5120. const void* ptr_id = (void*)(intptr_t)int_id;
  5121. ImGuiWindow* window = GetCurrentWindow();
  5122. window->IDStack.push_back(window->GetID(ptr_id));
  5123. }
  5124. void ImGui::PopID()
  5125. {
  5126. ImGuiWindow* window = GetCurrentWindow();
  5127. window->IDStack.pop_back();
  5128. }
  5129. ImGuiID ImGui::GetID(const char* str_id)
  5130. {
  5131. return GImGui->CurrentWindow->GetID(str_id);
  5132. }
  5133. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  5134. {
  5135. return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
  5136. }
  5137. ImGuiID ImGui::GetID(const void* ptr_id)
  5138. {
  5139. return GImGui->CurrentWindow->GetID(ptr_id);
  5140. }
  5141. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
  5142. {
  5143. if (data_type == ImGuiDataType_Int)
  5144. ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
  5145. else if (data_type == ImGuiDataType_Float)
  5146. ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
  5147. }
  5148. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
  5149. {
  5150. if (data_type == ImGuiDataType_Int)
  5151. {
  5152. if (decimal_precision < 0)
  5153. ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
  5154. else
  5155. ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
  5156. }
  5157. else if (data_type == ImGuiDataType_Float)
  5158. {
  5159. if (decimal_precision < 0)
  5160. ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits?
  5161. else
  5162. ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
  5163. }
  5164. }
  5165. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
  5166. {
  5167. if (data_type == ImGuiDataType_Int)
  5168. {
  5169. if (op == '+')
  5170. *(int*)value1 = *(int*)value1 + *(const int*)value2;
  5171. else if (op == '-')
  5172. *(int*)value1 = *(int*)value1 - *(const int*)value2;
  5173. }
  5174. else if (data_type == ImGuiDataType_Float)
  5175. {
  5176. if (op == '+')
  5177. *(float*)value1 = *(float*)value1 + *(const float*)value2;
  5178. else if (op == '-')
  5179. *(float*)value1 = *(float*)value1 - *(const float*)value2;
  5180. }
  5181. }
  5182. // User can input math operators (e.g. +100) to edit a numerical values.
  5183. static void DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
  5184. {
  5185. while (ImCharIsSpace(*buf))
  5186. buf++;
  5187. // We don't support '-' op because it would conflict with inputing negative value.
  5188. // Instead you can use +-100 to subtract from an existing value
  5189. char op = buf[0];
  5190. if (op == '+' || op == '*' || op == '/')
  5191. {
  5192. buf++;
  5193. while (ImCharIsSpace(*buf))
  5194. buf++;
  5195. }
  5196. else
  5197. {
  5198. op = 0;
  5199. }
  5200. if (!buf[0])
  5201. return;
  5202. if (data_type == ImGuiDataType_Int)
  5203. {
  5204. if (!scalar_format)
  5205. scalar_format = "%d";
  5206. int* v = (int*)data_ptr;
  5207. int ref_v = *v;
  5208. if (op && sscanf(initial_value_buf, scalar_format, &ref_v) < 1)
  5209. return;
  5210. // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
  5211. float op_v = 0.0f;
  5212. if (op == '+') { if (sscanf(buf, "%f", &op_v) == 1) *v = (int)(ref_v + op_v); } // Add (use "+-" to subtract)
  5213. else if (op == '*') { if (sscanf(buf, "%f", &op_v) == 1) *v = (int)(ref_v * op_v); } // Multiply
  5214. else if (op == '/') { if (sscanf(buf, "%f", &op_v) == 1 && op_v != 0.0f) *v = (int)(ref_v / op_v); }// Divide
  5215. else { if (sscanf(buf, scalar_format, &ref_v) == 1) *v = ref_v; } // Assign constant
  5216. }
  5217. else if (data_type == ImGuiDataType_Float)
  5218. {
  5219. // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
  5220. scalar_format = "%f";
  5221. float* v = (float*)data_ptr;
  5222. float ref_v = *v;
  5223. if (op && sscanf(initial_value_buf, scalar_format, &ref_v) < 1)
  5224. return;
  5225. float op_v = 0.0f;
  5226. if (sscanf(buf, scalar_format, &op_v) < 1)
  5227. return;
  5228. if (op == '+') { *v = ref_v + op_v; } // Add (use "+-" to subtract)
  5229. else if (op == '*') { *v = ref_v * op_v; } // Multiply
  5230. else if (op == '/') { if (op_v != 0.0f) *v = ref_v / op_v; } // Divide
  5231. else { *v = op_v; } // Assign constant
  5232. }
  5233. }
  5234. // Create text input in place of a slider (when CTRL+Clicking on slider)
  5235. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
  5236. {
  5237. ImGuiState& g = *GImGui;
  5238. ImGuiWindow* window = GetCurrentWindow();
  5239. // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
  5240. SetActiveID(g.ScalarAsInputTextId, window);
  5241. SetHoveredID(0);
  5242. FocusableItemUnregister(window);
  5243. char buf[32];
  5244. DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
  5245. bool value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
  5246. if (g.ScalarAsInputTextId == 0)
  5247. {
  5248. // First frame
  5249. IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible)
  5250. g.ScalarAsInputTextId = g.ActiveId;
  5251. SetHoveredID(id);
  5252. }
  5253. else if (g.ActiveId != g.ScalarAsInputTextId)
  5254. {
  5255. // Release
  5256. g.ScalarAsInputTextId = 0;
  5257. }
  5258. if (value_changed)
  5259. DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
  5260. return value_changed;
  5261. }
  5262. // Parse display precision back from the display format string
  5263. int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
  5264. {
  5265. int precision = default_precision;
  5266. while ((fmt = strchr(fmt, '%')) != NULL)
  5267. {
  5268. fmt++;
  5269. if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
  5270. while (*fmt >= '0' && *fmt <= '9')
  5271. fmt++;
  5272. if (*fmt == '.')
  5273. {
  5274. precision = atoi(fmt + 1);
  5275. if (precision < 0 || precision > 10)
  5276. precision = default_precision;
  5277. }
  5278. break;
  5279. }
  5280. return precision;
  5281. }
  5282. float ImGui::RoundScalar(float value, int decimal_precision)
  5283. {
  5284. // Round past decimal precision
  5285. // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
  5286. // FIXME: Investigate better rounding methods
  5287. static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
  5288. float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
  5289. bool negative = value < 0.0f;
  5290. value = fabsf(value);
  5291. float remainder = fmodf(value, min_step);
  5292. if (remainder <= min_step*0.5f)
  5293. value -= remainder;
  5294. else
  5295. value += (min_step - remainder);
  5296. return negative ? -value : value;
  5297. }
  5298. bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
  5299. {
  5300. ImGuiState& g = *GImGui;
  5301. ImGuiWindow* window = GetCurrentWindow();
  5302. const ImGuiStyle& style = g.Style;
  5303. // Draw frame
  5304. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  5305. const bool is_non_linear = fabsf(power - 1.0f) > 0.0001f;
  5306. const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
  5307. const float grab_padding = 2.0f;
  5308. const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
  5309. float grab_sz;
  5310. if (decimal_precision > 0)
  5311. grab_sz = ImMin(style.GrabMinSize, slider_sz);
  5312. else
  5313. grab_sz = ImMin(ImMax(1.0f * (slider_sz / (v_max-v_min+1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
  5314. const float slider_usable_sz = slider_sz - grab_sz;
  5315. const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
  5316. const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
  5317. // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
  5318. float linear_zero_pos = 0.0f; // 0.0->1.0f
  5319. if (v_min * v_max < 0.0f)
  5320. {
  5321. // Different sign
  5322. const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power);
  5323. const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power);
  5324. linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0);
  5325. }
  5326. else
  5327. {
  5328. // Same sign
  5329. linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
  5330. }
  5331. // Process clicking on the slider
  5332. bool value_changed = false;
  5333. if (g.ActiveId == id)
  5334. {
  5335. if (g.IO.MouseDown[0])
  5336. {
  5337. const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  5338. float normalized_pos = ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f);
  5339. if (!is_horizontal)
  5340. normalized_pos = 1.0f - normalized_pos;
  5341. float new_value;
  5342. if (is_non_linear)
  5343. {
  5344. // Account for logarithmic scale on both sides of the zero
  5345. if (normalized_pos < linear_zero_pos)
  5346. {
  5347. // Negative: rescale to the negative range before powering
  5348. float a = 1.0f - (normalized_pos / linear_zero_pos);
  5349. a = powf(a, power);
  5350. new_value = ImLerp(ImMin(v_max,0.0f), v_min, a);
  5351. }
  5352. else
  5353. {
  5354. // Positive: rescale to the positive range before powering
  5355. float a;
  5356. if (fabsf(linear_zero_pos - 1.0f) > 1.e-6)
  5357. a = (normalized_pos - linear_zero_pos) / (1.0f - linear_zero_pos);
  5358. else
  5359. a = normalized_pos;
  5360. a = powf(a, power);
  5361. new_value = ImLerp(ImMax(v_min,0.0f), v_max, a);
  5362. }
  5363. }
  5364. else
  5365. {
  5366. // Linear slider
  5367. new_value = ImLerp(v_min, v_max, normalized_pos);
  5368. }
  5369. // Round past decimal precision
  5370. new_value = RoundScalar(new_value, decimal_precision);
  5371. if (*v != new_value)
  5372. {
  5373. *v = new_value;
  5374. value_changed = true;
  5375. }
  5376. }
  5377. else
  5378. {
  5379. SetActiveID(0);
  5380. }
  5381. }
  5382. // Calculate slider grab positioning
  5383. float grab_t;
  5384. if (is_non_linear)
  5385. {
  5386. float v_clamped = ImClamp(*v, v_min, v_max);
  5387. if (v_clamped < 0.0f)
  5388. {
  5389. const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min);
  5390. grab_t = (1.0f - powf(f, 1.0f/power)) * linear_zero_pos;
  5391. }
  5392. else
  5393. {
  5394. const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min));
  5395. grab_t = linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos);
  5396. }
  5397. }
  5398. else
  5399. {
  5400. // Linear slider
  5401. grab_t = (ImClamp(*v, v_min, v_max) - v_min) / (v_max - v_min);
  5402. }
  5403. // Draw
  5404. if (!is_horizontal)
  5405. grab_t = 1.0f - grab_t;
  5406. const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
  5407. ImRect grab_bb;
  5408. if (is_horizontal)
  5409. grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding));
  5410. else
  5411. grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f));
  5412. window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
  5413. return value_changed;
  5414. }
  5415. // Use power!=1.0 for logarithmic sliders.
  5416. // Adjust display_format to decorate the value with a prefix or a suffix.
  5417. // "%.3f" 1.234
  5418. // "%5.2f secs" 01.23 secs
  5419. // "Gold: %.0f" Gold: 1
  5420. bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
  5421. {
  5422. ImGuiWindow* window = GetCurrentWindow();
  5423. if (window->SkipItems)
  5424. return false;
  5425. ImGuiState& g = *GImGui;
  5426. const ImGuiStyle& style = g.Style;
  5427. const ImGuiID id = window->GetID(label);
  5428. const float w = CalcItemWidth();
  5429. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5430. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  5431. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  5432. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  5433. if (!ItemAdd(total_bb, &id))
  5434. {
  5435. ItemSize(total_bb, style.FramePadding.y);
  5436. return false;
  5437. }
  5438. const bool hovered = IsHovered(frame_bb, id);
  5439. if (hovered)
  5440. SetHoveredID(id);
  5441. if (!display_format)
  5442. display_format = "%.3f";
  5443. int decimal_precision = ParseFormatPrecision(display_format, 3);
  5444. // Tabbing or CTRL-clicking on Slider turns it into an input box
  5445. bool start_text_input = false;
  5446. const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
  5447. if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
  5448. {
  5449. SetActiveID(id, window);
  5450. FocusWindow(window);
  5451. if (tab_focus_requested || g.IO.KeyCtrl)
  5452. {
  5453. start_text_input = true;
  5454. g.ScalarAsInputTextId = 0;
  5455. }
  5456. }
  5457. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  5458. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  5459. ItemSize(total_bb, style.FramePadding.y);
  5460. // Actual slider behavior + render grab
  5461. const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
  5462. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  5463. char value_buf[64];
  5464. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  5465. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter);
  5466. if (label_size.x > 0.0f)
  5467. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  5468. return value_changed;
  5469. }
  5470. bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power)
  5471. {
  5472. ImGuiWindow* window = GetCurrentWindow();
  5473. if (window->SkipItems)
  5474. return false;
  5475. ImGuiState& g = *GImGui;
  5476. const ImGuiStyle& style = g.Style;
  5477. const ImGuiID id = window->GetID(label);
  5478. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5479. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  5480. const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  5481. ItemSize(bb, style.FramePadding.y);
  5482. if (!ItemAdd(frame_bb, &id))
  5483. return false;
  5484. const bool hovered = IsHovered(frame_bb, id);
  5485. if (hovered)
  5486. SetHoveredID(id);
  5487. if (!display_format)
  5488. display_format = "%.3f";
  5489. int decimal_precision = ParseFormatPrecision(display_format, 3);
  5490. if (hovered && g.IO.MouseClicked[0])
  5491. {
  5492. SetActiveID(id, window);
  5493. FocusWindow(window);
  5494. }
  5495. // Actual slider behavior + render grab
  5496. bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
  5497. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  5498. // For the vertical slider we allow centered text to overlap the frame padding
  5499. char value_buf[64];
  5500. char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  5501. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center);
  5502. if (label_size.x > 0.0f)
  5503. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  5504. return value_changed;
  5505. }
  5506. bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
  5507. {
  5508. float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
  5509. bool value_changed = ImGui::SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f);
  5510. *v_rad = v_deg * (2*IM_PI) / 360.0f;
  5511. return value_changed;
  5512. }
  5513. bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format)
  5514. {
  5515. if (!display_format)
  5516. display_format = "%.0f";
  5517. float v_f = (float)*v;
  5518. bool value_changed = ImGui::SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  5519. *v = (int)v_f;
  5520. return value_changed;
  5521. }
  5522. bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
  5523. {
  5524. if (!display_format)
  5525. display_format = "%.0f";
  5526. float v_f = (float)*v;
  5527. bool value_changed = ImGui::VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  5528. *v = (int)v_f;
  5529. return value_changed;
  5530. }
  5531. // Add multiple sliders on 1 line for compact edition of multiple components
  5532. bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
  5533. {
  5534. ImGuiWindow* window = GetCurrentWindow();
  5535. if (window->SkipItems)
  5536. return false;
  5537. ImGuiState& g = *GImGui;
  5538. bool value_changed = false;
  5539. ImGui::BeginGroup();
  5540. ImGui::PushID(label);
  5541. PushMultiItemsWidths(components);
  5542. for (int i = 0; i < components; i++)
  5543. {
  5544. ImGui::PushID(i);
  5545. value_changed |= ImGui::SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
  5546. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5547. ImGui::PopID();
  5548. ImGui::PopItemWidth();
  5549. }
  5550. ImGui::PopID();
  5551. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  5552. ImGui::EndGroup();
  5553. return value_changed;
  5554. }
  5555. bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
  5556. {
  5557. return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
  5558. }
  5559. bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
  5560. {
  5561. return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
  5562. }
  5563. bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
  5564. {
  5565. return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
  5566. }
  5567. bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
  5568. {
  5569. ImGuiWindow* window = GetCurrentWindow();
  5570. if (window->SkipItems)
  5571. return false;
  5572. ImGuiState& g = *GImGui;
  5573. bool value_changed = false;
  5574. ImGui::BeginGroup();
  5575. ImGui::PushID(label);
  5576. PushMultiItemsWidths(components);
  5577. for (int i = 0; i < components; i++)
  5578. {
  5579. ImGui::PushID(i);
  5580. value_changed |= ImGui::SliderInt("##v", &v[i], v_min, v_max, display_format);
  5581. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5582. ImGui::PopID();
  5583. ImGui::PopItemWidth();
  5584. }
  5585. ImGui::PopID();
  5586. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  5587. ImGui::EndGroup();
  5588. return value_changed;
  5589. }
  5590. bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
  5591. {
  5592. return SliderIntN(label, v, 2, v_min, v_max, display_format);
  5593. }
  5594. bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
  5595. {
  5596. return SliderIntN(label, v, 3, v_min, v_max, display_format);
  5597. }
  5598. bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
  5599. {
  5600. return SliderIntN(label, v, 4, v_min, v_max, display_format);
  5601. }
  5602. bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power)
  5603. {
  5604. ImGuiState& g = *GImGui;
  5605. const ImGuiStyle& style = g.Style;
  5606. // Draw frame
  5607. const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
  5608. RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
  5609. bool value_changed = false;
  5610. // Process clicking on the drag
  5611. if (g.ActiveId == id)
  5612. {
  5613. if (g.IO.MouseDown[0])
  5614. {
  5615. if (g.ActiveIdIsJustActivated)
  5616. {
  5617. // Lock current value on click
  5618. g.DragCurrentValue = *v;
  5619. g.DragLastMouseDelta = ImVec2(0.f, 0.f);
  5620. }
  5621. const ImVec2 mouse_drag_delta = ImGui::GetMouseDragDelta(0, 1.0f);
  5622. if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f)
  5623. {
  5624. float speed = v_speed;
  5625. if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
  5626. speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
  5627. if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
  5628. speed = speed * g.DragSpeedScaleFast;
  5629. if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
  5630. speed = speed * g.DragSpeedScaleSlow;
  5631. float v_cur = g.DragCurrentValue;
  5632. float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed;
  5633. if (fabsf(power - 1.0f) > 0.001f)
  5634. {
  5635. // Logarithmic curve on both side of 0.0
  5636. float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
  5637. float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
  5638. float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign);
  5639. float v1_abs = v1 >= 0.0f ? v1 : -v1;
  5640. float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
  5641. v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
  5642. }
  5643. else
  5644. {
  5645. v_cur += delta;
  5646. }
  5647. g.DragLastMouseDelta.x = mouse_drag_delta.x;
  5648. // Clamp
  5649. if (v_min < v_max)
  5650. v_cur = ImClamp(v_cur, v_min, v_max);
  5651. g.DragCurrentValue = v_cur;
  5652. // Round to user desired precision, then apply
  5653. v_cur = RoundScalar(v_cur, decimal_precision);
  5654. if (*v != v_cur)
  5655. {
  5656. *v = v_cur;
  5657. value_changed = true;
  5658. }
  5659. }
  5660. }
  5661. else
  5662. {
  5663. SetActiveID(0);
  5664. }
  5665. }
  5666. return value_changed;
  5667. }
  5668. bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
  5669. {
  5670. ImGuiWindow* window = GetCurrentWindow();
  5671. if (window->SkipItems)
  5672. return false;
  5673. ImGuiState& g = *GImGui;
  5674. const ImGuiStyle& style = g.Style;
  5675. const ImGuiID id = window->GetID(label);
  5676. const float w = CalcItemWidth();
  5677. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5678. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  5679. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  5680. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  5681. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  5682. if (!ItemAdd(total_bb, &id))
  5683. {
  5684. ItemSize(total_bb, style.FramePadding.y);
  5685. return false;
  5686. }
  5687. const bool hovered = IsHovered(frame_bb, id);
  5688. if (hovered)
  5689. SetHoveredID(id);
  5690. if (!display_format)
  5691. display_format = "%.3f";
  5692. int decimal_precision = ParseFormatPrecision(display_format, 3);
  5693. // Tabbing or CTRL-clicking on Drag turns it into an input box
  5694. bool start_text_input = false;
  5695. const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
  5696. if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0])))
  5697. {
  5698. SetActiveID(id, window);
  5699. FocusWindow(window);
  5700. if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
  5701. {
  5702. start_text_input = true;
  5703. g.ScalarAsInputTextId = 0;
  5704. }
  5705. }
  5706. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  5707. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  5708. // Actual drag behavior
  5709. ItemSize(total_bb, style.FramePadding.y);
  5710. const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
  5711. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  5712. char value_buf[64];
  5713. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  5714. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter);
  5715. if (label_size.x > 0.0f)
  5716. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  5717. return value_changed;
  5718. }
  5719. bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power)
  5720. {
  5721. ImGuiWindow* window = GetCurrentWindow();
  5722. if (window->SkipItems)
  5723. return false;
  5724. ImGuiState& g = *GImGui;
  5725. bool value_changed = false;
  5726. ImGui::BeginGroup();
  5727. ImGui::PushID(label);
  5728. PushMultiItemsWidths(components);
  5729. for (int i = 0; i < components; i++)
  5730. {
  5731. ImGui::PushID(i);
  5732. value_changed |= ImGui::DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
  5733. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5734. ImGui::PopID();
  5735. ImGui::PopItemWidth();
  5736. }
  5737. ImGui::PopID();
  5738. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  5739. ImGui::EndGroup();
  5740. return value_changed;
  5741. }
  5742. bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
  5743. {
  5744. return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
  5745. }
  5746. bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
  5747. {
  5748. return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
  5749. }
  5750. bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
  5751. {
  5752. return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power);
  5753. }
  5754. bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power)
  5755. {
  5756. ImGuiWindow* window = GetCurrentWindow();
  5757. if (window->SkipItems)
  5758. return false;
  5759. ImGuiState& g = *GImGui;
  5760. ImGui::PushID(label);
  5761. ImGui::BeginGroup();
  5762. PushMultiItemsWidths(2);
  5763. bool value_changed = ImGui::DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power);
  5764. ImGui::PopItemWidth();
  5765. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5766. value_changed |= ImGui::DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power);
  5767. ImGui::PopItemWidth();
  5768. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5769. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  5770. ImGui::EndGroup();
  5771. ImGui::PopID();
  5772. return value_changed;
  5773. }
  5774. // NB: v_speed is float to allow adjusting the drag speed with more precision
  5775. bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
  5776. {
  5777. if (!display_format)
  5778. display_format = "%.0f";
  5779. float v_f = (float)*v;
  5780. bool value_changed = ImGui::DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
  5781. *v = (int)v_f;
  5782. return value_changed;
  5783. }
  5784. bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
  5785. {
  5786. ImGuiWindow* window = GetCurrentWindow();
  5787. if (window->SkipItems)
  5788. return false;
  5789. ImGuiState& g = *GImGui;
  5790. bool value_changed = false;
  5791. ImGui::BeginGroup();
  5792. ImGui::PushID(label);
  5793. PushMultiItemsWidths(components);
  5794. for (int i = 0; i < components; i++)
  5795. {
  5796. ImGui::PushID(i);
  5797. value_changed |= ImGui::DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
  5798. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5799. ImGui::PopID();
  5800. ImGui::PopItemWidth();
  5801. }
  5802. ImGui::PopID();
  5803. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  5804. ImGui::EndGroup();
  5805. return value_changed;
  5806. }
  5807. bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
  5808. {
  5809. return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
  5810. }
  5811. bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
  5812. {
  5813. return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
  5814. }
  5815. bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
  5816. {
  5817. return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format);
  5818. }
  5819. bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max)
  5820. {
  5821. ImGuiWindow* window = GetCurrentWindow();
  5822. if (window->SkipItems)
  5823. return false;
  5824. ImGuiState& g = *GImGui;
  5825. ImGui::PushID(label);
  5826. ImGui::BeginGroup();
  5827. PushMultiItemsWidths(2);
  5828. bool value_changed = ImGui::DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? IM_INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format);
  5829. ImGui::PopItemWidth();
  5830. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5831. value_changed |= ImGui::DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? IM_INT_MAX : v_max, display_format_max ? display_format_max : display_format);
  5832. ImGui::PopItemWidth();
  5833. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  5834. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  5835. ImGui::EndGroup();
  5836. ImGui::PopID();
  5837. return value_changed;
  5838. }
  5839. void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  5840. {
  5841. ImGuiWindow* window = GetCurrentWindow();
  5842. if (window->SkipItems)
  5843. return;
  5844. ImGuiState& g = *GImGui;
  5845. const ImGuiStyle& style = g.Style;
  5846. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5847. if (graph_size.x == 0.0f)
  5848. graph_size.x = CalcItemWidth();
  5849. if (graph_size.y == 0.0f)
  5850. graph_size.y = label_size.y + (style.FramePadding.y * 2);
  5851. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y));
  5852. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  5853. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
  5854. ItemSize(total_bb, style.FramePadding.y);
  5855. if (!ItemAdd(total_bb, NULL))
  5856. return;
  5857. // Determine scale from values if not specified
  5858. if (scale_min == FLT_MAX || scale_max == FLT_MAX)
  5859. {
  5860. float v_min = FLT_MAX;
  5861. float v_max = -FLT_MAX;
  5862. for (int i = 0; i < values_count; i++)
  5863. {
  5864. const float v = values_getter(data, i);
  5865. v_min = ImMin(v_min, v);
  5866. v_max = ImMax(v_max, v);
  5867. }
  5868. if (scale_min == FLT_MAX)
  5869. scale_min = v_min;
  5870. if (scale_max == FLT_MAX)
  5871. scale_max = v_max;
  5872. }
  5873. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  5874. int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  5875. int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  5876. // Tooltip on hover
  5877. int v_hovered = -1;
  5878. if (IsHovered(inner_bb, 0))
  5879. {
  5880. const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
  5881. const int v_idx = (int)(t * item_count);
  5882. IM_ASSERT(v_idx >= 0 && v_idx < values_count);
  5883. const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
  5884. const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
  5885. if (plot_type == ImGuiPlotType_Lines)
  5886. ImGui::SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
  5887. else if (plot_type == ImGuiPlotType_Histogram)
  5888. ImGui::SetTooltip("%d: %8.4g", v_idx, v0);
  5889. v_hovered = v_idx;
  5890. }
  5891. const float t_step = 1.0f / (float)res_w;
  5892. float v0 = values_getter(data, (0 + values_offset) % values_count);
  5893. float t0 = 0.0f;
  5894. ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
  5895. const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
  5896. const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
  5897. for (int n = 0; n < res_w; n++)
  5898. {
  5899. const float t1 = t0 + t_step;
  5900. const int v1_idx = (int)(t0 * item_count + 0.5f);
  5901. IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
  5902. const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
  5903. const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) );
  5904. // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
  5905. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
  5906. ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f));
  5907. if (plot_type == ImGuiPlotType_Lines)
  5908. {
  5909. window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  5910. }
  5911. else if (plot_type == ImGuiPlotType_Histogram)
  5912. {
  5913. if (pos1.x >= pos0.x + 2.0f)
  5914. pos1.x -= 1.0f;
  5915. window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  5916. }
  5917. t0 = t1;
  5918. tp0 = tp1;
  5919. }
  5920. // Text overlay
  5921. if (overlay_text)
  5922. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImGuiAlign_Center);
  5923. if (label_size.x > 0.0f)
  5924. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  5925. }
  5926. struct ImGuiPlotArrayGetterData
  5927. {
  5928. const float* Values;
  5929. int Stride;
  5930. ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
  5931. };
  5932. static float Plot_ArrayGetter(void* data, int idx)
  5933. {
  5934. ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
  5935. const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
  5936. return v;
  5937. }
  5938. void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
  5939. {
  5940. ImGuiPlotArrayGetterData data(values, stride);
  5941. PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  5942. }
  5943. void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  5944. {
  5945. PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  5946. }
  5947. void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
  5948. {
  5949. ImGuiPlotArrayGetterData data(values, stride);
  5950. PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  5951. }
  5952. void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  5953. {
  5954. PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  5955. }
  5956. // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
  5957. void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
  5958. {
  5959. ImGuiWindow* window = GetCurrentWindow();
  5960. if (window->SkipItems)
  5961. return;
  5962. ImGuiState& g = *GImGui;
  5963. const ImGuiStyle& style = g.Style;
  5964. ImVec2 pos = window->DC.CursorPos;
  5965. ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
  5966. ItemSize(bb, style.FramePadding.y);
  5967. if (!ItemAdd(bb, NULL))
  5968. return;
  5969. // Render
  5970. fraction = ImSaturate(fraction);
  5971. RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  5972. bb.Reduce(ImVec2(window->BorderSize, window->BorderSize));
  5973. const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
  5974. RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding);
  5975. // Default displaying the fraction as percentage string, but user can override it
  5976. char overlay_buf[32];
  5977. if (!overlay)
  5978. {
  5979. ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
  5980. overlay = overlay_buf;
  5981. }
  5982. ImVec2 overlay_size = CalcTextSize(overlay, NULL);
  5983. if (overlay_size.x > 0.0f)
  5984. RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImGuiAlign_Left|ImGuiAlign_VCenter, &bb.Min, &bb.Max);
  5985. }
  5986. bool ImGui::Checkbox(const char* label, bool* v)
  5987. {
  5988. ImGuiWindow* window = GetCurrentWindow();
  5989. if (window->SkipItems)
  5990. return false;
  5991. ImGuiState& g = *GImGui;
  5992. const ImGuiStyle& style = g.Style;
  5993. const ImGuiID id = window->GetID(label);
  5994. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5995. const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2));
  5996. ItemSize(check_bb, style.FramePadding.y);
  5997. ImRect total_bb = check_bb;
  5998. if (label_size.x > 0)
  5999. SameLine(0, style.ItemInnerSpacing.x);
  6000. const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size);
  6001. if (label_size.x > 0)
  6002. {
  6003. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  6004. total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
  6005. }
  6006. if (!ItemAdd(total_bb, &id))
  6007. return false;
  6008. bool hovered, held;
  6009. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  6010. if (pressed)
  6011. *v = !(*v);
  6012. RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
  6013. if (*v)
  6014. {
  6015. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  6016. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  6017. window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding);
  6018. }
  6019. if (g.LogEnabled)
  6020. LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]");
  6021. if (label_size.x > 0.0f)
  6022. RenderText(text_bb.GetTL(), label);
  6023. return pressed;
  6024. }
  6025. bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
  6026. {
  6027. bool v = (*flags & flags_value) ? true : false;
  6028. bool pressed = ImGui::Checkbox(label, &v);
  6029. if (v)
  6030. *flags |= flags_value;
  6031. else
  6032. *flags &= ~flags_value;
  6033. return pressed;
  6034. }
  6035. bool ImGui::RadioButton(const char* label, bool active)
  6036. {
  6037. ImGuiWindow* window = GetCurrentWindow();
  6038. if (window->SkipItems)
  6039. return false;
  6040. ImGuiState& g = *GImGui;
  6041. const ImGuiStyle& style = g.Style;
  6042. const ImGuiID id = window->GetID(label);
  6043. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6044. const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1));
  6045. ItemSize(check_bb, style.FramePadding.y);
  6046. ImRect total_bb = check_bb;
  6047. if (label_size.x > 0)
  6048. SameLine(0, style.ItemInnerSpacing.x);
  6049. const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
  6050. if (label_size.x > 0)
  6051. {
  6052. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  6053. total_bb.Add(text_bb);
  6054. }
  6055. if (!ItemAdd(total_bb, &id))
  6056. return false;
  6057. ImVec2 center = check_bb.GetCenter();
  6058. center.x = (float)(int)center.x + 0.5f;
  6059. center.y = (float)(int)center.y + 0.5f;
  6060. const float radius = check_bb.GetHeight() * 0.5f;
  6061. bool hovered, held;
  6062. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  6063. window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
  6064. if (active)
  6065. {
  6066. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  6067. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  6068. window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16);
  6069. }
  6070. if (window->Flags & ImGuiWindowFlags_ShowBorders)
  6071. {
  6072. window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16);
  6073. window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16);
  6074. }
  6075. if (g.LogEnabled)
  6076. LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )");
  6077. if (label_size.x > 0.0f)
  6078. RenderText(text_bb.GetTL(), label);
  6079. return pressed;
  6080. }
  6081. bool ImGui::RadioButton(const char* label, int* v, int v_button)
  6082. {
  6083. const bool pressed = ImGui::RadioButton(label, *v == v_button);
  6084. if (pressed)
  6085. {
  6086. *v = v_button;
  6087. }
  6088. return pressed;
  6089. }
  6090. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
  6091. {
  6092. int line_count = 0;
  6093. const char* s = text_begin;
  6094. while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
  6095. if (c == '\n')
  6096. line_count++;
  6097. s--;
  6098. if (s[0] != '\n' && s[0] != '\r')
  6099. line_count++;
  6100. *out_text_end = s;
  6101. return line_count;
  6102. }
  6103. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
  6104. {
  6105. ImFont* font = GImGui->Font;
  6106. const float line_height = GImGui->FontSize;
  6107. const float scale = line_height / font->FontSize;
  6108. ImVec2 text_size = ImVec2(0,0);
  6109. float line_width = 0.0f;
  6110. const ImWchar* s = text_begin;
  6111. while (s < text_end)
  6112. {
  6113. unsigned int c = (unsigned int)(*s++);
  6114. if (c == '\n')
  6115. {
  6116. text_size.x = ImMax(text_size.x, line_width);
  6117. text_size.y += line_height;
  6118. line_width = 0.0f;
  6119. if (stop_on_new_line)
  6120. break;
  6121. continue;
  6122. }
  6123. if (c == '\r')
  6124. continue;
  6125. const float char_width = font->GetCharAdvance((unsigned short)c) * scale;
  6126. line_width += char_width;
  6127. }
  6128. if (text_size.x < line_width)
  6129. text_size.x = line_width;
  6130. if (out_offset)
  6131. *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
  6132. if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
  6133. text_size.y += line_height;
  6134. if (remaining)
  6135. *remaining = s;
  6136. return text_size;
  6137. }
  6138. // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
  6139. namespace ImGuiStb
  6140. {
  6141. static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
  6142. static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; }
  6143. static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); }
  6144. static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
  6145. static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
  6146. static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
  6147. {
  6148. const ImWchar* text = obj->Text.Data;
  6149. const ImWchar* text_remaining = NULL;
  6150. const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
  6151. r->x0 = 0.0f;
  6152. r->x1 = size.x;
  6153. r->baseline_y_delta = size.y;
  6154. r->ymin = 0.0f;
  6155. r->ymax = size.y;
  6156. r->num_chars = (int)(text_remaining - (text + line_start_idx));
  6157. }
  6158. static bool is_separator(unsigned int c) { return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
  6159. #define STB_TEXTEDIT_IS_SPACE(CH) ( ImCharIsSpace((unsigned int)CH) || is_separator((unsigned int)CH) )
  6160. static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
  6161. {
  6162. ImWchar* dst = obj->Text.Data + pos;
  6163. // We maintain our buffer length in both UTF-8 and wchar formats
  6164. obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
  6165. obj->CurLenW -= n;
  6166. // Offset remaining text
  6167. const ImWchar* src = obj->Text.Data + pos + n;
  6168. while (ImWchar c = *src++)
  6169. *dst++ = c;
  6170. *dst = '\0';
  6171. }
  6172. static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
  6173. {
  6174. const int text_len = obj->CurLenW;
  6175. if (new_text_len + text_len + 1 > obj->Text.Size)
  6176. return false;
  6177. const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
  6178. if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
  6179. return false;
  6180. ImWchar* text = obj->Text.Data;
  6181. if (pos != text_len)
  6182. memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
  6183. memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
  6184. obj->CurLenW += new_text_len;
  6185. obj->CurLenA += new_text_len_utf8;
  6186. obj->Text[obj->CurLenW] = '\0';
  6187. return true;
  6188. }
  6189. // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
  6190. #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
  6191. #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
  6192. #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
  6193. #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
  6194. #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
  6195. #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
  6196. #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
  6197. #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
  6198. #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
  6199. #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
  6200. #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
  6201. #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
  6202. #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
  6203. #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
  6204. #define STB_TEXTEDIT_K_SHIFT 0x20000
  6205. #define STB_TEXTEDIT_IMPLEMENTATION
  6206. #include "stb_textedit.h"
  6207. }
  6208. void ImGuiTextEditState::OnKeyPressed(int key)
  6209. {
  6210. stb_textedit_key(this, &StbState, key);
  6211. CursorFollow = true;
  6212. CursorAnimReset();
  6213. }
  6214. // Public API to manipulate UTF-8 text
  6215. // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
  6216. // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
  6217. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count)
  6218. {
  6219. IM_ASSERT(pos + bytes_count <= BufTextLen);
  6220. char* dst = Buf + pos;
  6221. const char* src = Buf + pos + bytes_count;
  6222. while (char c = *src++)
  6223. *dst++ = c;
  6224. *dst = '\0';
  6225. if (CursorPos + bytes_count >= pos)
  6226. CursorPos -= bytes_count;
  6227. else if (CursorPos >= pos)
  6228. CursorPos = pos;
  6229. SelectionStart = SelectionEnd = CursorPos;
  6230. BufDirty = true;
  6231. BufTextLen -= bytes_count;
  6232. }
  6233. void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
  6234. {
  6235. const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
  6236. if (new_text_len + BufTextLen + 1 >= BufSize)
  6237. return;
  6238. if (BufTextLen != pos)
  6239. memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
  6240. memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
  6241. Buf[BufTextLen + new_text_len] = '\0';
  6242. if (CursorPos >= pos)
  6243. CursorPos += new_text_len;
  6244. SelectionStart = SelectionEnd = CursorPos;
  6245. BufDirty = true;
  6246. BufTextLen += new_text_len;
  6247. }
  6248. // Return false to discard a character.
  6249. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  6250. {
  6251. unsigned int c = *p_char;
  6252. if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
  6253. {
  6254. bool pass = false;
  6255. pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
  6256. pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
  6257. if (!pass)
  6258. return false;
  6259. }
  6260. if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys.
  6261. return false;
  6262. if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank))
  6263. {
  6264. if (flags & ImGuiInputTextFlags_CharsDecimal)
  6265. if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
  6266. return false;
  6267. if (flags & ImGuiInputTextFlags_CharsHexadecimal)
  6268. if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
  6269. return false;
  6270. if (flags & ImGuiInputTextFlags_CharsUppercase)
  6271. if (c >= 'a' && c <= 'z')
  6272. *p_char = (c += (unsigned int)('A'-'a'));
  6273. if (flags & ImGuiInputTextFlags_CharsNoBlank)
  6274. if (ImCharIsSpace(c))
  6275. return false;
  6276. }
  6277. if (flags & ImGuiInputTextFlags_CallbackCharFilter)
  6278. {
  6279. ImGuiTextEditCallbackData callback_data;
  6280. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  6281. callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
  6282. callback_data.EventChar = (ImWchar)c;
  6283. callback_data.Flags = flags;
  6284. callback_data.UserData = user_data;
  6285. if (callback(&callback_data) != 0)
  6286. return false;
  6287. *p_char = callback_data.EventChar;
  6288. if (!callback_data.EventChar)
  6289. return false;
  6290. }
  6291. return true;
  6292. }
  6293. // Edit a string of text
  6294. // NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect.
  6295. // FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188
  6296. bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  6297. {
  6298. ImGuiWindow* window = GetCurrentWindow();
  6299. if (window->SkipItems)
  6300. return false;
  6301. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
  6302. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
  6303. ImGuiState& g = *GImGui;
  6304. const ImGuiIO& io = g.IO;
  6305. const ImGuiStyle& style = g.Style;
  6306. const ImGuiID id = window->GetID(label);
  6307. const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
  6308. const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
  6309. const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
  6310. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6311. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? ImGui::GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
  6312. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  6313. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f));
  6314. ImGuiWindow* draw_window = window;
  6315. if (is_multiline)
  6316. {
  6317. ImGui::BeginGroup();
  6318. if (!ImGui::BeginChildFrame(id, frame_bb.GetSize()))
  6319. {
  6320. ImGui::EndChildFrame();
  6321. ImGui::EndGroup();
  6322. return false;
  6323. }
  6324. draw_window = GetCurrentWindow();
  6325. draw_window->DC.CursorPos += style.FramePadding;
  6326. size.x -= draw_window->ScrollbarSizes.x;
  6327. }
  6328. else
  6329. {
  6330. ItemSize(total_bb, style.FramePadding.y);
  6331. if (!ItemAdd(total_bb, &id))
  6332. return false;
  6333. }
  6334. // Password pushes a temporary font with only a fallback glyph
  6335. if (is_password)
  6336. {
  6337. const ImFont::Glyph* glyph = g.Font->FindGlyph('*');
  6338. ImFont* password_font = &g.InputTextPasswordFont;
  6339. password_font->FontSize = g.Font->FontSize;
  6340. password_font->Scale = g.Font->Scale;
  6341. password_font->DisplayOffset = g.Font->DisplayOffset;
  6342. password_font->Ascent = g.Font->Ascent;
  6343. password_font->Descent = g.Font->Descent;
  6344. password_font->ContainerAtlas = g.Font->ContainerAtlas;
  6345. password_font->FallbackGlyph = glyph;
  6346. password_font->FallbackXAdvance = glyph->XAdvance;
  6347. IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty());
  6348. ImGui::PushFont(password_font);
  6349. }
  6350. // NB: we are only allowed to access 'edit_state' if we are the active widget.
  6351. ImGuiTextEditState& edit_state = g.InputTextState;
  6352. const bool is_ctrl_down = io.KeyCtrl;
  6353. const bool is_shift_down = io.KeyShift;
  6354. const bool is_alt_down = io.KeyAlt;
  6355. const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
  6356. const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
  6357. const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
  6358. const bool hovered = IsHovered(frame_bb, id);
  6359. if (hovered)
  6360. {
  6361. SetHoveredID(id);
  6362. g.MouseCursor = ImGuiMouseCursor_TextInput;
  6363. }
  6364. const bool user_clicked = hovered && io.MouseClicked[0];
  6365. const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetID("#SCROLLY");
  6366. bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
  6367. if (focus_requested || user_clicked || user_scrolled)
  6368. {
  6369. if (g.ActiveId != id)
  6370. {
  6371. // Start edition
  6372. // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
  6373. // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
  6374. const int prev_len_w = edit_state.CurLenW;
  6375. edit_state.Text.resize(buf_size+1); // wchar count <= utf-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
  6376. edit_state.InitialText.resize(buf_size+1); // utf-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
  6377. ImFormatString(edit_state.InitialText.Data, edit_state.InitialText.Size, "%s", buf);
  6378. const char* buf_end = NULL;
  6379. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  6380. edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
  6381. edit_state.CursorAnimReset();
  6382. // Preserve cursor position and undo/redo stack if we come back to same widget
  6383. // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar).
  6384. const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW);
  6385. if (recycle_state)
  6386. {
  6387. // Recycle existing cursor/selection/undo stack but clamp position
  6388. // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
  6389. edit_state.CursorClamp();
  6390. }
  6391. else
  6392. {
  6393. edit_state.Id = id;
  6394. edit_state.ScrollX = 0.0f;
  6395. stb_textedit_initialize_state(&edit_state.StbState, !is_multiline);
  6396. if (!is_multiline && focus_requested_by_code)
  6397. select_all = true;
  6398. }
  6399. if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
  6400. edit_state.StbState.insert_mode = true;
  6401. if (!is_multiline && (focus_requested_by_tab || (user_clicked && is_ctrl_down)))
  6402. select_all = true;
  6403. }
  6404. SetActiveID(id, window);
  6405. FocusWindow(window);
  6406. }
  6407. else if (io.MouseClicked[0])
  6408. {
  6409. // Release focus when we click outside
  6410. if (g.ActiveId == id)
  6411. SetActiveID(0);
  6412. }
  6413. bool value_changed = false;
  6414. bool enter_pressed = false;
  6415. if (g.ActiveId == id)
  6416. {
  6417. if (!is_editable && !g.ActiveIdIsJustActivated)
  6418. {
  6419. // When read-only we always use the live data passed to the function
  6420. edit_state.Text.resize(buf_size+1);
  6421. const char* buf_end = NULL;
  6422. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  6423. edit_state.CurLenA = (int)(buf_end - buf);
  6424. edit_state.CursorClamp();
  6425. }
  6426. edit_state.BufSizeA = buf_size;
  6427. // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
  6428. // Down the line we should have a cleaner library-wide concept of Selected vs Active.
  6429. g.ActiveIdAllowOverlap = !io.MouseDown[0];
  6430. // Edit in progress
  6431. const float mouse_x = (g.IO.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
  6432. const float mouse_y = (is_multiline ? (g.IO.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
  6433. if (select_all || (hovered && io.MouseDoubleClicked[0]))
  6434. {
  6435. edit_state.SelectAll();
  6436. edit_state.SelectedAllMouseLock = true;
  6437. }
  6438. else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
  6439. {
  6440. stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  6441. edit_state.CursorAnimReset();
  6442. }
  6443. else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
  6444. {
  6445. stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  6446. edit_state.CursorAnimReset();
  6447. edit_state.CursorFollow = true;
  6448. }
  6449. if (edit_state.SelectedAllMouseLock && !io.MouseDown[0])
  6450. edit_state.SelectedAllMouseLock = false;
  6451. if (g.IO.InputCharacters[0])
  6452. {
  6453. // Process text input (before we check for Return because using some IME will effectively send a Return?)
  6454. // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters.
  6455. if (!(is_ctrl_down && !is_alt_down) && is_editable)
  6456. {
  6457. for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++)
  6458. if (unsigned int c = (unsigned int)g.IO.InputCharacters[n])
  6459. {
  6460. // Insert character if they pass filtering
  6461. if (!InputTextFilterCharacter(&c, flags, callback, user_data))
  6462. continue;
  6463. edit_state.OnKeyPressed((int)c);
  6464. }
  6465. }
  6466. // Consume characters
  6467. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  6468. }
  6469. // Handle various key-presses
  6470. bool cancel_edit = false;
  6471. const int k_mask = (is_shift_down ? STB_TEXTEDIT_K_SHIFT : 0);
  6472. const bool is_ctrl_only = is_ctrl_down && !is_alt_down && !is_shift_down;
  6473. if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDLEFT | k_mask : STB_TEXTEDIT_K_LEFT | k_mask); }
  6474. else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDRIGHT | k_mask : STB_TEXTEDIT_K_RIGHT | k_mask); }
  6475. else if (is_multiline && IsKeyPressedMap(ImGuiKey_UpArrow)) { if (is_ctrl_down) SetWindowScrollY(draw_window, draw_window->Scroll.y - g.FontSize); else edit_state.OnKeyPressed(STB_TEXTEDIT_K_UP | k_mask); }
  6476. else if (is_multiline && IsKeyPressedMap(ImGuiKey_DownArrow)) { if (is_ctrl_down) SetWindowScrollY(draw_window, draw_window->Scroll.y + g.FontSize); else edit_state.OnKeyPressed(STB_TEXTEDIT_K_DOWN| k_mask); }
  6477. else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
  6478. else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
  6479. else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
  6480. else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); }
  6481. else if (IsKeyPressedMap(ImGuiKey_Enter))
  6482. {
  6483. bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
  6484. if (!is_multiline || (ctrl_enter_for_new_line && !is_ctrl_down) || (!ctrl_enter_for_new_line && is_ctrl_down))
  6485. {
  6486. SetActiveID(0);
  6487. enter_pressed = true;
  6488. }
  6489. else if (is_editable)
  6490. {
  6491. unsigned int c = '\n'; // Insert new line
  6492. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  6493. edit_state.OnKeyPressed((int)c);
  6494. }
  6495. }
  6496. else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !is_ctrl_down && !is_shift_down && !is_alt_down && is_editable)
  6497. {
  6498. unsigned int c = '\t'; // Insert TAB
  6499. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  6500. edit_state.OnKeyPressed((int)c);
  6501. }
  6502. else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveID(0); cancel_edit = true; }
  6503. else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
  6504. else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
  6505. else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
  6506. else if (is_ctrl_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection()))
  6507. {
  6508. // Cut, Copy
  6509. const bool cut = IsKeyPressedMap(ImGuiKey_X);
  6510. if (cut && !edit_state.HasSelection())
  6511. edit_state.SelectAll();
  6512. if (g.IO.SetClipboardTextFn)
  6513. {
  6514. const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
  6515. const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW;
  6516. edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1);
  6517. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie);
  6518. g.IO.SetClipboardTextFn(edit_state.TempTextBuffer.Data);
  6519. }
  6520. if (cut)
  6521. {
  6522. edit_state.CursorFollow = true;
  6523. stb_textedit_cut(&edit_state, &edit_state.StbState);
  6524. }
  6525. }
  6526. else if (is_ctrl_only && IsKeyPressedMap(ImGuiKey_V) && is_editable)
  6527. {
  6528. // Paste
  6529. if (g.IO.GetClipboardTextFn)
  6530. {
  6531. if (const char* clipboard = g.IO.GetClipboardTextFn())
  6532. {
  6533. // Remove new-line from pasted buffer
  6534. const int clipboard_len = (int)strlen(clipboard);
  6535. ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar));
  6536. int clipboard_filtered_len = 0;
  6537. for (const char* s = clipboard; *s; )
  6538. {
  6539. unsigned int c;
  6540. s += ImTextCharFromUtf8(&c, s, NULL);
  6541. if (c == 0)
  6542. break;
  6543. if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data))
  6544. continue;
  6545. clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
  6546. }
  6547. clipboard_filtered[clipboard_filtered_len] = 0;
  6548. if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
  6549. {
  6550. stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len);
  6551. edit_state.CursorFollow = true;
  6552. }
  6553. ImGui::MemFree(clipboard_filtered);
  6554. }
  6555. }
  6556. }
  6557. if (cancel_edit)
  6558. {
  6559. // Restore initial value
  6560. if (is_editable)
  6561. {
  6562. ImFormatString(buf, buf_size, "%s", edit_state.InitialText.Data);
  6563. value_changed = true;
  6564. }
  6565. }
  6566. else
  6567. {
  6568. // Apply new value immediately - copy modified buffer back
  6569. // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
  6570. // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
  6571. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
  6572. if (is_editable)
  6573. {
  6574. edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4);
  6575. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL);
  6576. }
  6577. // User callback
  6578. if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
  6579. {
  6580. IM_ASSERT(callback != NULL);
  6581. // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
  6582. ImGuiInputTextFlags event_flag = 0;
  6583. ImGuiKey event_key = ImGuiKey_COUNT;
  6584. if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
  6585. {
  6586. event_flag = ImGuiInputTextFlags_CallbackCompletion;
  6587. event_key = ImGuiKey_Tab;
  6588. }
  6589. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
  6590. {
  6591. event_flag = ImGuiInputTextFlags_CallbackHistory;
  6592. event_key = ImGuiKey_UpArrow;
  6593. }
  6594. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
  6595. {
  6596. event_flag = ImGuiInputTextFlags_CallbackHistory;
  6597. event_key = ImGuiKey_DownArrow;
  6598. }
  6599. if (event_key != ImGuiKey_COUNT || (flags & ImGuiInputTextFlags_CallbackAlways) != 0)
  6600. {
  6601. ImGuiTextEditCallbackData callback_data;
  6602. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  6603. callback_data.EventFlag = event_flag;
  6604. callback_data.Flags = flags;
  6605. callback_data.UserData = user_data;
  6606. callback_data.ReadOnly = !is_editable;
  6607. callback_data.EventKey = event_key;
  6608. callback_data.Buf = edit_state.TempTextBuffer.Data;
  6609. callback_data.BufTextLen = edit_state.CurLenA;
  6610. callback_data.BufSize = edit_state.BufSizeA;
  6611. callback_data.BufDirty = false;
  6612. // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
  6613. ImWchar* text = edit_state.Text.Data;
  6614. const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor);
  6615. const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start);
  6616. const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end);
  6617. // Call user code
  6618. callback(&callback_data);
  6619. // Read back what user may have modified
  6620. IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields
  6621. IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
  6622. IM_ASSERT(callback_data.Flags == flags);
  6623. if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos);
  6624. if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart);
  6625. if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd);
  6626. if (callback_data.BufDirty)
  6627. {
  6628. IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
  6629. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL);
  6630. edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
  6631. edit_state.CursorAnimReset();
  6632. }
  6633. }
  6634. }
  6635. // Copy back to user buffer
  6636. if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
  6637. {
  6638. ImFormatString(buf, buf_size, "%s", edit_state.TempTextBuffer.Data);
  6639. value_changed = true;
  6640. }
  6641. }
  6642. }
  6643. if (!is_multiline)
  6644. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  6645. // Render
  6646. const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size
  6647. ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
  6648. ImVec2 text_size(0.f, 0.f);
  6649. if (g.ActiveId == id || (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetID("#SCROLLY")))
  6650. {
  6651. edit_state.CursorAnim += g.IO.DeltaTime;
  6652. // We need to:
  6653. // - Display the text (this can be more easily clipped)
  6654. // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
  6655. // - Measure text height (for scrollbar)
  6656. // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
  6657. const ImWchar* text_begin = edit_state.Text.Data;
  6658. ImVec2 cursor_offset, select_start_offset;
  6659. {
  6660. // Count lines + find lines numbers straddling 'cursor' and 'select_start' position.
  6661. const ImWchar* searches_input_ptr[2];
  6662. searches_input_ptr[0] = text_begin + edit_state.StbState.cursor;
  6663. searches_input_ptr[1] = NULL;
  6664. int searches_remaining = 1;
  6665. int searches_result_line_number[2] = { -1, -999 };
  6666. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  6667. {
  6668. searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  6669. searches_result_line_number[1] = -1;
  6670. searches_remaining++;
  6671. }
  6672. // Iterate all lines to find our line numbers
  6673. // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
  6674. searches_remaining += is_multiline ? 1 : 0;
  6675. int line_count = 0;
  6676. for (const ImWchar* s = text_begin; *s != 0; s++)
  6677. if (*s == '\n')
  6678. {
  6679. line_count++;
  6680. if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; }
  6681. if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; }
  6682. }
  6683. line_count++;
  6684. if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count;
  6685. if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count;
  6686. // Calculate 2d position by finding the beginning of the line and measuring distance
  6687. cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
  6688. cursor_offset.y = searches_result_line_number[0] * g.FontSize;
  6689. if (searches_result_line_number[1] >= 0)
  6690. {
  6691. select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
  6692. select_start_offset.y = searches_result_line_number[1] * g.FontSize;
  6693. }
  6694. // Calculate text height
  6695. if (is_multiline)
  6696. text_size = ImVec2(size.x, line_count * g.FontSize);
  6697. }
  6698. // Scroll
  6699. if (edit_state.CursorFollow)
  6700. {
  6701. // Horizontal scroll in chunks of quarter width
  6702. if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
  6703. {
  6704. const float scroll_increment_x = size.x * 0.25f;
  6705. if (cursor_offset.x < edit_state.ScrollX)
  6706. edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
  6707. else if (cursor_offset.x - size.x >= edit_state.ScrollX)
  6708. edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
  6709. }
  6710. else
  6711. {
  6712. edit_state.ScrollX = 0.0f;
  6713. }
  6714. // Vertical scroll
  6715. if (is_multiline)
  6716. {
  6717. float scroll_y = draw_window->Scroll.y;
  6718. if (cursor_offset.y - g.FontSize < scroll_y)
  6719. scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
  6720. else if (cursor_offset.y - size.y >= scroll_y)
  6721. scroll_y = cursor_offset.y - size.y;
  6722. draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag
  6723. draw_window->Scroll.y = scroll_y;
  6724. render_pos.y = draw_window->DC.CursorPos.y;
  6725. }
  6726. }
  6727. edit_state.CursorFollow = false;
  6728. const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f);
  6729. // Draw selection
  6730. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  6731. {
  6732. const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  6733. const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end);
  6734. float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
  6735. float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
  6736. ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg);
  6737. ImVec2 rect_pos = render_pos + select_start_offset - render_scroll;
  6738. for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
  6739. {
  6740. if (rect_pos.y > clip_rect.w + g.FontSize)
  6741. break;
  6742. if (rect_pos.y < clip_rect.y)
  6743. {
  6744. while (p < text_selected_end)
  6745. if (*p++ == '\n')
  6746. break;
  6747. }
  6748. else
  6749. {
  6750. ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
  6751. if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines
  6752. ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
  6753. rect.Clip(clip_rect);
  6754. if (rect.Overlaps(clip_rect))
  6755. draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
  6756. }
  6757. rect_pos.x = render_pos.x - render_scroll.x;
  6758. rect_pos.y += g.FontSize;
  6759. }
  6760. }
  6761. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf, buf+edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
  6762. // Draw blinking cursor
  6763. ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll;
  6764. bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
  6765. if (cursor_is_visible)
  6766. draw_window->DrawList->AddLine(cursor_screen_pos + ImVec2(0.0f,-g.FontSize+0.5f), cursor_screen_pos + ImVec2(0.0f,-1.5f), GetColorU32(ImGuiCol_Text));
  6767. // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
  6768. if (is_editable)
  6769. g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize);
  6770. }
  6771. else
  6772. {
  6773. // Render text only
  6774. const char* buf_end = NULL;
  6775. if (is_multiline)
  6776. text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf, &buf_end) * g.FontSize); // We don't need width
  6777. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf, buf_end, 0.0f, is_multiline ? NULL : &clip_rect);
  6778. }
  6779. if (is_multiline)
  6780. {
  6781. ImGui::Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
  6782. ImGui::EndChildFrame();
  6783. ImGui::EndGroup();
  6784. }
  6785. if (is_password)
  6786. ImGui::PopFont();
  6787. // Log as text
  6788. if (g.LogEnabled && !is_password)
  6789. LogRenderedText(render_pos, buf, NULL);
  6790. if (label_size.x > 0)
  6791. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  6792. if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
  6793. return enter_pressed;
  6794. else
  6795. return value_changed;
  6796. }
  6797. bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  6798. {
  6799. IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
  6800. bool ret = InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
  6801. return ret;
  6802. }
  6803. bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  6804. {
  6805. bool ret = InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
  6806. return ret;
  6807. }
  6808. // NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
  6809. bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags)
  6810. {
  6811. ImGuiWindow* window = GetCurrentWindow();
  6812. if (window->SkipItems)
  6813. return false;
  6814. ImGuiState& g = *GImGui;
  6815. const ImGuiStyle& style = g.Style;
  6816. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6817. ImGui::BeginGroup();
  6818. ImGui::PushID(label);
  6819. const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f;
  6820. if (step_ptr)
  6821. ImGui::PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
  6822. char buf[64];
  6823. DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
  6824. bool value_changed = false;
  6825. if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
  6826. extra_flags |= ImGuiInputTextFlags_CharsDecimal;
  6827. extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
  6828. if (ImGui::InputText("", buf, IM_ARRAYSIZE(buf), extra_flags))
  6829. {
  6830. DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
  6831. value_changed = true;
  6832. }
  6833. // Step buttons
  6834. if (step_ptr)
  6835. {
  6836. ImGui::PopItemWidth();
  6837. ImGui::SameLine(0, style.ItemInnerSpacing.x);
  6838. if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  6839. {
  6840. DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  6841. value_changed = true;
  6842. }
  6843. ImGui::SameLine(0, style.ItemInnerSpacing.x);
  6844. if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  6845. {
  6846. DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  6847. value_changed = true;
  6848. }
  6849. }
  6850. ImGui::PopID();
  6851. if (label_size.x > 0)
  6852. {
  6853. ImGui::SameLine(0, style.ItemInnerSpacing.x);
  6854. RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
  6855. ItemSize(label_size, style.FramePadding.y);
  6856. }
  6857. ImGui::EndGroup();
  6858. return value_changed;
  6859. }
  6860. bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
  6861. {
  6862. char display_format[16];
  6863. if (decimal_precision < 0)
  6864. strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
  6865. else
  6866. ImFormatString(display_format, 16, "%%.%df", decimal_precision);
  6867. return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
  6868. }
  6869. bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags)
  6870. {
  6871. // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
  6872. const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
  6873. return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags);
  6874. }
  6875. bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
  6876. {
  6877. ImGuiWindow* window = GetCurrentWindow();
  6878. if (window->SkipItems)
  6879. return false;
  6880. ImGuiState& g = *GImGui;
  6881. bool value_changed = false;
  6882. ImGui::BeginGroup();
  6883. ImGui::PushID(label);
  6884. PushMultiItemsWidths(components);
  6885. for (int i = 0; i < components; i++)
  6886. {
  6887. ImGui::PushID(i);
  6888. value_changed |= ImGui::InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
  6889. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  6890. ImGui::PopID();
  6891. ImGui::PopItemWidth();
  6892. }
  6893. ImGui::PopID();
  6894. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  6895. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  6896. ImGui::EndGroup();
  6897. return value_changed;
  6898. }
  6899. bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
  6900. {
  6901. return InputFloatN(label, v, 2, decimal_precision, extra_flags);
  6902. }
  6903. bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
  6904. {
  6905. return InputFloatN(label, v, 3, decimal_precision, extra_flags);
  6906. }
  6907. bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
  6908. {
  6909. return InputFloatN(label, v, 4, decimal_precision, extra_flags);
  6910. }
  6911. bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
  6912. {
  6913. ImGuiWindow* window = GetCurrentWindow();
  6914. if (window->SkipItems)
  6915. return false;
  6916. ImGuiState& g = *GImGui;
  6917. bool value_changed = false;
  6918. ImGui::BeginGroup();
  6919. ImGui::PushID(label);
  6920. PushMultiItemsWidths(components);
  6921. for (int i = 0; i < components; i++)
  6922. {
  6923. ImGui::PushID(i);
  6924. value_changed |= ImGui::InputInt("##v", &v[i], 0, 0, extra_flags);
  6925. ImGui::SameLine(0, g.Style.ItemInnerSpacing.x);
  6926. ImGui::PopID();
  6927. ImGui::PopItemWidth();
  6928. }
  6929. ImGui::PopID();
  6930. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  6931. ImGui::TextUnformatted(label, FindTextDisplayEnd(label));
  6932. ImGui::EndGroup();
  6933. return value_changed;
  6934. }
  6935. bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
  6936. {
  6937. return InputIntN(label, v, 2, extra_flags);
  6938. }
  6939. bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
  6940. {
  6941. return InputIntN(label, v, 3, extra_flags);
  6942. }
  6943. bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
  6944. {
  6945. return InputIntN(label, v, 4, extra_flags);
  6946. }
  6947. static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
  6948. {
  6949. const char** items = (const char**)data;
  6950. if (out_text)
  6951. *out_text = items[idx];
  6952. return true;
  6953. }
  6954. static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
  6955. {
  6956. // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
  6957. const char* items_separated_by_zeros = (const char*)data;
  6958. int items_count = 0;
  6959. const char* p = items_separated_by_zeros;
  6960. while (*p)
  6961. {
  6962. if (idx == items_count)
  6963. break;
  6964. p += strlen(p) + 1;
  6965. items_count++;
  6966. }
  6967. if (!*p)
  6968. return false;
  6969. if (out_text)
  6970. *out_text = p;
  6971. return true;
  6972. }
  6973. // Combo box helper allowing to pass an array of strings.
  6974. bool ImGui::Combo(const char* label, int* current_item, const char** items, int items_count, int height_in_items)
  6975. {
  6976. const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
  6977. return value_changed;
  6978. }
  6979. // Combo box helper allowing to pass all items in a single string.
  6980. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
  6981. {
  6982. int items_count = 0;
  6983. const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
  6984. while (*p)
  6985. {
  6986. p += strlen(p) + 1;
  6987. items_count++;
  6988. }
  6989. bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
  6990. return value_changed;
  6991. }
  6992. // Combo box function.
  6993. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
  6994. {
  6995. ImGuiWindow* window = GetCurrentWindow();
  6996. if (window->SkipItems)
  6997. return false;
  6998. ImGuiState& g = *GImGui;
  6999. const ImGuiStyle& style = g.Style;
  7000. const ImGuiID id = window->GetID(label);
  7001. const float w = CalcItemWidth();
  7002. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7003. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  7004. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  7005. ItemSize(total_bb, style.FramePadding.y);
  7006. if (!ItemAdd(total_bb, &id))
  7007. return false;
  7008. const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f);
  7009. const bool hovered = IsHovered(frame_bb, id);
  7010. const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
  7011. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7012. RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
  7013. RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true);
  7014. if (*current_item >= 0 && *current_item < items_count)
  7015. {
  7016. const char* item_text;
  7017. if (items_getter(data, *current_item, &item_text))
  7018. RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL);
  7019. }
  7020. if (label_size.x > 0)
  7021. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  7022. bool menu_toggled = false;
  7023. if (hovered)
  7024. {
  7025. SetHoveredID(id);
  7026. if (g.IO.MouseClicked[0])
  7027. {
  7028. SetActiveID(0);
  7029. if (IsPopupOpen(id))
  7030. {
  7031. ClosePopup(id);
  7032. }
  7033. else
  7034. {
  7035. FocusWindow(window);
  7036. ImGui::OpenPopup(label);
  7037. menu_toggled = true;
  7038. }
  7039. }
  7040. }
  7041. bool value_changed = false;
  7042. if (IsPopupOpen(id))
  7043. {
  7044. // Size default to hold ~7 items
  7045. if (height_in_items < 0)
  7046. height_in_items = 7;
  7047. float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3);
  7048. ImRect popup_rect(ImVec2(frame_bb.Min.x, frame_bb.Max.y), ImVec2(frame_bb.Max.x, frame_bb.Max.y + popup_height));
  7049. popup_rect.Max.y = ImMin(popup_rect.Max.y, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y); // Adhoc height limit for Combo. Ideally should be handled in Begin() along with other popups size, we want to have the possibility of moving the popup above as well.
  7050. ImGui::SetNextWindowPos(popup_rect.Min);
  7051. ImGui::SetNextWindowSize(popup_rect.GetSize());
  7052. ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  7053. const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0);
  7054. if (BeginPopupEx(label, flags))
  7055. {
  7056. // Display items
  7057. ImGui::Spacing();
  7058. for (int i = 0; i < items_count; i++)
  7059. {
  7060. ImGui::PushID((void*)(intptr_t)i);
  7061. const bool item_selected = (i == *current_item);
  7062. const char* item_text;
  7063. if (!items_getter(data, i, &item_text))
  7064. item_text = "*Unknown item*";
  7065. if (ImGui::Selectable(item_text, item_selected))
  7066. {
  7067. SetActiveID(0);
  7068. value_changed = true;
  7069. *current_item = i;
  7070. }
  7071. if (item_selected && menu_toggled)
  7072. ImGui::SetScrollHere();
  7073. ImGui::PopID();
  7074. }
  7075. ImGui::EndPopup();
  7076. }
  7077. ImGui::PopStyleVar();
  7078. }
  7079. return value_changed;
  7080. }
  7081. // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image.
  7082. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID.
  7083. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  7084. {
  7085. ImGuiWindow* window = GetCurrentWindow();
  7086. if (window->SkipItems)
  7087. return false;
  7088. ImGuiState& g = *GImGui;
  7089. const ImGuiStyle& style = g.Style;
  7090. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  7091. PopClipRect();
  7092. ImGuiID id = window->GetID(label);
  7093. ImVec2 label_size = CalcTextSize(label, NULL, true);
  7094. ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
  7095. ImVec2 pos = window->DC.CursorPos;
  7096. pos.y += window->DC.CurrentLineTextBaseOffset;
  7097. ImRect bb(pos, pos + size);
  7098. ItemSize(bb);
  7099. // Fill horizontal space.
  7100. ImVec2 window_padding = window->WindowPadding;
  7101. float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? ImGui::GetWindowContentRegionMax().x : ImGui::GetContentRegionMax().x;
  7102. float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x);
  7103. ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y);
  7104. ImRect bb_with_spacing(pos, pos + size_draw);
  7105. if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
  7106. bb_with_spacing.Max.x += window_padding.x;
  7107. // Selectables are tightly packed together, we extend the box to cover spacing between selectable.
  7108. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
  7109. float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
  7110. float spacing_R = style.ItemSpacing.x - spacing_L;
  7111. float spacing_D = style.ItemSpacing.y - spacing_U;
  7112. bb_with_spacing.Min.x -= spacing_L;
  7113. bb_with_spacing.Min.y -= spacing_U;
  7114. bb_with_spacing.Max.x += spacing_R;
  7115. bb_with_spacing.Max.y += spacing_D;
  7116. if (!ItemAdd(bb_with_spacing, &id))
  7117. {
  7118. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  7119. PushColumnClipRect();
  7120. return false;
  7121. }
  7122. ImGuiButtonFlags button_flags = 0;
  7123. if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick;
  7124. if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease;
  7125. if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
  7126. bool hovered, held;
  7127. bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
  7128. if (flags & ImGuiSelectableFlags_Disabled)
  7129. selected = false;
  7130. // Render
  7131. if (hovered || selected)
  7132. {
  7133. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  7134. RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
  7135. }
  7136. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  7137. {
  7138. PushColumnClipRect();
  7139. bb_with_spacing.Max.x -= (ImGui::GetContentRegionMax().x - max_x);
  7140. }
  7141. if (flags & ImGuiSelectableFlags_Disabled) ImGui::PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  7142. RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size);
  7143. if (flags & ImGuiSelectableFlags_Disabled) ImGui::PopStyleColor();
  7144. // Automatically close popups
  7145. if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  7146. ImGui::CloseCurrentPopup();
  7147. return pressed;
  7148. }
  7149. bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  7150. {
  7151. if (ImGui::Selectable(label, *p_selected, flags, size_arg))
  7152. {
  7153. *p_selected = !*p_selected;
  7154. return true;
  7155. }
  7156. return false;
  7157. }
  7158. // Helper to calculate the size of a listbox and display a label on the right.
  7159. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty"
  7160. bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
  7161. {
  7162. ImGuiWindow* window = GetCurrentWindow();
  7163. if (window->SkipItems)
  7164. return false;
  7165. const ImGuiStyle& style = ImGui::GetStyle();
  7166. const ImGuiID id = ImGui::GetID(label);
  7167. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7168. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  7169. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), ImGui::GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
  7170. ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
  7171. ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
  7172. ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  7173. window->DC.LastItemRect = bb;
  7174. ImGui::BeginGroup();
  7175. if (label_size.x > 0)
  7176. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  7177. ImGui::BeginChildFrame(id, frame_bb.GetSize());
  7178. return true;
  7179. }
  7180. bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
  7181. {
  7182. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  7183. // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size.
  7184. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
  7185. if (height_in_items < 0)
  7186. height_in_items = ImMin(items_count, 7);
  7187. float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f);
  7188. // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild().
  7189. ImVec2 size;
  7190. size.x = 0.0f;
  7191. size.y = ImGui::GetTextLineHeightWithSpacing() * height_in_items_f + ImGui::GetStyle().ItemSpacing.y;
  7192. return ImGui::ListBoxHeader(label, size);
  7193. }
  7194. void ImGui::ListBoxFooter()
  7195. {
  7196. ImGuiWindow* parent_window = GetParentWindow();
  7197. const ImRect bb = parent_window->DC.LastItemRect;
  7198. const ImGuiStyle& style = ImGui::GetStyle();
  7199. ImGui::EndChildFrame();
  7200. // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
  7201. // We call SameLine() to restore DC.CurrentLine* data
  7202. ImGui::SameLine();
  7203. parent_window->DC.CursorPos = bb.Min;
  7204. ItemSize(bb, style.FramePadding.y);
  7205. ImGui::EndGroup();
  7206. }
  7207. bool ImGui::ListBox(const char* label, int* current_item, const char** items, int items_count, int height_items)
  7208. {
  7209. const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
  7210. return value_changed;
  7211. }
  7212. bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
  7213. {
  7214. if (!ImGui::ListBoxHeader(label, items_count, height_in_items))
  7215. return false;
  7216. // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
  7217. bool value_changed = false;
  7218. ImGuiListClipper clipper(items_count, ImGui::GetTextLineHeightWithSpacing());
  7219. for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
  7220. {
  7221. const bool item_selected = (i == *current_item);
  7222. const char* item_text;
  7223. if (!items_getter(data, i, &item_text))
  7224. item_text = "*Unknown item*";
  7225. ImGui::PushID(i);
  7226. if (ImGui::Selectable(item_text, item_selected))
  7227. {
  7228. *current_item = i;
  7229. value_changed = true;
  7230. }
  7231. ImGui::PopID();
  7232. }
  7233. clipper.End();
  7234. ImGui::ListBoxFooter();
  7235. return value_changed;
  7236. }
  7237. bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
  7238. {
  7239. ImGuiWindow* window = GetCurrentWindow();
  7240. if (window->SkipItems)
  7241. return false;
  7242. ImGuiState& g = *GImGui;
  7243. ImVec2 pos = window->DC.CursorPos;
  7244. ImVec2 label_size = CalcTextSize(label, NULL, true);
  7245. ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
  7246. float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
  7247. float extra_w = ImMax(0.0f, ImGui::GetContentRegionAvail().x - w);
  7248. bool pressed = ImGui::Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  7249. if (shortcut_size.x > 0.0f)
  7250. {
  7251. ImGui::PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  7252. RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
  7253. ImGui::PopStyleColor();
  7254. }
  7255. if (selected)
  7256. RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(ImGuiCol_Text));
  7257. return pressed;
  7258. }
  7259. bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
  7260. {
  7261. if (ImGui::MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
  7262. {
  7263. if (p_selected)
  7264. *p_selected = !*p_selected;
  7265. return true;
  7266. }
  7267. return false;
  7268. }
  7269. bool ImGui::BeginMainMenuBar()
  7270. {
  7271. ImGuiState& g = *GImGui;
  7272. ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f));
  7273. ImGui::SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
  7274. ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  7275. ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
  7276. if (!ImGui::Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar)
  7277. || !ImGui::BeginMenuBar())
  7278. {
  7279. ImGui::End();
  7280. ImGui::PopStyleVar(2);
  7281. return false;
  7282. }
  7283. g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
  7284. return true;
  7285. }
  7286. void ImGui::EndMainMenuBar()
  7287. {
  7288. ImGui::EndMenuBar();
  7289. ImGui::End();
  7290. ImGui::PopStyleVar(2);
  7291. }
  7292. bool ImGui::BeginMenuBar()
  7293. {
  7294. ImGuiWindow* window = GetCurrentWindow();
  7295. if (window->SkipItems)
  7296. return false;
  7297. if (!(window->Flags & ImGuiWindowFlags_MenuBar))
  7298. return false;
  7299. IM_ASSERT(!window->DC.MenuBarAppending);
  7300. ImGui::BeginGroup(); // Save position
  7301. ImGui::PushID("##menubar");
  7302. ImRect rect = window->MenuBarRect();
  7303. PushClipRect(ImVec2(rect.Min.x+0.5f, rect.Min.y-0.5f+window->BorderSize), ImVec2(rect.Max.x+0.5f, rect.Max.y-0.5f), false);
  7304. window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y);
  7305. window->DC.LayoutType = ImGuiLayoutType_Horizontal;
  7306. window->DC.MenuBarAppending = true;
  7307. ImGui::AlignFirstTextHeightToWidgets();
  7308. return true;
  7309. }
  7310. void ImGui::EndMenuBar()
  7311. {
  7312. ImGuiWindow* window = GetCurrentWindow();
  7313. if (window->SkipItems)
  7314. return;
  7315. IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
  7316. IM_ASSERT(window->DC.MenuBarAppending);
  7317. PopClipRect();
  7318. ImGui::PopID();
  7319. window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
  7320. window->DC.GroupStack.back().AdvanceCursor = false;
  7321. ImGui::EndGroup();
  7322. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  7323. window->DC.MenuBarAppending = false;
  7324. }
  7325. bool ImGui::BeginMenu(const char* label, bool enabled)
  7326. {
  7327. ImGuiWindow* window = GetCurrentWindow();
  7328. if (window->SkipItems)
  7329. return false;
  7330. ImGuiState& g = *GImGui;
  7331. const ImGuiStyle& style = g.Style;
  7332. const ImGuiID id = window->GetID(label);
  7333. ImVec2 label_size = CalcTextSize(label, NULL, true);
  7334. ImGuiWindow* backed_focused_window = g.FocusedWindow;
  7335. bool pressed;
  7336. bool opened = IsPopupOpen(id);
  7337. bool menuset_opened = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenedPopupStack.Size > g.CurrentPopupStack.Size && g.OpenedPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus"));
  7338. if (menuset_opened)
  7339. g.FocusedWindow = window;
  7340. ImVec2 popup_pos, pos = window->DC.CursorPos;
  7341. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  7342. {
  7343. popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
  7344. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  7345. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
  7346. float w = label_size.x;
  7347. pressed = ImGui::Selectable(label, opened, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  7348. ImGui::PopStyleVar();
  7349. ImGui::SameLine();
  7350. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  7351. }
  7352. else
  7353. {
  7354. popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
  7355. float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
  7356. float extra_w = ImMax(0.0f, ImGui::GetContentRegionAvail().x - w);
  7357. pressed = ImGui::Selectable(label, opened, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  7358. if (!enabled) ImGui::PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  7359. RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false);
  7360. if (!enabled) ImGui::PopStyleColor();
  7361. }
  7362. bool hovered = enabled && IsHovered(window->DC.LastItemRect, id);
  7363. if (menuset_opened)
  7364. g.FocusedWindow = backed_focused_window;
  7365. bool want_open = false, want_close = false;
  7366. if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
  7367. {
  7368. // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers so menus feel more reactive.
  7369. bool moving_within_opened_triangle = false;
  7370. if (g.HoveredWindow == window && g.OpenedPopupStack.Size > g.CurrentPopupStack.Size && g.OpenedPopupStack[g.CurrentPopupStack.Size].ParentWindow == window)
  7371. {
  7372. if (ImGuiWindow* next_window = g.OpenedPopupStack[g.CurrentPopupStack.Size].Window)
  7373. {
  7374. ImRect next_window_rect = next_window->Rect();
  7375. ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
  7376. ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
  7377. ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
  7378. float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
  7379. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
  7380. tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus
  7381. tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
  7382. moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc);
  7383. //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? 0x80008000 : 0x80000080); window->DrawList->PopClipRect(); // Debug
  7384. }
  7385. }
  7386. want_close = (opened && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
  7387. want_open = (!opened && hovered && !moving_within_opened_triangle) || (!opened && hovered && pressed);
  7388. }
  7389. else if (opened && pressed && menuset_opened) // menu-bar: click open menu to close
  7390. {
  7391. want_close = true;
  7392. want_open = opened = false;
  7393. }
  7394. else if (pressed || (hovered && menuset_opened && !opened)) // menu-bar: first click to open, then hover to open others
  7395. want_open = true;
  7396. if (want_close && IsPopupOpen(id))
  7397. ClosePopupToLevel(GImGui->CurrentPopupStack.Size);
  7398. if (!opened && want_open && g.OpenedPopupStack.Size > g.CurrentPopupStack.Size)
  7399. {
  7400. // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
  7401. ImGui::OpenPopup(label);
  7402. return false;
  7403. }
  7404. opened |= want_open;
  7405. if (want_open)
  7406. ImGui::OpenPopup(label);
  7407. if (opened)
  7408. {
  7409. ImGui::SetNextWindowPos(popup_pos, ImGuiSetCond_Always);
  7410. ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
  7411. opened = BeginPopupEx(label, flags); // opened can be 'false' when the popup is completely clipped (e.g. zero size display)
  7412. }
  7413. return opened;
  7414. }
  7415. void ImGui::EndMenu()
  7416. {
  7417. ImGui::EndPopup();
  7418. }
  7419. // A little colored square. Return true when clicked.
  7420. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
  7421. bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border)
  7422. {
  7423. ImGuiWindow* window = GetCurrentWindow();
  7424. if (window->SkipItems)
  7425. return false;
  7426. ImGuiState& g = *GImGui;
  7427. const ImGuiStyle& style = g.Style;
  7428. const ImGuiID id = window->GetID("#colorbutton");
  7429. const float square_size = g.FontSize;
  7430. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2)));
  7431. ItemSize(bb, small_height ? 0.0f : style.FramePadding.y);
  7432. if (!ItemAdd(bb, &id))
  7433. return false;
  7434. bool hovered, held;
  7435. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  7436. RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding);
  7437. if (hovered)
  7438. ImGui::SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8(col.x), IM_F32_TO_INT8(col.y), IM_F32_TO_INT8(col.z), IM_F32_TO_INT8(col.z));
  7439. return pressed;
  7440. }
  7441. bool ImGui::ColorEdit3(const char* label, float col[3])
  7442. {
  7443. float col4[4];
  7444. col4[0] = col[0];
  7445. col4[1] = col[1];
  7446. col4[2] = col[2];
  7447. col4[3] = 1.0f;
  7448. const bool value_changed = ImGui::ColorEdit4(label, col4, false);
  7449. col[0] = col4[0];
  7450. col[1] = col4[1];
  7451. col[2] = col4[2];
  7452. return value_changed;
  7453. }
  7454. // Edit colors components (each component in 0.0f..1.0f range
  7455. // Use CTRL-Click to input value and TAB to go to next item.
  7456. bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha)
  7457. {
  7458. ImGuiWindow* window = GetCurrentWindow();
  7459. if (window->SkipItems)
  7460. return false;
  7461. ImGuiState& g = *GImGui;
  7462. const ImGuiStyle& style = g.Style;
  7463. const ImGuiID id = window->GetID(label);
  7464. const float w_full = CalcItemWidth();
  7465. const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f);
  7466. ImGuiColorEditMode edit_mode = window->DC.ColorEditMode;
  7467. if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton)
  7468. edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3;
  7469. float f[4] = { col[0], col[1], col[2], col[3] };
  7470. if (edit_mode == ImGuiColorEditMode_HSV)
  7471. ImGui::ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
  7472. int i[4] = { IM_F32_TO_INT8(f[0]), IM_F32_TO_INT8(f[1]), IM_F32_TO_INT8(f[2]), IM_F32_TO_INT8(f[3]) };
  7473. int components = alpha ? 4 : 3;
  7474. bool value_changed = false;
  7475. ImGui::BeginGroup();
  7476. ImGui::PushID(label);
  7477. const bool hsv = (edit_mode == 1);
  7478. switch (edit_mode)
  7479. {
  7480. case ImGuiColorEditMode_RGB:
  7481. case ImGuiColorEditMode_HSV:
  7482. {
  7483. // RGB/HSV 0..255 Sliders
  7484. const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x);
  7485. const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  7486. const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  7487. const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x);
  7488. const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
  7489. const char* fmt_table[3][4] =
  7490. {
  7491. { "%3.0f", "%3.0f", "%3.0f", "%3.0f" },
  7492. { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" },
  7493. { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" }
  7494. };
  7495. const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1];
  7496. ImGui::PushItemWidth(w_item_one);
  7497. for (int n = 0; n < components; n++)
  7498. {
  7499. if (n > 0)
  7500. ImGui::SameLine(0, style.ItemInnerSpacing.x);
  7501. if (n + 1 == components)
  7502. ImGui::PushItemWidth(w_item_last);
  7503. value_changed |= ImGui::DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]);
  7504. }
  7505. ImGui::PopItemWidth();
  7506. ImGui::PopItemWidth();
  7507. }
  7508. break;
  7509. case ImGuiColorEditMode_HEX:
  7510. {
  7511. // RGB Hexadecimal Input
  7512. const float w_slider_all = w_full - square_sz;
  7513. char buf[64];
  7514. if (alpha)
  7515. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]);
  7516. else
  7517. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]);
  7518. ImGui::PushItemWidth(w_slider_all - style.ItemInnerSpacing.x);
  7519. if (ImGui::InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
  7520. {
  7521. value_changed |= true;
  7522. char* p = buf;
  7523. while (*p == '#' || ImCharIsSpace(*p))
  7524. p++;
  7525. i[0] = i[1] = i[2] = i[3] = 0;
  7526. if (alpha)
  7527. sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
  7528. else
  7529. sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
  7530. }
  7531. ImGui::PopItemWidth();
  7532. }
  7533. break;
  7534. }
  7535. ImGui::SameLine(0, style.ItemInnerSpacing.x);
  7536. const ImVec4 col_display(col[0], col[1], col[2], 1.0f);
  7537. if (ImGui::ColorButton(col_display))
  7538. g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
  7539. // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here
  7540. if (ImGui::IsItemHovered())
  7541. ImGui::SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8(col[0]), IM_F32_TO_INT8(col[1]), IM_F32_TO_INT8(col[2]), IM_F32_TO_INT8(col[3]));
  7542. if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton)
  7543. {
  7544. ImGui::SameLine(0, style.ItemInnerSpacing.x);
  7545. const char* button_titles[3] = { "RGB", "HSV", "HEX" };
  7546. if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups))
  7547. g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
  7548. }
  7549. const char* label_display_end = FindTextDisplayEnd(label);
  7550. if (label != label_display_end)
  7551. {
  7552. ImGui::SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x);
  7553. ImGui::TextUnformatted(label, label_display_end);
  7554. }
  7555. // Convert back
  7556. for (int n = 0; n < 4; n++)
  7557. f[n] = i[n] / 255.0f;
  7558. if (edit_mode == 1)
  7559. ImGui::ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
  7560. if (value_changed)
  7561. {
  7562. col[0] = f[0];
  7563. col[1] = f[1];
  7564. col[2] = f[2];
  7565. if (alpha)
  7566. col[3] = f[3];
  7567. }
  7568. ImGui::PopID();
  7569. ImGui::EndGroup();
  7570. return value_changed;
  7571. }
  7572. void ImGui::ColorEditMode(ImGuiColorEditMode mode)
  7573. {
  7574. ImGuiWindow* window = GetCurrentWindow();
  7575. window->DC.ColorEditMode = mode;
  7576. }
  7577. // Horizontal separating line.
  7578. void ImGui::Separator()
  7579. {
  7580. ImGuiWindow* window = GetCurrentWindow();
  7581. if (window->SkipItems)
  7582. return;
  7583. if (window->DC.ColumnsCount > 1)
  7584. PopClipRect();
  7585. float x1 = window->Pos.x;
  7586. float x2 = window->Pos.x + window->Size.x;
  7587. if (!window->DC.GroupStack.empty())
  7588. x1 += window->DC.IndentX;
  7589. const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y));
  7590. ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit // FIXME: Height should be 1.0f not 0.0f ?
  7591. if (!ItemAdd(bb, NULL))
  7592. {
  7593. if (window->DC.ColumnsCount > 1)
  7594. PushColumnClipRect();
  7595. return;
  7596. }
  7597. window->DrawList->AddLine(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border));
  7598. ImGuiState& g = *GImGui;
  7599. if (g.LogEnabled)
  7600. ImGui::LogText(IM_NEWLINE "--------------------------------");
  7601. if (window->DC.ColumnsCount > 1)
  7602. {
  7603. PushColumnClipRect();
  7604. window->DC.ColumnsCellMinY = window->DC.CursorPos.y;
  7605. }
  7606. }
  7607. void ImGui::Spacing()
  7608. {
  7609. ImGuiWindow* window = GetCurrentWindow();
  7610. if (window->SkipItems)
  7611. return;
  7612. ItemSize(ImVec2(0,0));
  7613. }
  7614. void ImGui::Dummy(const ImVec2& size)
  7615. {
  7616. ImGuiWindow* window = GetCurrentWindow();
  7617. if (window->SkipItems)
  7618. return;
  7619. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  7620. ItemSize(bb);
  7621. ItemAdd(bb, NULL);
  7622. }
  7623. bool ImGui::IsRectVisible(const ImVec2& size)
  7624. {
  7625. ImGuiWindow* window = GetCurrentWindowRead();
  7626. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  7627. }
  7628. void ImGui::BeginGroup()
  7629. {
  7630. ImGuiWindow* window = GetCurrentWindow();
  7631. window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
  7632. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  7633. group_data.BackupCursorPos = window->DC.CursorPos;
  7634. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  7635. group_data.BackupIndentX = window->DC.IndentX;
  7636. group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
  7637. group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
  7638. group_data.BackupLogLinePosY = window->DC.LogLinePosY;
  7639. group_data.AdvanceCursor = true;
  7640. window->DC.IndentX = window->DC.CursorPos.x - window->Pos.x;
  7641. window->DC.CursorMaxPos = window->DC.CursorPos;
  7642. window->DC.CurrentLineHeight = 0.0f;
  7643. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  7644. }
  7645. void ImGui::EndGroup()
  7646. {
  7647. ImGuiWindow* window = GetCurrentWindow();
  7648. ImGuiStyle& style = ImGui::GetStyle();
  7649. IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
  7650. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  7651. ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
  7652. group_bb.Max.y -= style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves.
  7653. group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
  7654. window->DC.CursorPos = group_data.BackupCursorPos;
  7655. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  7656. window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight;
  7657. window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
  7658. window->DC.IndentX = group_data.BackupIndentX;
  7659. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  7660. if (group_data.AdvanceCursor)
  7661. {
  7662. 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.
  7663. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
  7664. ItemAdd(group_bb, NULL);
  7665. }
  7666. window->DC.GroupStack.pop_back();
  7667. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, 0xFFFF00FF); // Debug
  7668. }
  7669. // Gets back to previous line and continue with horizontal layout
  7670. // local_pos_x == 0 : follow on previous item
  7671. // local_pos_x != 0 : align to specified column
  7672. // spacing_w < 0 : use default spacing if column_x==0, no spacing if column_x!=0
  7673. // spacing_w >= 0 : enforce spacing
  7674. void ImGui::SameLine(float local_pos_x, float spacing_w)
  7675. {
  7676. ImGuiWindow* window = GetCurrentWindow();
  7677. if (window->SkipItems)
  7678. return;
  7679. ImGuiState& g = *GImGui;
  7680. float x, y;
  7681. if (local_pos_x != 0.0f)
  7682. {
  7683. if (spacing_w < 0.0f) spacing_w = 0.0f;
  7684. x = window->Pos.x - window->Scroll.x + local_pos_x + spacing_w;
  7685. y = window->DC.CursorPosPrevLine.y;
  7686. }
  7687. else
  7688. {
  7689. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  7690. x = window->DC.CursorPosPrevLine.x + spacing_w;
  7691. y = window->DC.CursorPosPrevLine.y;
  7692. }
  7693. window->DC.CurrentLineHeight = window->DC.PrevLineHeight;
  7694. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  7695. window->DC.CursorPos = ImVec2(x, y);
  7696. }
  7697. void ImGui::NextColumn()
  7698. {
  7699. ImGuiWindow* window = GetCurrentWindow();
  7700. if (window->SkipItems)
  7701. return;
  7702. ImGuiState& g = *GImGui;
  7703. if (window->DC.ColumnsCount > 1)
  7704. {
  7705. ImGui::PopItemWidth();
  7706. PopClipRect();
  7707. window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
  7708. if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount)
  7709. {
  7710. // Columns 1+ cancel out IndentX
  7711. window->DC.ColumnsOffsetX = ImGui::GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x;
  7712. window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent);
  7713. }
  7714. else
  7715. {
  7716. window->DC.ColumnsCurrent = 0;
  7717. window->DC.ColumnsOffsetX = 0.0f;
  7718. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY;
  7719. window->DrawList->ChannelsSetCurrent(0);
  7720. }
  7721. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  7722. window->DC.CursorPos.y = window->DC.ColumnsCellMinY;
  7723. window->DC.CurrentLineHeight = 0.0f;
  7724. window->DC.CurrentLineTextBaseOffset = 0.0f;
  7725. PushColumnClipRect();
  7726. ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
  7727. }
  7728. }
  7729. int ImGui::GetColumnIndex()
  7730. {
  7731. ImGuiWindow* window = GetCurrentWindowRead();
  7732. return window->DC.ColumnsCurrent;
  7733. }
  7734. int ImGui::GetColumnsCount()
  7735. {
  7736. ImGuiWindow* window = GetCurrentWindowRead();
  7737. return window->DC.ColumnsCount;
  7738. }
  7739. static float GetDraggedColumnOffset(int column_index)
  7740. {
  7741. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  7742. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  7743. ImGuiState& g = *GImGui;
  7744. ImGuiWindow* window = ImGui::GetCurrentWindowRead();
  7745. IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets.
  7746. IM_ASSERT(g.ActiveId == window->DC.ColumnsSetID + ImGuiID(column_index));
  7747. float x = g.IO.MousePos.x + g.ActiveClickDeltaToCenter.x - window->Pos.x;
  7748. x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing);
  7749. return (float)(int)x;
  7750. }
  7751. float ImGui::GetColumnOffset(int column_index)
  7752. {
  7753. ImGuiState& g = *GImGui;
  7754. ImGuiWindow* window = GetCurrentWindowRead();
  7755. if (column_index < 0)
  7756. column_index = window->DC.ColumnsCurrent;
  7757. if (g.ActiveId)
  7758. {
  7759. const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index);
  7760. if (g.ActiveId == column_id)
  7761. return GetDraggedColumnOffset(column_index);
  7762. }
  7763. IM_ASSERT(column_index < window->DC.ColumnsData.Size);
  7764. const float t = window->DC.ColumnsData[column_index].OffsetNorm;
  7765. const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
  7766. return (float)(int)x_offset;
  7767. }
  7768. void ImGui::SetColumnOffset(int column_index, float offset)
  7769. {
  7770. ImGuiWindow* window = GetCurrentWindow();
  7771. if (column_index < 0)
  7772. column_index = window->DC.ColumnsCurrent;
  7773. IM_ASSERT(column_index < window->DC.ColumnsData.Size);
  7774. const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
  7775. window->DC.ColumnsData[column_index].OffsetNorm = t;
  7776. const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index);
  7777. window->DC.StateStorage->SetFloat(column_id, t);
  7778. }
  7779. float ImGui::GetColumnWidth(int column_index)
  7780. {
  7781. ImGuiWindow* window = GetCurrentWindowRead();
  7782. if (column_index < 0)
  7783. column_index = window->DC.ColumnsCurrent;
  7784. const float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index);
  7785. return w;
  7786. }
  7787. static void PushColumnClipRect(int column_index)
  7788. {
  7789. ImGuiWindow* window = ImGui::GetCurrentWindow();
  7790. if (column_index < 0)
  7791. column_index = window->DC.ColumnsCurrent;
  7792. const float x1 = window->Pos.x + ImGui::GetColumnOffset(column_index) - 1;
  7793. const float x2 = window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1;
  7794. ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true);
  7795. }
  7796. void ImGui::Columns(int columns_count, const char* id, bool border)
  7797. {
  7798. ImGuiState& g = *GImGui;
  7799. ImGuiWindow* window = GetCurrentWindow();
  7800. IM_ASSERT(columns_count >= 1);
  7801. if (window->DC.ColumnsCount != 1)
  7802. {
  7803. if (window->DC.ColumnsCurrent != 0)
  7804. ItemSize(ImVec2(0,0)); // Advance to column 0
  7805. ImGui::PopItemWidth();
  7806. PopClipRect();
  7807. window->DrawList->ChannelsMerge();
  7808. window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
  7809. window->DC.CursorPos.y = window->DC.ColumnsCellMaxY;
  7810. }
  7811. // Draw columns borders and handle resize at the time of "closing" a columns set
  7812. if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems)
  7813. {
  7814. const float y1 = window->DC.ColumnsStartPosY;
  7815. const float y2 = window->DC.CursorPos.y;
  7816. for (int i = 1; i < window->DC.ColumnsCount; i++)
  7817. {
  7818. float x = window->Pos.x + GetColumnOffset(i);
  7819. const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(i);
  7820. const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2));
  7821. if (IsClippedEx(column_rect, &column_id, false))
  7822. continue;
  7823. bool hovered, held;
  7824. ButtonBehavior(column_rect, column_id, &hovered, &held, true);
  7825. if (hovered || held)
  7826. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  7827. // Draw before resize so our items positioning are in sync with the line being drawn
  7828. const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column);
  7829. const float xi = (float)(int)x;
  7830. window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col);
  7831. if (held)
  7832. {
  7833. if (g.ActiveIdIsJustActivated)
  7834. g.ActiveClickDeltaToCenter.x = x - g.IO.MousePos.x;
  7835. x = GetDraggedColumnOffset(i);
  7836. SetColumnOffset(i, x);
  7837. }
  7838. }
  7839. }
  7840. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  7841. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  7842. ImGui::PushID(0x11223347 + (id ? 0 : columns_count));
  7843. window->DC.ColumnsSetID = window->GetID(id ? id : "columns");
  7844. ImGui::PopID();
  7845. // Set state for first column
  7846. window->DC.ColumnsCurrent = 0;
  7847. window->DC.ColumnsCount = columns_count;
  7848. window->DC.ColumnsShowBorders = border;
  7849. const float content_region_width = window->SizeContentsExplicit.x ? window->SizeContentsExplicit.x : window->Size.x;
  7850. window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range
  7851. window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
  7852. window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
  7853. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y;
  7854. window->DC.ColumnsOffsetX = 0.0f;
  7855. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  7856. if (window->DC.ColumnsCount != 1)
  7857. {
  7858. // Cache column offsets
  7859. window->DC.ColumnsData.resize(columns_count + 1);
  7860. for (int column_index = 0; column_index < columns_count + 1; column_index++)
  7861. {
  7862. const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index);
  7863. KeepAliveID(column_id);
  7864. const float default_t = column_index / (float)window->DC.ColumnsCount;
  7865. const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store an union into the map?)
  7866. window->DC.ColumnsData[column_index].OffsetNorm = t;
  7867. }
  7868. window->DrawList->ChannelsSplit(window->DC.ColumnsCount);
  7869. PushColumnClipRect();
  7870. ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f);
  7871. }
  7872. else
  7873. {
  7874. window->DC.ColumnsData.resize(0);
  7875. }
  7876. }
  7877. void ImGui::Indent()
  7878. {
  7879. ImGuiState& g = *GImGui;
  7880. ImGuiWindow* window = GetCurrentWindow();
  7881. window->DC.IndentX += g.Style.IndentSpacing;
  7882. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  7883. }
  7884. void ImGui::Unindent()
  7885. {
  7886. ImGuiState& g = *GImGui;
  7887. ImGuiWindow* window = GetCurrentWindow();
  7888. window->DC.IndentX -= g.Style.IndentSpacing;
  7889. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  7890. }
  7891. void ImGui::TreePush(const char* str_id)
  7892. {
  7893. ImGuiWindow* window = GetCurrentWindow();
  7894. ImGui::Indent();
  7895. window->DC.TreeDepth++;
  7896. PushID(str_id ? str_id : "#TreePush");
  7897. }
  7898. void ImGui::TreePush(const void* ptr_id)
  7899. {
  7900. ImGuiWindow* window = GetCurrentWindow();
  7901. ImGui::Indent();
  7902. window->DC.TreeDepth++;
  7903. PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
  7904. }
  7905. void ImGui::TreePop()
  7906. {
  7907. ImGuiWindow* window = GetCurrentWindow();
  7908. ImGui::Unindent();
  7909. window->DC.TreeDepth--;
  7910. PopID();
  7911. }
  7912. void ImGui::Value(const char* prefix, bool b)
  7913. {
  7914. ImGui::Text("%s: %s", prefix, (b ? "true" : "false"));
  7915. }
  7916. void ImGui::Value(const char* prefix, int v)
  7917. {
  7918. ImGui::Text("%s: %d", prefix, v);
  7919. }
  7920. void ImGui::Value(const char* prefix, unsigned int v)
  7921. {
  7922. ImGui::Text("%s: %d", prefix, v);
  7923. }
  7924. void ImGui::Value(const char* prefix, float v, const char* float_format)
  7925. {
  7926. if (float_format)
  7927. {
  7928. char fmt[64];
  7929. ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
  7930. ImGui::Text(fmt, prefix, v);
  7931. }
  7932. else
  7933. {
  7934. ImGui::Text("%s: %.3f", prefix, v);
  7935. }
  7936. }
  7937. // FIXME: May want to remove those helpers?
  7938. void ImGui::ValueColor(const char* prefix, const ImVec4& v)
  7939. {
  7940. ImGui::Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w);
  7941. ImGui::SameLine();
  7942. ImGui::ColorButton(v, true);
  7943. }
  7944. void ImGui::ValueColor(const char* prefix, unsigned int v)
  7945. {
  7946. ImGui::Text("%s: %08X", prefix, v);
  7947. ImGui::SameLine();
  7948. ImVec4 col;
  7949. col.x = (float)((v >> 0) & 0xFF) / 255.0f;
  7950. col.y = (float)((v >> 8) & 0xFF) / 255.0f;
  7951. col.z = (float)((v >> 16) & 0xFF) / 255.0f;
  7952. col.w = (float)((v >> 24) & 0xFF) / 255.0f;
  7953. ImGui::ColorButton(col, true);
  7954. }
  7955. //-----------------------------------------------------------------------------
  7956. // PLATFORM DEPENDANT HELPERS
  7957. //-----------------------------------------------------------------------------
  7958. #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS))
  7959. #undef WIN32_LEAN_AND_MEAN
  7960. #define WIN32_LEAN_AND_MEAN
  7961. #include <windows.h>
  7962. #endif
  7963. // Win32 API clipboard implementation
  7964. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS)
  7965. #ifdef _MSC_VER
  7966. #pragma comment(lib, "user32")
  7967. #endif
  7968. static const char* GetClipboardTextFn_DefaultImpl()
  7969. {
  7970. static char* buf_local = NULL;
  7971. if (buf_local)
  7972. {
  7973. ImGui::MemFree(buf_local);
  7974. buf_local = NULL;
  7975. }
  7976. if (!OpenClipboard(NULL))
  7977. return NULL;
  7978. HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
  7979. if (wbuf_handle == NULL)
  7980. return NULL;
  7981. if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
  7982. {
  7983. int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
  7984. buf_local = (char*)ImGui::MemAlloc(buf_len * sizeof(char));
  7985. ImTextStrToUtf8(buf_local, buf_len, wbuf_global, NULL);
  7986. }
  7987. GlobalUnlock(wbuf_handle);
  7988. CloseClipboard();
  7989. return buf_local;
  7990. }
  7991. static void SetClipboardTextFn_DefaultImpl(const char* text)
  7992. {
  7993. if (!OpenClipboard(NULL))
  7994. return;
  7995. const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
  7996. HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
  7997. if (wbuf_handle == NULL)
  7998. return;
  7999. ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
  8000. ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
  8001. GlobalUnlock(wbuf_handle);
  8002. EmptyClipboard();
  8003. SetClipboardData(CF_UNICODETEXT, wbuf_handle);
  8004. CloseClipboard();
  8005. }
  8006. #else
  8007. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  8008. static const char* GetClipboardTextFn_DefaultImpl()
  8009. {
  8010. return GImGui->PrivateClipboard;
  8011. }
  8012. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  8013. static void SetClipboardTextFn_DefaultImpl(const char* text)
  8014. {
  8015. ImGuiState& g = *GImGui;
  8016. if (g.PrivateClipboard)
  8017. {
  8018. ImGui::MemFree(g.PrivateClipboard);
  8019. g.PrivateClipboard = NULL;
  8020. }
  8021. const char* text_end = text + strlen(text);
  8022. g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1);
  8023. memcpy(g.PrivateClipboard, text, (size_t)(text_end - text));
  8024. g.PrivateClipboard[(int)(text_end - text)] = 0;
  8025. }
  8026. #endif
  8027. // Win32 API IME support (for Asian languages, etc.)
  8028. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)
  8029. #include <imm.h>
  8030. #ifdef _MSC_VER
  8031. #pragma comment(lib, "imm32")
  8032. #endif
  8033. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
  8034. {
  8035. // Notify OS Input Method Editor of text input position
  8036. if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
  8037. if (HIMC himc = ImmGetContext(hwnd))
  8038. {
  8039. COMPOSITIONFORM cf;
  8040. cf.ptCurrentPos.x = x;
  8041. cf.ptCurrentPos.y = y;
  8042. cf.dwStyle = CFS_FORCE_POSITION;
  8043. ImmSetCompositionWindow(himc, &cf);
  8044. }
  8045. }
  8046. #else
  8047. static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
  8048. #endif
  8049. //-----------------------------------------------------------------------------
  8050. // HELP
  8051. //-----------------------------------------------------------------------------
  8052. void ImGui::ShowMetricsWindow(bool* opened)
  8053. {
  8054. if (ImGui::Begin("ImGui Metrics", opened))
  8055. {
  8056. ImGui::Text("ImGui %s", ImGui::GetVersion());
  8057. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  8058. ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
  8059. ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs);
  8060. static bool show_clip_rects = true;
  8061. ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects);
  8062. ImGui::Separator();
  8063. struct Funcs
  8064. {
  8065. static void NodeDrawList(ImDrawList* draw_list, const char* label)
  8066. {
  8067. bool node_opened = 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);
  8068. if (draw_list == ImGui::GetWindowDrawList())
  8069. {
  8070. ImGui::SameLine();
  8071. ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  8072. }
  8073. if (!node_opened)
  8074. return;
  8075. int elem_offset = 0;
  8076. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
  8077. {
  8078. if (pcmd->UserCallback)
  8079. {
  8080. ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  8081. continue;
  8082. }
  8083. ImGui::BulletText("Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  8084. if (show_clip_rects && ImGui::IsItemHovered())
  8085. {
  8086. ImRect clip_rect = pcmd->ClipRect;
  8087. ImRect vtxs_rect;
  8088. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  8089. for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
  8090. vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
  8091. GImGui->OverlayDrawList.PushClipRectFullScreen();
  8092. clip_rect.Round(); GImGui->OverlayDrawList.AddRect(clip_rect.Min, clip_rect.Max, ImColor(255,255,0));
  8093. vtxs_rect.Round(); GImGui->OverlayDrawList.AddRect(vtxs_rect.Min, vtxs_rect.Max, ImColor(255,0,255));
  8094. GImGui->OverlayDrawList.PopClipRect();
  8095. }
  8096. }
  8097. ImGui::TreePop();
  8098. }
  8099. static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
  8100. {
  8101. if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
  8102. return;
  8103. for (int i = 0; i < windows.Size; i++)
  8104. Funcs::NodeWindow(windows[i], "Window");
  8105. ImGui::TreePop();
  8106. }
  8107. static void NodeWindow(ImGuiWindow* window, const char* label)
  8108. {
  8109. if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
  8110. return;
  8111. NodeDrawList(window->DrawList, "DrawList");
  8112. if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
  8113. if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
  8114. ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
  8115. ImGui::TreePop();
  8116. }
  8117. };
  8118. ImGuiState& g = *GImGui; // Access private state
  8119. Funcs::NodeWindows(g.Windows, "Windows");
  8120. if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size))
  8121. {
  8122. for (int i = 0; i < g.RenderDrawLists[0].Size; i++)
  8123. Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList");
  8124. ImGui::TreePop();
  8125. }
  8126. if (ImGui::TreeNode("Popups", "Opened Popups Stack (%d)", g.OpenedPopupStack.Size))
  8127. {
  8128. for (int i = 0; i < g.OpenedPopupStack.Size; i++)
  8129. {
  8130. ImGuiWindow* window = g.OpenedPopupStack[i].Window;
  8131. ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenedPopupStack[i].PopupID, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
  8132. }
  8133. ImGui::TreePop();
  8134. }
  8135. if (ImGui::TreeNode("Basic state"))
  8136. {
  8137. ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL");
  8138. ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  8139. ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
  8140. ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
  8141. ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame);
  8142. ImGui::TreePop();
  8143. }
  8144. }
  8145. ImGui::End();
  8146. }
  8147. //-----------------------------------------------------------------------------
  8148. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  8149. // 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.
  8150. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  8151. #include "imgui_user.inl"
  8152. #endif
  8153. //-----------------------------------------------------------------------------