imgui.cpp 529 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863
  1. // dear imgui, v1.54 WIP
  2. // (main code and documentation)
  3. // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
  4. // Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
  5. // Get latest version at https://github.com/ocornut/imgui
  6. // Releases change-log at https://github.com/ocornut/imgui/releases
  7. // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
  8. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  9. // This library is free but I need your support to sustain development and maintenance.
  10. // If you work for a company, please consider financial support, see Readme. For individuals: https://www.patreon.com/imgui
  11. /*
  12. Index
  13. - MISSION STATEMENT
  14. - END-USER GUIDE
  15. - PROGRAMMER GUIDE (read me!)
  16. - Read first
  17. - How to update to a newer version of Dear ImGui
  18. - Getting started with integrating Dear ImGui in your code/engine
  19. - API BREAKING CHANGES (read me when you update!)
  20. - ISSUES & TODO LIST
  21. - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  22. - How can I help?
  23. - How can I display an image? What is ImTextureID, how does it works?
  24. - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels and the ID stack.
  25. - How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
  26. - How can I load a different font than the default?
  27. - How can I easily use icons in my application?
  28. - How can I load multiple fonts?
  29. - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
  30. - How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables)
  31. - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  32. - I integrated Dear ImGui in my engine and the text or lines are blurry..
  33. - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  34. - ISSUES & TODO-LIST
  35. - CODE
  36. MISSION STATEMENT
  37. =================
  38. - Easy to use to create code-driven and data-driven tools
  39. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
  40. - Easy to hack and improve
  41. - Minimize screen real-estate usage
  42. - Minimize setup and maintenance
  43. - Minimize state storage on user side
  44. - Portable, minimize dependencies, run on target (consoles, phones, etc.)
  45. - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window, opening a tree node
  46. for the first time, etc. but a typical frame won't allocate anything)
  47. Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
  48. - Doesn't look fancy, doesn't animate
  49. - Limited layout features, intricate layouts are typically crafted in code
  50. END-USER GUIDE
  51. ==============
  52. - Double-click on title bar to collapse window.
  53. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
  54. - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
  55. - Click and drag on any empty space to move window.
  56. - TAB/SHIFT+TAB to cycle through keyboard editable fields.
  57. - CTRL+Click on a slider or drag box to input value as text.
  58. - Use mouse wheel to scroll.
  59. - Text editor:
  60. - Hold SHIFT or use mouse to select text.
  61. - CTRL+Left/Right to word jump.
  62. - CTRL+Shift+Left/Right to select words.
  63. - CTRL+A our Double-Click to select all.
  64. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
  65. - CTRL+Z,CTRL+Y to undo/redo.
  66. - ESCAPE to revert text to its original value.
  67. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  68. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  69. PROGRAMMER GUIDE
  70. ================
  71. READ FIRST
  72. - Read the FAQ below this section!
  73. - 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
  74. on your side, no state duplication, less sync, less bugs.
  75. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
  76. - You can learn about immediate-mode gui principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861
  77. HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  78. - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
  79. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  80. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API.
  81. If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it.
  82. Please report any issue to the GitHub page!
  83. - Try to keep your copy of dear imgui reasonably up to date.
  84. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  85. - Add the Dear ImGui source files to your projects, using your preferred build system.
  86. It is recommended you build the .cpp files as part of your project and not as a library.
  87. - You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types.
  88. - See examples/ folder for standalone sample applications.
  89. - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
  90. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
  91. - Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize
  92. (application resolution). Later on you will fill your keyboard mapping, clipboard handlers, and other advanced features but for a basic
  93. integration you don't need to worry about it all.
  94. - Init: call io.Fonts->GetTexDataAsRGBA32(...), it will build the font atlas texture, then load the texture pixels into graphics memory.
  95. - Every frame:
  96. - In your main loop as early a possible, fill the IO fields marked 'Input' (e.g. mouse position, buttons, keyboard info, etc.)
  97. - Call ImGui::NewFrame() to begin the frame
  98. - You can use any ImGui function you want between NewFrame() and Render()
  99. - Call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your io.RenderDrawListFn handler.
  100. (Even if you don't render, call Render() and ignore the callback, or call EndFrame() instead. Otherwhise some features will break)
  101. - All rendering information are stored into command-lists until ImGui::Render() is called.
  102. - Dear ImGui never touches or knows about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide.
  103. - Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases
  104. of your own application.
  105. - Refer to the examples applications in the examples/ folder for instruction on how to setup your code.
  106. - A minimal application skeleton may be:
  107. // Application init
  108. ImGui::CreateContext();
  109. ImGuiIO& io = ImGui::GetIO();
  110. io.DisplaySize.x = 1920.0f;
  111. io.DisplaySize.y = 1280.0f;
  112. io.RenderDrawListsFn = MyRenderFunction; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access render data.
  113. // TODO: Fill others settings of the io structure later.
  114. // Load texture atlas (there is a default font so you don't need to care about choosing a font yet)
  115. unsigned char* pixels;
  116. int width, height;
  117. io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
  118. // TODO: At this points you've got the texture data and you need to upload that your your graphic system:
  119. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA)
  120. // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'. This will be passed back to your via the renderer.
  121. io.Fonts->TexID = (void*)texture;
  122. // Application main loop
  123. while (true)
  124. {
  125. // Setup low-level inputs (e.g. on Win32, GetKeyboardState(), or write to those fields from your Windows message loop handlers, etc.)
  126. ImGuiIO& io = ImGui::GetIO();
  127. io.DeltaTime = 1.0f/60.0f;
  128. io.MousePos = mouse_pos;
  129. io.MouseDown[0] = mouse_button_0;
  130. io.MouseDown[1] = mouse_button_1;
  131. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  132. ImGui::NewFrame();
  133. // Most of your application code here
  134. MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  135. MyGameRender(); // may use any ImGui functions as well!
  136. // Render & swap video buffers
  137. ImGui::Render();
  138. SwapBuffers();
  139. }
  140. // Shutdown
  141. ImGui::DestroyContext();
  142. - A minimal render function skeleton may be:
  143. void void MyRenderFunction(ImDrawData* draw_data)
  144. {
  145. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  146. // TODO: Setup viewport, orthographic projection matrix
  147. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  148. for (int n = 0; n < draw_data->CmdListsCount; n++)
  149. {
  150. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
  151. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
  152. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  153. {
  154. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  155. if (pcmd->UserCallback)
  156. {
  157. pcmd->UserCallback(cmd_list, pcmd);
  158. }
  159. else
  160. {
  161. // The texture for the draw call is specified by pcmd->TextureId.
  162. // The vast majority of draw calls with use the imgui texture atlas, which value you have set yourself during initialization.
  163. MyEngineBindTexture(pcmd->TextureId);
  164. // We are using scissoring to clip some objects. All low-level graphics API supports it.
  165. // If your engine doesn't support scissoring yet, you will get some small glitches (some elements outside their bounds) which you can fix later.
  166. MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  167. // Render 'pcmd->ElemCount/3' indexed triangles.
  168. // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits if your engine doesn't support 16-bits indices.
  169. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
  170. }
  171. idx_buffer += pcmd->ElemCount;
  172. }
  173. }
  174. }
  175. - The examples/ folders contains many functional implementation of the pseudo-code above.
  176. - When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated.
  177. They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide
  178. mouse inputs from the rest of your application. Read the FAQ below for more information about those flags.
  179. API BREAKING CHANGES
  180. ====================
  181. Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
  182. 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.
  183. Also read releases logs https://github.com/ocornut/imgui/releases for more details.
  184. - 2018/01/21 (1.XX) - reorganized context handling to be more explicit,
  185. - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
  186. - removed Shutdown() function, as DestroyContext() serve this purpose.
  187. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwhise CreateContext() will create its own font atlas instance.
  188. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
  189. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
  190. - 2018/01/11 (1.54) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
  191. - 2018/01/11 (1.54) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
  192. - 2018/01/03 (1.54) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
  193. - 2017/12/29 (1.54) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
  194. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
  195. - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
  196. - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
  197. - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
  198. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
  199. - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
  200. - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
  201. - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
  202. - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
  203. - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
  204. - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
  205. Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
  206. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
  207. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
  208. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
  209. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
  210. - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
  211. - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
  212. - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
  213. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
  214. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
  215. - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
  216. - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
  217. - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
  218. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
  219. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  220. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  221. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  222. - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
  223. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
  224. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
  225. - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
  226. - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
  227. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  228. - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
  229. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
  230. - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
  231. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  232. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  233. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  234. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
  235. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  236. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
  237. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
  238. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  239. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
  240. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
  241. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
  242. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
  243. {
  244. float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
  245. return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
  246. }
  247. If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
  248. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  249. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  250. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
  251. - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
  252. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
  253. - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
  254. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  255. - 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.
  256. - 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.
  257. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  258. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  259. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  260. 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.
  261. 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!
  262. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  263. - 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.
  264. - 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
  265. - 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.
  266. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  267. - 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.
  268. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  269. - 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.
  270. - the signature of the io.RenderDrawListsFn handler has changed!
  271. ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  272. became:
  273. ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  274. argument 'cmd_lists' -> 'draw_data->CmdLists'
  275. argument 'cmd_lists_count' -> 'draw_data->CmdListsCount'
  276. ImDrawList 'commands' -> 'CmdBuffer'
  277. ImDrawList 'vtx_buffer' -> 'VtxBuffer'
  278. ImDrawList n/a -> 'IdxBuffer' (new)
  279. ImDrawCmd 'vtx_count' -> 'ElemCount'
  280. ImDrawCmd 'clip_rect' -> 'ClipRect'
  281. ImDrawCmd 'user_callback' -> 'UserCallback'
  282. ImDrawCmd 'texture_id' -> 'TextureId'
  283. - 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.
  284. - 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!
  285. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  286. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  287. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  288. - 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.
  289. - 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
  290. - 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!
  291. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  292. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  293. - 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.
  294. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
  295. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  296. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  297. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  298. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  299. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  300. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  301. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  302. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  303. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  304. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  305. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  306. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  307. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  308. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  309. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  310. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  311. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  312. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  313. this sequence:
  314. const void* png_data;
  315. unsigned int png_size;
  316. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  317. // <Copy to GPU>
  318. became:
  319. unsigned char* pixels;
  320. int width, height;
  321. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  322. // <Copy to GPU>
  323. io.Fonts->TexID = (your_texture_identifier);
  324. you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
  325. it is now recommended that you sample the font texture with bilinear interpolation.
  326. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
  327. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  328. (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  329. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  330. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  331. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  332. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  333. - 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)
  334. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  335. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  336. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  337. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  338. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  339. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  340. ISSUES & TODO-LIST
  341. ==================
  342. See TODO.txt
  343. FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  344. ======================================
  345. Q: How can I help?
  346. A: - If you are experienced with Dear ImGui and C++, look at the github issues, or TODO.txt and see how you want/can help!
  347. - Convince your company to fund development time! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README.
  348. - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
  349. You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1269). Visuals are ideal as they inspire other programmers.
  350. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
  351. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
  352. Q: How can I display an image? What is ImTextureID, how does it works?
  353. A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
  354. Dear ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
  355. It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
  356. At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
  357. Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
  358. (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
  359. To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
  360. Dear ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
  361. You may call ImGui::ShowMetricsWindow() to explore active draw lists and visualize/understand how the draw data is generated.
  362. It is your responsibility to get textures uploaded to your GPU.
  363. Q: Can I have multiple widgets with the same label? Can I have widget without a label?
  364. A: Yes. A primer on labels and the ID stack...
  365. - Elements that are typically not clickable, such as Text() items don't need an ID.
  366. - Interactive widgets require state to be carried over multiple frames (most typically Dear ImGui often needs to remember what is
  367. the "active" widget). to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
  368. Button("OK"); // Label = "OK", ID = hash of "OK"
  369. Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
  370. - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK"
  371. in two different windows or in two different locations of a tree.
  372. - If you have a same ID twice in the same location, you'll have a conflict:
  373. Button("OK");
  374. Button("OK"); // ID collision! Both buttons will be treated as the same.
  375. Fear not! this is easy to solve and there are many ways to solve it!
  376. - When passing a label you can optionally specify extra unique ID information within string itself.
  377. Use "##" to pass a complement to the ID that won't be visible to the end-user.
  378. This helps solving the simple collision cases when you know which items are going to be created.
  379. Button("Play"); // Label = "Play", ID = hash of "Play"
  380. Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
  381. Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
  382. - If you want to completely hide the label, but still need an ID:
  383. Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
  384. - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels.
  385. For example you may want to include varying information in a window title bar, but windows are uniquely identified by their ID..
  386. Use "###" to pass a label that isn't part of ID:
  387. Button("Hello###ID"; // Label = "Hello", ID = hash of "ID"
  388. Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above)
  389. sprintf(buf, "My game (%f FPS)###MyGame", fps);
  390. Begin(buf); // Variable label, ID = hash of "MyGame"
  391. - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
  392. This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
  393. 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!
  394. for (int i = 0; i < 100; i++)
  395. {
  396. PushID(i);
  397. Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
  398. PopID();
  399. }
  400. for (int i = 0; i < 100; i++)
  401. {
  402. MyObject* obj = Objects[i];
  403. PushID(obj);
  404. Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
  405. PopID();
  406. }
  407. for (int i = 0; i < 100; i++)
  408. {
  409. MyObject* obj = Objects[i];
  410. PushID(obj->Name);
  411. Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
  412. PopID();
  413. }
  414. - More example showing that you can stack multiple prefixes into the ID stack:
  415. Button("Click"); // Label = "Click", ID = hash of "Click"
  416. PushID("node");
  417. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  418. PushID(my_ptr);
  419. Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click"
  420. PopID();
  421. PopID();
  422. - Tree nodes implicitly creates a scope for you by calling PushID().
  423. Button("Click"); // Label = "Click", ID = hash of "Click"
  424. if (TreeNode("node"))
  425. {
  426. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  427. TreePop();
  428. }
  429. - When working with trees, ID are used to preserve the open/close state of each tree node.
  430. Depending on your use cases you may want to use strings, indices or pointers as ID.
  431. e.g. when displaying a single object that may change over time (dynamic 1-1 relationship), using a static string as ID will preserve your
  432. node open/closed state when the targeted object change.
  433. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently.
  434. experiment and see what makes more sense!
  435. Q: How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
  436. A: You can read the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'ioWantTextInput' flags from the ImGuiIO structure.
  437. - When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
  438. - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
  439. Preferably read the flags after calling ImGui::NewFrame() to avoid them lagging by one frame. But reading those flags before calling NewFrame() is
  440. also generally ok, as the bool toggles fairly rarely and you don't generally expect to interact with either Dear ImGui or your application during
  441. the same frame when that transition occurs. Dear ImGui is tracking dragging and widget activity that may occur outside the boundary of a window,
  442. so 'io.WantCaptureMouse' is more accurate and correct than checking if a window is hovered.
  443. (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically
  444. have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
  445. were for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
  446. Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
  447. A: Use the font atlas to load the TTF/OTF file you want:
  448. ImGuiIO& io = ImGui::GetIO();
  449. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  450. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  451. Q: How can I easily use icons in my application?
  452. A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your
  453. strings. Read 'How can I load multiple fonts?' and the file 'misc/fonts/README.txt' for instructions and useful header files.
  454. Q: How can I load multiple fonts?
  455. A: Use the font atlas to pack them into a single texture:
  456. (Read misc/fonts/README.txt and the code in ImFontAtlas for more details.)
  457. ImGuiIO& io = ImGui::GetIO();
  458. ImFont* font0 = io.Fonts->AddFontDefault();
  459. ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  460. ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
  461. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  462. // the first loaded font gets used by default
  463. // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
  464. // Options
  465. ImFontConfig config;
  466. config.OversampleH = 3;
  467. config.OversampleV = 1;
  468. config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up
  469. config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
  470. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
  471. // Combine multiple fonts into one (e.g. for icon fonts)
  472. ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
  473. ImFontConfig config;
  474. config.MergeMode = true;
  475. io.Fonts->AddFontDefault();
  476. io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
  477. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
  478. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  479. A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
  480. // Add default Japanese ranges
  481. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
  482. // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
  483. ImVector<ImWchar> ranges;
  484. ImFontAtlas::GlyphRangesBuilder builder;
  485. builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
  486. builder.AddChar(0x7262); // Add a specific character
  487. builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
  488. builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
  489. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
  490. All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax.
  491. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
  492. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
  493. Text input: it is up to your application to pass the right character code to io.AddInputCharacter(). The applications in examples/ are doing that.
  494. For languages using IME, on Windows you can copy the Hwnd of your application to io.ImeWindowHandle.
  495. The default implementation of io.ImeSetInputScreenPosFn() on Windows will set your IME position correctly.
  496. Q: How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables)
  497. A: Create your own context 'ctx = CreateContext()' + 'SetCurrentContext(ctx)' and your own font atlas 'ctx->GetIO().Fonts = new ImFontAtlas()'
  498. so you don't rely on the default globals.
  499. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  500. A: - You can create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag,
  501. push a ImGuiCol_WindowBg with zero alpha, then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
  502. - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows.
  503. - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData.
  504. Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
  505. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
  506. Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
  507. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  508. A: You are probably mishandling the clipping rectangles in your render function.
  509. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
  510. - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
  511. this is also useful to set yourself in the context of another window (to get/set other settings)
  512. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
  513. - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
  514. of a deep nested inner loop in your code.
  515. - tip: you can call Render() multiple times (e.g for VR renders).
  516. - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
  517. */
  518. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  519. #define _CRT_SECURE_NO_WARNINGS
  520. #endif
  521. #include "imgui.h"
  522. #define IMGUI_DEFINE_MATH_OPERATORS
  523. #include "imgui_internal.h"
  524. #include <ctype.h> // toupper, isprint
  525. #include <stdlib.h> // NULL, malloc, free, qsort, atoi
  526. #include <stdio.h> // vsnprintf, sscanf, printf
  527. #include <limits.h> // INT_MIN, INT_MAX
  528. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  529. #include <stddef.h> // intptr_t
  530. #else
  531. #include <stdint.h> // intptr_t
  532. #endif
  533. #ifdef _MSC_VER
  534. #pragma warning (disable: 4127) // condition expression is constant
  535. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  536. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  537. #endif
  538. // Clang warnings with -Weverything
  539. #ifdef __clang__
  540. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
  541. #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
  542. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
  543. #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.
  544. #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.
  545. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
  546. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
  547. #pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
  548. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' //
  549. #elif defined(__GNUC__)
  550. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  551. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  552. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  553. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  554. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  555. #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
  556. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  557. #endif
  558. //-------------------------------------------------------------------------
  559. // Forward Declarations
  560. //-------------------------------------------------------------------------
  561. static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
  562. static ImFont* GetDefaultFont();
  563. static void SetCurrentWindow(ImGuiWindow* window);
  564. static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x);
  565. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
  566. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
  567. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
  568. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
  569. static ImGuiWindow* FindHoveredWindow(ImVec2 pos);
  570. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
  571. static void CheckStacksSize(ImGuiWindow* window, bool write);
  572. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
  573. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_render_list, ImDrawList* draw_list);
  574. static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window);
  575. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
  576. static ImGuiWindowSettings* AddWindowSettings(const char* name);
  577. static void LoadIniSettingsFromDisk(const char* ini_filename);
  578. static void LoadIniSettingsFromMemory(const char* buf);
  579. static void SaveIniSettingsToDisk(const char* ini_filename);
  580. static void SaveIniSettingsToMemory(ImVector<char>& out_buf);
  581. static void MarkIniSettingsDirty(ImGuiWindow* window);
  582. static ImRect GetViewportRect();
  583. static void ClosePopupToLevel(int remaining);
  584. static ImGuiWindow* GetFrontMostModalRootWindow();
  585. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data);
  586. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
  587. 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);
  588. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
  589. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
  590. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
  591. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
  592. namespace ImGui
  593. {
  594. static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
  595. static void FocusFrontMostActiveWindow(ImGuiWindow* ignore_window);
  596. }
  597. //-----------------------------------------------------------------------------
  598. // Platform dependent default implementations
  599. //-----------------------------------------------------------------------------
  600. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  601. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  602. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
  603. //-----------------------------------------------------------------------------
  604. // Context
  605. //-----------------------------------------------------------------------------
  606. // Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL.
  607. // CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
  608. // If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file.
  609. // ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can:
  610. // - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  611. // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
  612. #ifndef GImGui
  613. ImGuiContext* GImGui = NULL;
  614. #endif
  615. // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
  616. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
  617. // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
  618. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
  619. static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); }
  620. static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); }
  621. #else
  622. static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; }
  623. static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); }
  624. #endif
  625. static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
  626. static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
  627. static void* GImAllocatorUserData = NULL;
  628. static size_t GImAllocatorActiveAllocationsCount = 0;
  629. //-----------------------------------------------------------------------------
  630. // User facing structures
  631. //-----------------------------------------------------------------------------
  632. ImGuiStyle::ImGuiStyle()
  633. {
  634. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  635. WindowPadding = ImVec2(8,8); // Padding within a window
  636. WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
  637. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  638. WindowMinSize = ImVec2(32,32); // Minimum window size
  639. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  640. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  641. ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  642. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
  643. PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  644. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  645. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  646. FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
  647. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  648. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  649. 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!
  650. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  651. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
  652. ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  653. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  654. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  655. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  656. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  657. DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
  658. 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.
  659. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
  660. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
  661. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
  662. CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
  663. ImGui::StyleColorsClassic(this);
  664. }
  665. // To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
  666. // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
  667. void ImGuiStyle::ScaleAllSizes(float scale_factor)
  668. {
  669. WindowPadding = ImFloor(WindowPadding * scale_factor);
  670. WindowRounding = ImFloor(WindowRounding * scale_factor);
  671. WindowMinSize = ImFloor(WindowMinSize * scale_factor);
  672. ChildRounding = ImFloor(ChildRounding * scale_factor);
  673. PopupRounding = ImFloor(PopupRounding * scale_factor);
  674. FramePadding = ImFloor(FramePadding * scale_factor);
  675. FrameRounding = ImFloor(FrameRounding * scale_factor);
  676. ItemSpacing = ImFloor(ItemSpacing * scale_factor);
  677. ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
  678. TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
  679. IndentSpacing = ImFloor(IndentSpacing * scale_factor);
  680. ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
  681. ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
  682. ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
  683. GrabMinSize = ImFloor(GrabMinSize * scale_factor);
  684. GrabRounding = ImFloor(GrabRounding * scale_factor);
  685. DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
  686. DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
  687. MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
  688. }
  689. ImGuiIO::ImGuiIO()
  690. {
  691. // Most fields are initialized with zero
  692. memset(this, 0, sizeof(*this));
  693. // Settings
  694. DisplaySize = ImVec2(-1.0f, -1.0f);
  695. DeltaTime = 1.0f/60.0f;
  696. IniSavingRate = 5.0f;
  697. IniFilename = "imgui.ini";
  698. LogFilename = "imgui_log.txt";
  699. MouseDoubleClickTime = 0.30f;
  700. MouseDoubleClickMaxDist = 6.0f;
  701. for (int i = 0; i < ImGuiKey_COUNT; i++)
  702. KeyMap[i] = -1;
  703. KeyRepeatDelay = 0.250f;
  704. KeyRepeatRate = 0.050f;
  705. UserData = NULL;
  706. Fonts = NULL;
  707. FontGlobalScale = 1.0f;
  708. FontDefault = NULL;
  709. FontAllowUserScaling = false;
  710. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  711. DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f);
  712. // Advanced/subtle behaviors
  713. #ifdef __APPLE__
  714. OptMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
  715. #else
  716. OptMacOSXBehaviors = false;
  717. #endif
  718. OptCursorBlink = true;
  719. // Settings (User Functions)
  720. RenderDrawListsFn = NULL;
  721. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  722. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  723. ClipboardUserData = NULL;
  724. ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
  725. ImeWindowHandle = NULL;
  726. // Input (NB: we already have memset zero the entire structure)
  727. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  728. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  729. MouseDragThreshold = 6.0f;
  730. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  731. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  732. }
  733. // Pass in translated ASCII characters for text input.
  734. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  735. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  736. void ImGuiIO::AddInputCharacter(ImWchar c)
  737. {
  738. const int n = ImStrlenW(InputCharacters);
  739. if (n + 1 < IM_ARRAYSIZE(InputCharacters))
  740. {
  741. InputCharacters[n] = c;
  742. InputCharacters[n+1] = '\0';
  743. }
  744. }
  745. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  746. {
  747. // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
  748. const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
  749. ImWchar wchars[wchars_buf_len];
  750. ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
  751. for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
  752. AddInputCharacter(wchars[i]);
  753. }
  754. //-----------------------------------------------------------------------------
  755. // HELPERS
  756. //-----------------------------------------------------------------------------
  757. #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
  758. #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
  759. // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
  760. #ifdef _WIN32
  761. #define IM_NEWLINE "\r\n"
  762. #else
  763. #define IM_NEWLINE "\n"
  764. #endif
  765. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  766. {
  767. ImVec2 ap = p - a;
  768. ImVec2 ab_dir = b - a;
  769. float ab_len = sqrtf(ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y);
  770. ab_dir *= 1.0f / ab_len;
  771. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  772. if (dot < 0.0f)
  773. return a;
  774. if (dot > ab_len)
  775. return b;
  776. return a + ab_dir * dot;
  777. }
  778. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  779. {
  780. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  781. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  782. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  783. return ((b1 == b2) && (b2 == b3));
  784. }
  785. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  786. {
  787. ImVec2 v0 = b - a;
  788. ImVec2 v1 = c - a;
  789. ImVec2 v2 = p - a;
  790. const float denom = v0.x * v1.y - v1.x * v0.y;
  791. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  792. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  793. out_u = 1.0f - out_v - out_w;
  794. }
  795. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  796. {
  797. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  798. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  799. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  800. float dist2_ab = ImLengthSqr(p - proj_ab);
  801. float dist2_bc = ImLengthSqr(p - proj_bc);
  802. float dist2_ca = ImLengthSqr(p - proj_ca);
  803. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  804. if (m == dist2_ab)
  805. return proj_ab;
  806. if (m == dist2_bc)
  807. return proj_bc;
  808. return proj_ca;
  809. }
  810. int ImStricmp(const char* str1, const char* str2)
  811. {
  812. int d;
  813. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  814. return d;
  815. }
  816. int ImStrnicmp(const char* str1, const char* str2, size_t count)
  817. {
  818. int d = 0;
  819. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  820. return d;
  821. }
  822. void ImStrncpy(char* dst, const char* src, size_t count)
  823. {
  824. if (count < 1) return;
  825. strncpy(dst, src, count);
  826. dst[count-1] = 0;
  827. }
  828. char* ImStrdup(const char *str)
  829. {
  830. size_t len = strlen(str) + 1;
  831. void* buf = ImGui::MemAlloc(len);
  832. return (char*)memcpy(buf, (const void*)str, len);
  833. }
  834. char* ImStrchrRange(const char* str, const char* str_end, char c)
  835. {
  836. for ( ; str < str_end; str++)
  837. if (*str == c)
  838. return (char*)str;
  839. return NULL;
  840. }
  841. int ImStrlenW(const ImWchar* str)
  842. {
  843. int n = 0;
  844. while (*str++) n++;
  845. return n;
  846. }
  847. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  848. {
  849. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  850. buf_mid_line--;
  851. return buf_mid_line;
  852. }
  853. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  854. {
  855. if (!needle_end)
  856. needle_end = needle + strlen(needle);
  857. const char un0 = (char)toupper(*needle);
  858. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  859. {
  860. if (toupper(*haystack) == un0)
  861. {
  862. const char* b = needle + 1;
  863. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  864. if (toupper(*a) != toupper(*b))
  865. break;
  866. if (b == needle_end)
  867. return haystack;
  868. }
  869. haystack++;
  870. }
  871. return NULL;
  872. }
  873. static const char* ImAtoi(const char* src, int* output)
  874. {
  875. int negative = 0;
  876. if (*src == '-') { negative = 1; src++; }
  877. if (*src == '+') { src++; }
  878. int v = 0;
  879. while (*src >= '0' && *src <= '9')
  880. v = (v * 10) + (*src++ - '0');
  881. *output = negative ? -v : v;
  882. return src;
  883. }
  884. // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  885. // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
  886. // B) When buf==NULL vsnprintf() will return the output size.
  887. #ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
  888. int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
  889. {
  890. va_list args;
  891. va_start(args, fmt);
  892. int w = vsnprintf(buf, buf_size, fmt, args);
  893. va_end(args);
  894. if (buf == NULL)
  895. return w;
  896. if (w == -1 || w >= (int)buf_size)
  897. w = (int)buf_size - 1;
  898. buf[w] = 0;
  899. return w;
  900. }
  901. int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
  902. {
  903. int w = vsnprintf(buf, buf_size, fmt, args);
  904. if (buf == NULL)
  905. return w;
  906. if (w == -1 || w >= (int)buf_size)
  907. w = (int)buf_size - 1;
  908. buf[w] = 0;
  909. return w;
  910. }
  911. #endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
  912. // Pass data_size==0 for zero-terminated strings
  913. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  914. ImU32 ImHash(const void* data, int data_size, ImU32 seed)
  915. {
  916. static ImU32 crc32_lut[256] = { 0 };
  917. if (!crc32_lut[1])
  918. {
  919. const ImU32 polynomial = 0xEDB88320;
  920. for (ImU32 i = 0; i < 256; i++)
  921. {
  922. ImU32 crc = i;
  923. for (ImU32 j = 0; j < 8; j++)
  924. crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
  925. crc32_lut[i] = crc;
  926. }
  927. }
  928. seed = ~seed;
  929. ImU32 crc = seed;
  930. const unsigned char* current = (const unsigned char*)data;
  931. if (data_size > 0)
  932. {
  933. // Known size
  934. while (data_size--)
  935. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
  936. }
  937. else
  938. {
  939. // Zero-terminated string
  940. while (unsigned char c = *current++)
  941. {
  942. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  943. // Because this syntax is rarely used we are optimizing for the common case.
  944. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  945. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
  946. if (c == '#' && current[0] == '#' && current[1] == '#')
  947. crc = seed;
  948. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  949. }
  950. }
  951. return ~crc;
  952. }
  953. //-----------------------------------------------------------------------------
  954. // ImText* helpers
  955. //-----------------------------------------------------------------------------
  956. // Convert UTF-8 to 32-bits character, process single character input.
  957. // Based on stb_from_utf8() from github.com/nothings/stb/
  958. // We handle UTF-8 decoding error by skipping forward.
  959. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  960. {
  961. unsigned int c = (unsigned int)-1;
  962. const unsigned char* str = (const unsigned char*)in_text;
  963. if (!(*str & 0x80))
  964. {
  965. c = (unsigned int)(*str++);
  966. *out_char = c;
  967. return 1;
  968. }
  969. if ((*str & 0xe0) == 0xc0)
  970. {
  971. *out_char = 0xFFFD; // will be invalid but not end of string
  972. if (in_text_end && in_text_end - (const char*)str < 2) return 1;
  973. if (*str < 0xc2) return 2;
  974. c = (unsigned int)((*str++ & 0x1f) << 6);
  975. if ((*str & 0xc0) != 0x80) return 2;
  976. c += (*str++ & 0x3f);
  977. *out_char = c;
  978. return 2;
  979. }
  980. if ((*str & 0xf0) == 0xe0)
  981. {
  982. *out_char = 0xFFFD; // will be invalid but not end of string
  983. if (in_text_end && in_text_end - (const char*)str < 3) return 1;
  984. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
  985. if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
  986. c = (unsigned int)((*str++ & 0x0f) << 12);
  987. if ((*str & 0xc0) != 0x80) return 3;
  988. c += (unsigned int)((*str++ & 0x3f) << 6);
  989. if ((*str & 0xc0) != 0x80) return 3;
  990. c += (*str++ & 0x3f);
  991. *out_char = c;
  992. return 3;
  993. }
  994. if ((*str & 0xf8) == 0xf0)
  995. {
  996. *out_char = 0xFFFD; // will be invalid but not end of string
  997. if (in_text_end && in_text_end - (const char*)str < 4) return 1;
  998. if (*str > 0xf4) return 4;
  999. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
  1000. if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
  1001. c = (unsigned int)((*str++ & 0x07) << 18);
  1002. if ((*str & 0xc0) != 0x80) return 4;
  1003. c += (unsigned int)((*str++ & 0x3f) << 12);
  1004. if ((*str & 0xc0) != 0x80) return 4;
  1005. c += (unsigned int)((*str++ & 0x3f) << 6);
  1006. if ((*str & 0xc0) != 0x80) return 4;
  1007. c += (*str++ & 0x3f);
  1008. // utf-8 encodings of values used in surrogate pairs are invalid
  1009. if ((c & 0xFFFFF800) == 0xD800) return 4;
  1010. *out_char = c;
  1011. return 4;
  1012. }
  1013. *out_char = 0;
  1014. return 0;
  1015. }
  1016. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1017. {
  1018. ImWchar* buf_out = buf;
  1019. ImWchar* buf_end = buf + buf_size;
  1020. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1021. {
  1022. unsigned int c;
  1023. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1024. if (c == 0)
  1025. break;
  1026. if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
  1027. *buf_out++ = (ImWchar)c;
  1028. }
  1029. *buf_out = 0;
  1030. if (in_text_remaining)
  1031. *in_text_remaining = in_text;
  1032. return (int)(buf_out - buf);
  1033. }
  1034. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1035. {
  1036. int char_count = 0;
  1037. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1038. {
  1039. unsigned int c;
  1040. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1041. if (c == 0)
  1042. break;
  1043. if (c < 0x10000)
  1044. char_count++;
  1045. }
  1046. return char_count;
  1047. }
  1048. // Based on stb_to_utf8() from github.com/nothings/stb/
  1049. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  1050. {
  1051. if (c < 0x80)
  1052. {
  1053. buf[0] = (char)c;
  1054. return 1;
  1055. }
  1056. if (c < 0x800)
  1057. {
  1058. if (buf_size < 2) return 0;
  1059. buf[0] = (char)(0xc0 + (c >> 6));
  1060. buf[1] = (char)(0x80 + (c & 0x3f));
  1061. return 2;
  1062. }
  1063. if (c >= 0xdc00 && c < 0xe000)
  1064. {
  1065. return 0;
  1066. }
  1067. if (c >= 0xd800 && c < 0xdc00)
  1068. {
  1069. if (buf_size < 4) return 0;
  1070. buf[0] = (char)(0xf0 + (c >> 18));
  1071. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1072. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1073. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1074. return 4;
  1075. }
  1076. //else if (c < 0x10000)
  1077. {
  1078. if (buf_size < 3) return 0;
  1079. buf[0] = (char)(0xe0 + (c >> 12));
  1080. buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
  1081. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1082. return 3;
  1083. }
  1084. }
  1085. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1086. {
  1087. if (c < 0x80) return 1;
  1088. if (c < 0x800) return 2;
  1089. if (c >= 0xdc00 && c < 0xe000) return 0;
  1090. if (c >= 0xd800 && c < 0xdc00) return 4;
  1091. return 3;
  1092. }
  1093. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1094. {
  1095. char* buf_out = buf;
  1096. const char* buf_end = buf + buf_size;
  1097. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1098. {
  1099. unsigned int c = (unsigned int)(*in_text++);
  1100. if (c < 0x80)
  1101. *buf_out++ = (char)c;
  1102. else
  1103. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
  1104. }
  1105. *buf_out = 0;
  1106. return (int)(buf_out - buf);
  1107. }
  1108. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1109. {
  1110. int bytes_count = 0;
  1111. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1112. {
  1113. unsigned int c = (unsigned int)(*in_text++);
  1114. if (c < 0x80)
  1115. bytes_count++;
  1116. else
  1117. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1118. }
  1119. return bytes_count;
  1120. }
  1121. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1122. {
  1123. float s = 1.0f/255.0f;
  1124. return ImVec4(
  1125. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1126. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1127. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1128. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1129. }
  1130. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1131. {
  1132. ImU32 out;
  1133. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1134. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1135. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1136. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1137. return out;
  1138. }
  1139. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  1140. {
  1141. ImGuiStyle& style = GImGui->Style;
  1142. ImVec4 c = style.Colors[idx];
  1143. c.w *= style.Alpha * alpha_mul;
  1144. return ColorConvertFloat4ToU32(c);
  1145. }
  1146. ImU32 ImGui::GetColorU32(const ImVec4& col)
  1147. {
  1148. ImGuiStyle& style = GImGui->Style;
  1149. ImVec4 c = col;
  1150. c.w *= style.Alpha;
  1151. return ColorConvertFloat4ToU32(c);
  1152. }
  1153. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  1154. {
  1155. ImGuiStyle& style = GImGui->Style;
  1156. return style.Colors[idx];
  1157. }
  1158. ImU32 ImGui::GetColorU32(ImU32 col)
  1159. {
  1160. float style_alpha = GImGui->Style.Alpha;
  1161. if (style_alpha >= 1.0f)
  1162. return col;
  1163. int a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  1164. a = (int)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  1165. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  1166. }
  1167. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1168. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1169. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1170. {
  1171. float K = 0.f;
  1172. if (g < b)
  1173. {
  1174. ImSwap(g, b);
  1175. K = -1.f;
  1176. }
  1177. if (r < g)
  1178. {
  1179. ImSwap(r, g);
  1180. K = -2.f / 6.f - K;
  1181. }
  1182. const float chroma = r - (g < b ? g : b);
  1183. out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f));
  1184. out_s = chroma / (r + 1e-20f);
  1185. out_v = r;
  1186. }
  1187. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1188. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1189. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1190. {
  1191. if (s == 0.0f)
  1192. {
  1193. // gray
  1194. out_r = out_g = out_b = v;
  1195. return;
  1196. }
  1197. h = fmodf(h, 1.0f) / (60.0f/360.0f);
  1198. int i = (int)h;
  1199. float f = h - (float)i;
  1200. float p = v * (1.0f - s);
  1201. float q = v * (1.0f - s * f);
  1202. float t = v * (1.0f - s * (1.0f - f));
  1203. switch (i)
  1204. {
  1205. case 0: out_r = v; out_g = t; out_b = p; break;
  1206. case 1: out_r = q; out_g = v; out_b = p; break;
  1207. case 2: out_r = p; out_g = v; out_b = t; break;
  1208. case 3: out_r = p; out_g = q; out_b = v; break;
  1209. case 4: out_r = t; out_g = p; out_b = v; break;
  1210. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1211. }
  1212. }
  1213. FILE* ImFileOpen(const char* filename, const char* mode)
  1214. {
  1215. #if defined(_WIN32) && !defined(__CYGWIN__)
  1216. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
  1217. const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
  1218. const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
  1219. ImVector<ImWchar> buf;
  1220. buf.resize(filename_wsize + mode_wsize);
  1221. ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
  1222. ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
  1223. return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
  1224. #else
  1225. return fopen(filename, mode);
  1226. #endif
  1227. }
  1228. // Load file content into memory
  1229. // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
  1230. void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
  1231. {
  1232. IM_ASSERT(filename && file_open_mode);
  1233. if (out_file_size)
  1234. *out_file_size = 0;
  1235. FILE* f;
  1236. if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
  1237. return NULL;
  1238. long file_size_signed;
  1239. if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
  1240. {
  1241. fclose(f);
  1242. return NULL;
  1243. }
  1244. int file_size = (int)file_size_signed;
  1245. void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
  1246. if (file_data == NULL)
  1247. {
  1248. fclose(f);
  1249. return NULL;
  1250. }
  1251. if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size)
  1252. {
  1253. fclose(f);
  1254. ImGui::MemFree(file_data);
  1255. return NULL;
  1256. }
  1257. if (padding_bytes > 0)
  1258. memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
  1259. fclose(f);
  1260. if (out_file_size)
  1261. *out_file_size = file_size;
  1262. return file_data;
  1263. }
  1264. //-----------------------------------------------------------------------------
  1265. // ImGuiStorage
  1266. // Helper: Key->value storage
  1267. //-----------------------------------------------------------------------------
  1268. // std::lower_bound but without the bullshit
  1269. static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
  1270. {
  1271. ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
  1272. ImVector<ImGuiStorage::Pair>::iterator last = data.end();
  1273. size_t count = (size_t)(last - first);
  1274. while (count > 0)
  1275. {
  1276. size_t count2 = count >> 1;
  1277. ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
  1278. if (mid->key < key)
  1279. {
  1280. first = ++mid;
  1281. count -= count2 + 1;
  1282. }
  1283. else
  1284. {
  1285. count = count2;
  1286. }
  1287. }
  1288. return first;
  1289. }
  1290. // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
  1291. void ImGuiStorage::BuildSortByKey()
  1292. {
  1293. struct StaticFunc
  1294. {
  1295. static int PairCompareByID(const void* lhs, const void* rhs)
  1296. {
  1297. // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
  1298. if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
  1299. if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
  1300. return 0;
  1301. }
  1302. };
  1303. if (Data.Size > 1)
  1304. qsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
  1305. }
  1306. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1307. {
  1308. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1309. if (it == Data.end() || it->key != key)
  1310. return default_val;
  1311. return it->val_i;
  1312. }
  1313. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1314. {
  1315. return GetInt(key, default_val ? 1 : 0) != 0;
  1316. }
  1317. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1318. {
  1319. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1320. if (it == Data.end() || it->key != key)
  1321. return default_val;
  1322. return it->val_f;
  1323. }
  1324. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1325. {
  1326. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1327. if (it == Data.end() || it->key != key)
  1328. return NULL;
  1329. return it->val_p;
  1330. }
  1331. // 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.
  1332. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1333. {
  1334. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1335. if (it == Data.end() || it->key != key)
  1336. it = Data.insert(it, Pair(key, default_val));
  1337. return &it->val_i;
  1338. }
  1339. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1340. {
  1341. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1342. }
  1343. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1344. {
  1345. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1346. if (it == Data.end() || it->key != key)
  1347. it = Data.insert(it, Pair(key, default_val));
  1348. return &it->val_f;
  1349. }
  1350. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1351. {
  1352. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1353. if (it == Data.end() || it->key != key)
  1354. it = Data.insert(it, Pair(key, default_val));
  1355. return &it->val_p;
  1356. }
  1357. // 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)
  1358. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1359. {
  1360. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1361. if (it == Data.end() || it->key != key)
  1362. {
  1363. Data.insert(it, Pair(key, val));
  1364. return;
  1365. }
  1366. it->val_i = val;
  1367. }
  1368. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1369. {
  1370. SetInt(key, val ? 1 : 0);
  1371. }
  1372. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1373. {
  1374. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1375. if (it == Data.end() || it->key != key)
  1376. {
  1377. Data.insert(it, Pair(key, val));
  1378. return;
  1379. }
  1380. it->val_f = val;
  1381. }
  1382. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1383. {
  1384. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1385. if (it == Data.end() || it->key != key)
  1386. {
  1387. Data.insert(it, Pair(key, val));
  1388. return;
  1389. }
  1390. it->val_p = val;
  1391. }
  1392. void ImGuiStorage::SetAllInt(int v)
  1393. {
  1394. for (int i = 0; i < Data.Size; i++)
  1395. Data[i].val_i = v;
  1396. }
  1397. //-----------------------------------------------------------------------------
  1398. // ImGuiTextFilter
  1399. //-----------------------------------------------------------------------------
  1400. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1401. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1402. {
  1403. if (default_filter)
  1404. {
  1405. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1406. Build();
  1407. }
  1408. else
  1409. {
  1410. InputBuf[0] = 0;
  1411. CountGrep = 0;
  1412. }
  1413. }
  1414. bool ImGuiTextFilter::Draw(const char* label, float width)
  1415. {
  1416. if (width != 0.0f)
  1417. ImGui::PushItemWidth(width);
  1418. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1419. if (width != 0.0f)
  1420. ImGui::PopItemWidth();
  1421. if (value_changed)
  1422. Build();
  1423. return value_changed;
  1424. }
  1425. void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
  1426. {
  1427. out.resize(0);
  1428. const char* wb = b;
  1429. const char* we = wb;
  1430. while (we < e)
  1431. {
  1432. if (*we == separator)
  1433. {
  1434. out.push_back(TextRange(wb, we));
  1435. wb = we + 1;
  1436. }
  1437. we++;
  1438. }
  1439. if (wb != we)
  1440. out.push_back(TextRange(wb, we));
  1441. }
  1442. void ImGuiTextFilter::Build()
  1443. {
  1444. Filters.resize(0);
  1445. TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
  1446. input_range.split(',', Filters);
  1447. CountGrep = 0;
  1448. for (int i = 0; i != Filters.Size; i++)
  1449. {
  1450. Filters[i].trim_blanks();
  1451. if (Filters[i].empty())
  1452. continue;
  1453. if (Filters[i].front() != '-')
  1454. CountGrep += 1;
  1455. }
  1456. }
  1457. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1458. {
  1459. if (Filters.empty())
  1460. return true;
  1461. if (text == NULL)
  1462. text = "";
  1463. for (int i = 0; i != Filters.Size; i++)
  1464. {
  1465. const TextRange& f = Filters[i];
  1466. if (f.empty())
  1467. continue;
  1468. if (f.front() == '-')
  1469. {
  1470. // Subtract
  1471. if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
  1472. return false;
  1473. }
  1474. else
  1475. {
  1476. // Grep
  1477. if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
  1478. return true;
  1479. }
  1480. }
  1481. // Implicit * grep
  1482. if (CountGrep == 0)
  1483. return true;
  1484. return false;
  1485. }
  1486. //-----------------------------------------------------------------------------
  1487. // ImGuiTextBuffer
  1488. //-----------------------------------------------------------------------------
  1489. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1490. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1491. #ifndef va_copy
  1492. #define va_copy(dest, src) (dest = src)
  1493. #endif
  1494. // Helper: Text buffer for logging/accumulating text
  1495. void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
  1496. {
  1497. va_list args_copy;
  1498. va_copy(args_copy, args);
  1499. int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1500. if (len <= 0)
  1501. return;
  1502. const int write_off = Buf.Size;
  1503. const int needed_sz = write_off + len;
  1504. if (write_off + len >= Buf.Capacity)
  1505. {
  1506. int double_capacity = Buf.Capacity * 2;
  1507. Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
  1508. }
  1509. Buf.resize(needed_sz);
  1510. ImFormatStringV(&Buf[write_off - 1], len + 1, fmt, args_copy);
  1511. }
  1512. void ImGuiTextBuffer::appendf(const char* fmt, ...)
  1513. {
  1514. va_list args;
  1515. va_start(args, fmt);
  1516. appendfv(fmt, args);
  1517. va_end(args);
  1518. }
  1519. //-----------------------------------------------------------------------------
  1520. // ImGuiSimpleColumns (internal use only)
  1521. //-----------------------------------------------------------------------------
  1522. ImGuiMenuColumns::ImGuiMenuColumns()
  1523. {
  1524. Count = 0;
  1525. Spacing = Width = NextWidth = 0.0f;
  1526. memset(Pos, 0, sizeof(Pos));
  1527. memset(NextWidths, 0, sizeof(NextWidths));
  1528. }
  1529. void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
  1530. {
  1531. IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
  1532. Count = count;
  1533. Width = NextWidth = 0.0f;
  1534. Spacing = spacing;
  1535. if (clear) memset(NextWidths, 0, sizeof(NextWidths));
  1536. for (int i = 0; i < Count; i++)
  1537. {
  1538. if (i > 0 && NextWidths[i] > 0.0f)
  1539. Width += Spacing;
  1540. Pos[i] = (float)(int)Width;
  1541. Width += NextWidths[i];
  1542. NextWidths[i] = 0.0f;
  1543. }
  1544. }
  1545. float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
  1546. {
  1547. NextWidth = 0.0f;
  1548. NextWidths[0] = ImMax(NextWidths[0], w0);
  1549. NextWidths[1] = ImMax(NextWidths[1], w1);
  1550. NextWidths[2] = ImMax(NextWidths[2], w2);
  1551. for (int i = 0; i < 3; i++)
  1552. NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
  1553. return ImMax(Width, NextWidth);
  1554. }
  1555. float ImGuiMenuColumns::CalcExtraSpace(float avail_w)
  1556. {
  1557. return ImMax(0.0f, avail_w - Width);
  1558. }
  1559. //-----------------------------------------------------------------------------
  1560. // ImGuiListClipper
  1561. //-----------------------------------------------------------------------------
  1562. static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
  1563. {
  1564. // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor.
  1565. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions?
  1566. ImGui::SetCursorPosY(pos_y);
  1567. ImGuiWindow* window = ImGui::GetCurrentWindow();
  1568. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage.
  1569. window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
  1570. if (window->DC.ColumnsSet)
  1571. window->DC.ColumnsSet->CellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  1572. }
  1573. // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
  1574. // Use case B: Begin() called from constructor with items_height>0
  1575. // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
  1576. void ImGuiListClipper::Begin(int count, float items_height)
  1577. {
  1578. StartPosY = ImGui::GetCursorPosY();
  1579. ItemsHeight = items_height;
  1580. ItemsCount = count;
  1581. StepNo = 0;
  1582. DisplayEnd = DisplayStart = -1;
  1583. if (ItemsHeight > 0.0f)
  1584. {
  1585. ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
  1586. if (DisplayStart > 0)
  1587. SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
  1588. StepNo = 2;
  1589. }
  1590. }
  1591. void ImGuiListClipper::End()
  1592. {
  1593. if (ItemsCount < 0)
  1594. return;
  1595. // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
  1596. if (ItemsCount < INT_MAX)
  1597. SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
  1598. ItemsCount = -1;
  1599. StepNo = 3;
  1600. }
  1601. bool ImGuiListClipper::Step()
  1602. {
  1603. if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
  1604. {
  1605. ItemsCount = -1;
  1606. return false;
  1607. }
  1608. if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
  1609. {
  1610. DisplayStart = 0;
  1611. DisplayEnd = 1;
  1612. StartPosY = ImGui::GetCursorPosY();
  1613. StepNo = 1;
  1614. return true;
  1615. }
  1616. if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
  1617. {
  1618. if (ItemsCount == 1) { ItemsCount = -1; return false; }
  1619. float items_height = ImGui::GetCursorPosY() - StartPosY;
  1620. IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
  1621. Begin(ItemsCount-1, items_height);
  1622. DisplayStart++;
  1623. DisplayEnd++;
  1624. StepNo = 3;
  1625. return true;
  1626. }
  1627. if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
  1628. {
  1629. IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
  1630. StepNo = 3;
  1631. return true;
  1632. }
  1633. if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
  1634. End();
  1635. return false;
  1636. }
  1637. //-----------------------------------------------------------------------------
  1638. // ImGuiWindow
  1639. //-----------------------------------------------------------------------------
  1640. ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
  1641. {
  1642. Name = ImStrdup(name);
  1643. ID = ImHash(name, 0);
  1644. IDStack.push_back(ID);
  1645. Flags = 0;
  1646. PosFloat = Pos = ImVec2(0.0f, 0.0f);
  1647. Size = SizeFull = ImVec2(0.0f, 0.0f);
  1648. SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  1649. WindowPadding = ImVec2(0.0f, 0.0f);
  1650. WindowRounding = 0.0f;
  1651. WindowBorderSize = 0.0f;
  1652. MoveId = GetID("#MOVE");
  1653. Scroll = ImVec2(0.0f, 0.0f);
  1654. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  1655. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  1656. ScrollbarX = ScrollbarY = false;
  1657. ScrollbarSizes = ImVec2(0.0f, 0.0f);
  1658. Active = WasActive = false;
  1659. WriteAccessed = false;
  1660. Collapsed = false;
  1661. SkipItems = false;
  1662. Appearing = false;
  1663. CloseButton = false;
  1664. BeginOrderWithinParent = -1;
  1665. BeginOrderWithinContext = -1;
  1666. BeginCount = 0;
  1667. PopupId = 0;
  1668. AutoFitFramesX = AutoFitFramesY = -1;
  1669. AutoFitOnlyGrows = false;
  1670. AutoFitChildAxises = 0x00;
  1671. AutoPosLastDirection = ImGuiDir_None;
  1672. HiddenFrames = 0;
  1673. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  1674. SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
  1675. LastFrameActive = -1;
  1676. ItemWidthDefault = 0.0f;
  1677. FontWindowScale = 1.0f;
  1678. DrawList = IM_NEW(ImDrawList)(&context->DrawListSharedData);
  1679. DrawList->_OwnerName = Name;
  1680. ParentWindow = NULL;
  1681. RootWindow = NULL;
  1682. RootNonPopupWindow = NULL;
  1683. FocusIdxAllCounter = FocusIdxTabCounter = -1;
  1684. FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
  1685. FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
  1686. }
  1687. ImGuiWindow::~ImGuiWindow()
  1688. {
  1689. IM_DELETE(DrawList);
  1690. IM_DELETE(Name);
  1691. for (int i = 0; i != ColumnsStorage.Size; i++)
  1692. ColumnsStorage[i].~ImGuiColumnsSet();
  1693. }
  1694. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  1695. {
  1696. ImGuiID seed = IDStack.back();
  1697. ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1698. ImGui::KeepAliveID(id);
  1699. return id;
  1700. }
  1701. ImGuiID ImGuiWindow::GetID(const void* ptr)
  1702. {
  1703. ImGuiID seed = IDStack.back();
  1704. ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
  1705. ImGui::KeepAliveID(id);
  1706. return id;
  1707. }
  1708. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  1709. {
  1710. ImGuiID seed = IDStack.back();
  1711. return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1712. }
  1713. // This is only used in rare/specific situations to manufacture an ID out of nowhere.
  1714. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
  1715. {
  1716. ImGuiID seed = IDStack.back();
  1717. const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
  1718. ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed);
  1719. ImGui::KeepAliveID(id);
  1720. return id;
  1721. }
  1722. //-----------------------------------------------------------------------------
  1723. // Internal API exposed in imgui_internal.h
  1724. //-----------------------------------------------------------------------------
  1725. static void SetCurrentWindow(ImGuiWindow* window)
  1726. {
  1727. ImGuiContext& g = *GImGui;
  1728. g.CurrentWindow = window;
  1729. if (window)
  1730. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  1731. }
  1732. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  1733. {
  1734. ImGuiContext& g = *GImGui;
  1735. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  1736. if (g.ActiveIdIsJustActivated)
  1737. g.ActiveIdTimer = 0.0f;
  1738. g.ActiveId = id;
  1739. g.ActiveIdAllowOverlap = false;
  1740. g.ActiveIdIsAlive |= (id != 0);
  1741. g.ActiveIdWindow = window;
  1742. }
  1743. void ImGui::ClearActiveID()
  1744. {
  1745. SetActiveID(0, NULL);
  1746. }
  1747. void ImGui::SetHoveredID(ImGuiID id)
  1748. {
  1749. ImGuiContext& g = *GImGui;
  1750. g.HoveredId = id;
  1751. g.HoveredIdAllowOverlap = false;
  1752. g.HoveredIdTimer = (id != 0 && g.HoveredIdPreviousFrame == id) ? (g.HoveredIdTimer + g.IO.DeltaTime) : 0.0f;
  1753. }
  1754. ImGuiID ImGui::GetHoveredID()
  1755. {
  1756. ImGuiContext& g = *GImGui;
  1757. return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
  1758. }
  1759. void ImGui::KeepAliveID(ImGuiID id)
  1760. {
  1761. ImGuiContext& g = *GImGui;
  1762. if (g.ActiveId == id)
  1763. g.ActiveIdIsAlive = true;
  1764. }
  1765. static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
  1766. {
  1767. // An active popup disable hovering on other windows (apart from its own children)
  1768. // FIXME-OPT: This could be cached/stored within the window.
  1769. ImGuiContext& g = *GImGui;
  1770. if (g.NavWindow)
  1771. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
  1772. if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
  1773. {
  1774. // For the purpose of those flags we differentiate "standard popup" from "modal popup"
  1775. // NB: The order of those two tests is important because Modal windows are also Popups.
  1776. if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
  1777. return false;
  1778. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  1779. return false;
  1780. }
  1781. return true;
  1782. }
  1783. // Advance cursor given item size for layout.
  1784. void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
  1785. {
  1786. ImGuiContext& g = *GImGui;
  1787. ImGuiWindow* window = g.CurrentWindow;
  1788. if (window->SkipItems)
  1789. return;
  1790. // Always align ourselves on pixel boundaries
  1791. const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
  1792. const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
  1793. //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
  1794. window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
  1795. 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));
  1796. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  1797. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
  1798. //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
  1799. window->DC.PrevLineHeight = line_height;
  1800. window->DC.PrevLineTextBaseOffset = text_base_offset;
  1801. window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
  1802. // Horizontal layout mode
  1803. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  1804. SameLine();
  1805. }
  1806. void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
  1807. {
  1808. ItemSize(bb.GetSize(), text_offset_y);
  1809. }
  1810. // Declare item bounding box for clipping and interaction.
  1811. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  1812. // declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
  1813. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id)
  1814. {
  1815. ImGuiContext& g = *GImGui;
  1816. ImGuiWindow* window = g.CurrentWindow;
  1817. const bool is_clipped = IsClippedEx(bb, id, false);
  1818. window->DC.LastItemId = id;
  1819. window->DC.LastItemRect = bb;
  1820. window->DC.LastItemStatusFlags = 0;
  1821. if (is_clipped)
  1822. return false;
  1823. //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
  1824. // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
  1825. if (IsMouseHoveringRect(bb.Min, bb.Max))
  1826. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
  1827. return true;
  1828. }
  1829. // This is roughly matching the behavior of internal-facing ItemHoverable()
  1830. // - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
  1831. // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
  1832. bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
  1833. {
  1834. ImGuiContext& g = *GImGui;
  1835. ImGuiWindow* window = g.CurrentWindow;
  1836. // Test for bounding box overlap, as updated as ItemAdd()
  1837. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  1838. return false;
  1839. IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
  1840. // Test if we are hovering the right window (our window could be behind another window)
  1841. // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
  1842. // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
  1843. //if (g.HoveredWindow != window)
  1844. // return false;
  1845. if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
  1846. return false;
  1847. // Test if another item is active (e.g. being dragged)
  1848. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  1849. if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
  1850. return false;
  1851. // Test if interactions on this window are blocked by an active popup or modal
  1852. if (!IsWindowContentHoverable(window, flags))
  1853. return false;
  1854. // Test if the item is disabled
  1855. if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
  1856. return false;
  1857. // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case.
  1858. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
  1859. return false;
  1860. return true;
  1861. }
  1862. // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
  1863. bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
  1864. {
  1865. ImGuiContext& g = *GImGui;
  1866. if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
  1867. return false;
  1868. ImGuiWindow* window = g.CurrentWindow;
  1869. if (g.HoveredWindow != window)
  1870. return false;
  1871. if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
  1872. return false;
  1873. if (!IsMouseHoveringRect(bb.Min, bb.Max))
  1874. return false;
  1875. if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_Default))
  1876. return false;
  1877. if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
  1878. return false;
  1879. SetHoveredID(id);
  1880. return true;
  1881. }
  1882. bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
  1883. {
  1884. ImGuiContext& g = *GImGui;
  1885. ImGuiWindow* window = g.CurrentWindow;
  1886. if (!bb.Overlaps(window->ClipRect))
  1887. if (id == 0 || id != g.ActiveId)
  1888. if (clip_even_when_logged || !g.LogEnabled)
  1889. return true;
  1890. return false;
  1891. }
  1892. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
  1893. {
  1894. ImGuiContext& g = *GImGui;
  1895. const bool allow_keyboard_focus = (window->DC.ItemFlags & (ImGuiItemFlags_AllowKeyboardFocus | ImGuiItemFlags_Disabled)) == ImGuiItemFlags_AllowKeyboardFocus;
  1896. window->FocusIdxAllCounter++;
  1897. if (allow_keyboard_focus)
  1898. window->FocusIdxTabCounter++;
  1899. // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
  1900. // Note that we can always TAB out of a widget that doesn't allow tabbing in.
  1901. if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
  1902. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
  1903. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
  1904. return true;
  1905. if (allow_keyboard_focus && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
  1906. return true;
  1907. return false;
  1908. }
  1909. void ImGui::FocusableItemUnregister(ImGuiWindow* window)
  1910. {
  1911. window->FocusIdxAllCounter--;
  1912. window->FocusIdxTabCounter--;
  1913. }
  1914. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
  1915. {
  1916. ImGuiContext& g = *GImGui;
  1917. ImVec2 content_max;
  1918. if (size.x < 0.0f || size.y < 0.0f)
  1919. content_max = g.CurrentWindow->Pos + GetContentRegionMax();
  1920. if (size.x <= 0.0f)
  1921. size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
  1922. if (size.y <= 0.0f)
  1923. size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
  1924. return size;
  1925. }
  1926. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  1927. {
  1928. if (wrap_pos_x < 0.0f)
  1929. return 0.0f;
  1930. ImGuiWindow* window = GetCurrentWindowRead();
  1931. if (wrap_pos_x == 0.0f)
  1932. wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
  1933. else if (wrap_pos_x > 0.0f)
  1934. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  1935. return ImMax(wrap_pos_x - pos.x, 1.0f);
  1936. }
  1937. //-----------------------------------------------------------------------------
  1938. void* ImGui::MemAlloc(size_t sz)
  1939. {
  1940. GImAllocatorActiveAllocationsCount++;
  1941. return GImAllocatorAllocFunc(sz, GImAllocatorUserData);
  1942. }
  1943. void ImGui::MemFree(void* ptr)
  1944. {
  1945. if (ptr) GImAllocatorActiveAllocationsCount--;
  1946. return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
  1947. }
  1948. const char* ImGui::GetClipboardText()
  1949. {
  1950. return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
  1951. }
  1952. void ImGui::SetClipboardText(const char* text)
  1953. {
  1954. if (GImGui->IO.SetClipboardTextFn)
  1955. GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
  1956. }
  1957. const char* ImGui::GetVersion()
  1958. {
  1959. return IMGUI_VERSION;
  1960. }
  1961. // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
  1962. // 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
  1963. ImGuiContext* ImGui::GetCurrentContext()
  1964. {
  1965. return GImGui;
  1966. }
  1967. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  1968. {
  1969. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  1970. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  1971. #else
  1972. GImGui = ctx;
  1973. #endif
  1974. }
  1975. void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data)
  1976. {
  1977. GImAllocatorAllocFunc = alloc_func;
  1978. GImAllocatorFreeFunc = free_func;
  1979. GImAllocatorUserData = user_data;
  1980. }
  1981. ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
  1982. {
  1983. ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
  1984. if (GImGui == NULL)
  1985. SetCurrentContext(ctx);
  1986. return ctx;
  1987. }
  1988. void ImGui::DestroyContext(ImGuiContext* ctx)
  1989. {
  1990. if (ctx == NULL)
  1991. ctx = GImGui;
  1992. Shutdown(ctx);
  1993. if (GImGui == ctx)
  1994. SetCurrentContext(NULL);
  1995. IM_DELETE(ctx);
  1996. }
  1997. ImGuiIO& ImGui::GetIO()
  1998. {
  1999. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2000. return GImGui->IO;
  2001. }
  2002. ImGuiStyle& ImGui::GetStyle()
  2003. {
  2004. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2005. return GImGui->Style;
  2006. }
  2007. // Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
  2008. ImDrawData* ImGui::GetDrawData()
  2009. {
  2010. return GImGui->DrawData.Valid ? &GImGui->DrawData : NULL;
  2011. }
  2012. float ImGui::GetTime()
  2013. {
  2014. return GImGui->Time;
  2015. }
  2016. int ImGui::GetFrameCount()
  2017. {
  2018. return GImGui->FrameCount;
  2019. }
  2020. ImDrawList* ImGui::GetOverlayDrawList()
  2021. {
  2022. return &GImGui->OverlayDrawList;
  2023. }
  2024. ImDrawListSharedData* ImGui::GetDrawListSharedData()
  2025. {
  2026. return &GImGui->DrawListSharedData;
  2027. }
  2028. void ImGui::NewFrame()
  2029. {
  2030. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2031. ImGuiContext& g = *GImGui;
  2032. // Check user data
  2033. // (We pass an error message in the assert expression as a trick to get it visible to programmers who are not using a debugger, as most assert handlers display their argument)
  2034. IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
  2035. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
  2036. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  2037. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  2038. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
  2039. IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)");
  2040. IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
  2041. for (int n = 0; n < ImGuiKey_COUNT; n++)
  2042. IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
  2043. // Initialize on first frame
  2044. if (!g.Initialized)
  2045. Initialize(&g);
  2046. g.Time += g.IO.DeltaTime;
  2047. g.FrameCount += 1;
  2048. g.TooltipOverrideCount = 0;
  2049. g.WindowsActiveCount = 0;
  2050. SetCurrentFont(GetDefaultFont());
  2051. IM_ASSERT(g.Font->IsLoaded());
  2052. g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
  2053. g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
  2054. g.OverlayDrawList.Clear();
  2055. g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
  2056. g.OverlayDrawList.PushClipRectFullScreen();
  2057. g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
  2058. // Mark rendering data as invalid to prevent user who may have a handle on it to use it
  2059. g.DrawData.Clear();
  2060. // Clear reference to active widget if the widget isn't alive anymore
  2061. if (!g.HoveredIdPreviousFrame)
  2062. g.HoveredIdTimer = 0.0f;
  2063. g.HoveredIdPreviousFrame = g.HoveredId;
  2064. g.HoveredId = 0;
  2065. g.HoveredIdAllowOverlap = false;
  2066. if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  2067. ClearActiveID();
  2068. if (g.ActiveId)
  2069. g.ActiveIdTimer += g.IO.DeltaTime;
  2070. g.ActiveIdPreviousFrame = g.ActiveId;
  2071. g.ActiveIdIsAlive = false;
  2072. g.ActiveIdIsJustActivated = false;
  2073. if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
  2074. g.ScalarAsInputTextId = 0;
  2075. // Elapse drag & drop payload
  2076. if (g.DragDropActive && g.DragDropPayload.DataFrameCount + 1 < g.FrameCount)
  2077. {
  2078. ClearDragDrop();
  2079. g.DragDropPayloadBufHeap.clear();
  2080. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  2081. }
  2082. g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
  2083. g.DragDropAcceptIdCurr = 0;
  2084. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  2085. // Update keyboard input state
  2086. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  2087. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  2088. 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;
  2089. // Update mouse input state
  2090. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX component, but in reality we test for -256000.0f) we cancel out movement in MouseDelta
  2091. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
  2092. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  2093. else
  2094. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  2095. g.IO.MousePosPrev = g.IO.MousePos;
  2096. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2097. {
  2098. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  2099. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  2100. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  2101. 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;
  2102. g.IO.MouseDoubleClicked[i] = false;
  2103. if (g.IO.MouseClicked[i])
  2104. {
  2105. if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
  2106. {
  2107. if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  2108. g.IO.MouseDoubleClicked[i] = true;
  2109. g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
  2110. }
  2111. else
  2112. {
  2113. g.IO.MouseClickedTime[i] = g.Time;
  2114. }
  2115. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  2116. g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
  2117. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  2118. }
  2119. else if (g.IO.MouseDown[i])
  2120. {
  2121. ImVec2 mouse_delta = g.IO.MousePos - g.IO.MouseClickedPos[i];
  2122. g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, mouse_delta.x < 0.0f ? -mouse_delta.x : mouse_delta.x);
  2123. g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, mouse_delta.y < 0.0f ? -mouse_delta.y : mouse_delta.y);
  2124. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(mouse_delta));
  2125. }
  2126. }
  2127. // Calculate frame-rate for the user, as a purely luxurious feature
  2128. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  2129. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  2130. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  2131. g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
  2132. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering).
  2133. if (g.MovingWindow && g.MovingWindow->MoveId == g.ActiveId)
  2134. {
  2135. KeepAliveID(g.ActiveId);
  2136. IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
  2137. if (g.IO.MouseDown[0])
  2138. {
  2139. // MovingWindow = window we clicked on, could be a child window. We track it to preserve Focus and so that ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
  2140. ImGuiWindow* actually_moving_window = g.MovingWindow->RootWindow;
  2141. ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
  2142. if (actually_moving_window->PosFloat.x != pos.x || actually_moving_window->PosFloat.y != pos.y)
  2143. {
  2144. MarkIniSettingsDirty(actually_moving_window);
  2145. actually_moving_window->PosFloat = pos;
  2146. }
  2147. FocusWindow(g.MovingWindow);
  2148. }
  2149. else
  2150. {
  2151. ClearActiveID();
  2152. g.MovingWindow = NULL;
  2153. }
  2154. }
  2155. else
  2156. {
  2157. // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
  2158. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
  2159. {
  2160. KeepAliveID(g.ActiveId);
  2161. if (!g.IO.MouseDown[0])
  2162. ClearActiveID();
  2163. }
  2164. g.MovingWindow = NULL;
  2165. }
  2166. // Delay saving settings so we don't spam disk too much
  2167. if (g.SettingsDirtyTimer > 0.0f)
  2168. {
  2169. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  2170. if (g.SettingsDirtyTimer <= 0.0f)
  2171. SaveIniSettingsToDisk(g.IO.IniFilename);
  2172. }
  2173. // Find the window we are hovering
  2174. // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
  2175. // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point.
  2176. // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
  2177. g.HoveredWindow = (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs)) ? g.MovingWindow : FindHoveredWindow(g.IO.MousePos);
  2178. g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
  2179. ImGuiWindow* modal_window = GetFrontMostModalRootWindow();
  2180. if (modal_window != NULL)
  2181. {
  2182. g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  2183. if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
  2184. g.HoveredRootWindow = g.HoveredWindow = NULL;
  2185. }
  2186. else
  2187. {
  2188. g.ModalWindowDarkeningRatio = 0.0f;
  2189. }
  2190. // Update the WantCaptureMouse/WantCAptureKeyboard flags, so user can capture/discard the inputs away from the rest of their application.
  2191. // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
  2192. int mouse_earliest_button_down = -1;
  2193. bool mouse_any_down = false;
  2194. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2195. {
  2196. if (g.IO.MouseClicked[i])
  2197. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
  2198. mouse_any_down |= g.IO.MouseDown[i];
  2199. if (g.IO.MouseDown[i])
  2200. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
  2201. mouse_earliest_button_down = i;
  2202. }
  2203. bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
  2204. if (g.WantCaptureMouseNextFrame != -1)
  2205. g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
  2206. else
  2207. g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
  2208. if (g.WantCaptureKeyboardNextFrame != -1)
  2209. g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
  2210. else
  2211. g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
  2212. g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : 0;
  2213. g.MouseCursor = ImGuiMouseCursor_Arrow;
  2214. g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
  2215. g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  2216. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  2217. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
  2218. bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
  2219. if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
  2220. g.HoveredWindow = g.HoveredRootWindow = NULL;
  2221. // Mouse wheel scrolling, scale
  2222. if (g.HoveredWindow && !g.HoveredWindow->Collapsed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f))
  2223. {
  2224. // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
  2225. ImGuiWindow* window = g.HoveredWindow;
  2226. ImGuiWindow* scroll_window = window;
  2227. while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs) && scroll_window->ParentWindow)
  2228. scroll_window = scroll_window->ParentWindow;
  2229. const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs);
  2230. if (g.IO.MouseWheel != 0.0f)
  2231. {
  2232. if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  2233. {
  2234. // Zoom / Scale window
  2235. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  2236. const float scale = new_font_scale / window->FontWindowScale;
  2237. window->FontWindowScale = new_font_scale;
  2238. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  2239. window->Pos += offset;
  2240. window->PosFloat += offset;
  2241. window->Size *= scale;
  2242. window->SizeFull *= scale;
  2243. }
  2244. else if (!g.IO.KeyCtrl && scroll_allowed)
  2245. {
  2246. // Mouse wheel vertical scrolling
  2247. float scroll_amount = 5 * scroll_window->CalcFontSize();
  2248. scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
  2249. SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
  2250. }
  2251. }
  2252. if (g.IO.MouseWheelH != 0.0f && scroll_allowed)
  2253. {
  2254. // Mouse wheel horizontal scrolling (for hardware that supports it)
  2255. float scroll_amount = scroll_window->CalcFontSize();
  2256. if (!g.IO.KeyCtrl && !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
  2257. SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
  2258. }
  2259. }
  2260. // Pressing TAB activate widget focus
  2261. if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
  2262. g.NavWindow->FocusIdxTabRequestNext = 0;
  2263. // Mark all windows as not visible
  2264. for (int i = 0; i != g.Windows.Size; i++)
  2265. {
  2266. ImGuiWindow* window = g.Windows[i];
  2267. window->WasActive = window->Active;
  2268. window->Active = false;
  2269. window->WriteAccessed = false;
  2270. }
  2271. // Closing the focused window restore focus to the first active root window in descending z-order
  2272. if (g.NavWindow && !g.NavWindow->WasActive)
  2273. FocusFrontMostActiveWindow(NULL);
  2274. // No window should be open at the beginning of the frame.
  2275. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  2276. g.CurrentWindowStack.resize(0);
  2277. g.CurrentPopupStack.resize(0);
  2278. ClosePopupsOverWindow(g.NavWindow);
  2279. // Create implicit window - we will only render it if the user has added something to it.
  2280. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
  2281. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
  2282. Begin("Debug##Default");
  2283. }
  2284. static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  2285. {
  2286. ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
  2287. if (!settings)
  2288. settings = AddWindowSettings(name);
  2289. return (void*)settings;
  2290. }
  2291. static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  2292. {
  2293. ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
  2294. float x, y;
  2295. int i;
  2296. if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y);
  2297. else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize);
  2298. else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
  2299. }
  2300. static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  2301. {
  2302. // Gather data from windows that were active during this session
  2303. ImGuiContext& g = *imgui_ctx;
  2304. for (int i = 0; i != g.Windows.Size; i++)
  2305. {
  2306. ImGuiWindow* window = g.Windows[i];
  2307. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  2308. continue;
  2309. ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID);
  2310. if (!settings)
  2311. settings = AddWindowSettings(window->Name);
  2312. settings->Pos = window->Pos;
  2313. settings->Size = window->SizeFull;
  2314. settings->Collapsed = window->Collapsed;
  2315. }
  2316. // Write a buffer
  2317. // If a window wasn't opened in this session we preserve its settings
  2318. buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
  2319. for (int i = 0; i != g.SettingsWindows.Size; i++)
  2320. {
  2321. const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
  2322. if (settings->Pos.x == FLT_MAX)
  2323. continue;
  2324. const char* name = settings->Name;
  2325. if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  2326. name = p;
  2327. buf->appendf("[%s][%s]\n", handler->TypeName, name);
  2328. buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
  2329. buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
  2330. buf->appendf("Collapsed=%d\n", settings->Collapsed);
  2331. buf->appendf("\n");
  2332. }
  2333. }
  2334. void ImGui::Initialize(ImGuiContext* context)
  2335. {
  2336. ImGuiContext& g = *context;
  2337. g.LogClipboard = IM_NEW(ImGuiTextBuffer)();
  2338. // Add .ini handle for ImGuiWindow type
  2339. ImGuiSettingsHandler ini_handler;
  2340. ini_handler.TypeName = "Window";
  2341. ini_handler.TypeHash = ImHash("Window", 0, 0);
  2342. ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
  2343. ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
  2344. ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
  2345. g.SettingsHandlers.push_front(ini_handler);
  2346. // Load .ini file
  2347. IM_ASSERT(g.SettingsWindows.empty());
  2348. LoadIniSettingsFromDisk(g.IO.IniFilename);
  2349. g.Initialized = true;
  2350. }
  2351. // This function is merely here to free heap allocations.
  2352. void ImGui::Shutdown(ImGuiContext* context)
  2353. {
  2354. ImGuiContext& g = *context;
  2355. // 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)
  2356. if (g.IO.Fonts && g.FontAtlasOwnedByContext)
  2357. IM_DELETE(g.IO.Fonts);
  2358. // Cleanup of other data are conditional on actually having initialize ImGui.
  2359. if (!g.Initialized)
  2360. return;
  2361. SaveIniSettingsToDisk(g.IO.IniFilename);
  2362. for (int i = 0; i < g.Windows.Size; i++)
  2363. IM_DELETE(g.Windows[i]);
  2364. g.Windows.clear();
  2365. g.WindowsSortBuffer.clear();
  2366. g.CurrentWindow = NULL;
  2367. g.CurrentWindowStack.clear();
  2368. g.WindowsById.Clear();
  2369. g.NavWindow = NULL;
  2370. g.HoveredWindow = NULL;
  2371. g.HoveredRootWindow = NULL;
  2372. g.ActiveIdWindow = NULL;
  2373. g.MovingWindow = NULL;
  2374. for (int i = 0; i < g.SettingsWindows.Size; i++)
  2375. IM_DELETE(g.SettingsWindows[i].Name);
  2376. g.ColorModifiers.clear();
  2377. g.StyleModifiers.clear();
  2378. g.FontStack.clear();
  2379. g.OpenPopupStack.clear();
  2380. g.CurrentPopupStack.clear();
  2381. g.DrawDataBuilder.ClearFreeMemory();
  2382. g.OverlayDrawList.ClearFreeMemory();
  2383. g.PrivateClipboard.clear();
  2384. g.InputTextState.Text.clear();
  2385. g.InputTextState.InitialText.clear();
  2386. g.InputTextState.TempTextBuffer.clear();
  2387. g.SettingsWindows.clear();
  2388. g.SettingsHandlers.clear();
  2389. if (g.LogFile && g.LogFile != stdout)
  2390. {
  2391. fclose(g.LogFile);
  2392. g.LogFile = NULL;
  2393. }
  2394. if (g.LogClipboard)
  2395. IM_DELETE(g.LogClipboard);
  2396. g.Initialized = false;
  2397. }
  2398. ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
  2399. {
  2400. ImGuiContext& g = *GImGui;
  2401. for (int i = 0; i != g.SettingsWindows.Size; i++)
  2402. if (g.SettingsWindows[i].Id == id)
  2403. return &g.SettingsWindows[i];
  2404. return NULL;
  2405. }
  2406. static ImGuiWindowSettings* AddWindowSettings(const char* name)
  2407. {
  2408. ImGuiContext& g = *GImGui;
  2409. g.SettingsWindows.push_back(ImGuiWindowSettings());
  2410. ImGuiWindowSettings* settings = &g.SettingsWindows.back();
  2411. settings->Name = ImStrdup(name);
  2412. settings->Id = ImHash(name, 0);
  2413. return settings;
  2414. }
  2415. static void LoadIniSettingsFromDisk(const char* ini_filename)
  2416. {
  2417. if (!ini_filename)
  2418. return;
  2419. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", NULL, +1);
  2420. if (!file_data)
  2421. return;
  2422. LoadIniSettingsFromMemory(file_data);
  2423. ImGui::MemFree(file_data);
  2424. }
  2425. ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
  2426. {
  2427. ImGuiContext& g = *GImGui;
  2428. const ImGuiID type_hash = ImHash(type_name, 0, 0);
  2429. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  2430. if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
  2431. return &g.SettingsHandlers[handler_n];
  2432. return NULL;
  2433. }
  2434. // Zero-tolerance, no error reporting, cheap .ini parsing
  2435. static void LoadIniSettingsFromMemory(const char* buf_readonly)
  2436. {
  2437. // For convenience and to make the code simpler, we'll write zero terminators inside the buffer. So let's create a writable copy.
  2438. char* buf = ImStrdup(buf_readonly);
  2439. char* buf_end = buf + strlen(buf);
  2440. ImGuiContext& g = *GImGui;
  2441. void* entry_data = NULL;
  2442. ImGuiSettingsHandler* entry_handler = NULL;
  2443. char* line_end = NULL;
  2444. for (char* line = buf; line < buf_end; line = line_end + 1)
  2445. {
  2446. // Skip new lines markers, then find end of the line
  2447. while (*line == '\n' || *line == '\r')
  2448. line++;
  2449. line_end = line;
  2450. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  2451. line_end++;
  2452. line_end[0] = 0;
  2453. if (line[0] == '[' && line_end > line && line_end[-1] == ']')
  2454. {
  2455. // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
  2456. line_end[-1] = 0;
  2457. const char* name_end = line_end - 1;
  2458. const char* type_start = line + 1;
  2459. char* type_end = ImStrchrRange(type_start, name_end, ']');
  2460. const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
  2461. if (!type_end || !name_start)
  2462. {
  2463. name_start = type_start; // Import legacy entries that have no type
  2464. type_start = "Window";
  2465. }
  2466. else
  2467. {
  2468. *type_end = 0; // Overwrite first ']'
  2469. name_start++; // Skip second '['
  2470. }
  2471. entry_handler = ImGui::FindSettingsHandler(type_start);
  2472. entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
  2473. }
  2474. else if (entry_handler != NULL && entry_data != NULL)
  2475. {
  2476. // Let type handler parse the line
  2477. entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
  2478. }
  2479. }
  2480. ImGui::MemFree(buf);
  2481. }
  2482. static void SaveIniSettingsToDisk(const char* ini_filename)
  2483. {
  2484. ImGuiContext& g = *GImGui;
  2485. g.SettingsDirtyTimer = 0.0f;
  2486. if (!ini_filename)
  2487. return;
  2488. ImVector<char> buf;
  2489. SaveIniSettingsToMemory(buf);
  2490. FILE* f = ImFileOpen(ini_filename, "wt");
  2491. if (!f)
  2492. return;
  2493. fwrite(buf.Data, sizeof(char), (size_t)buf.Size, f);
  2494. fclose(f);
  2495. }
  2496. static void SaveIniSettingsToMemory(ImVector<char>& out_buf)
  2497. {
  2498. ImGuiContext& g = *GImGui;
  2499. g.SettingsDirtyTimer = 0.0f;
  2500. ImGuiTextBuffer buf;
  2501. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  2502. {
  2503. ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
  2504. handler->WriteAllFn(&g, handler, &buf);
  2505. }
  2506. buf.Buf.pop_back(); // Remove extra zero-terminator used by ImGuiTextBuffer
  2507. out_buf.swap(buf.Buf);
  2508. }
  2509. void ImGui::MarkIniSettingsDirty()
  2510. {
  2511. ImGuiContext& g = *GImGui;
  2512. if (g.SettingsDirtyTimer <= 0.0f)
  2513. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  2514. }
  2515. static void MarkIniSettingsDirty(ImGuiWindow* window)
  2516. {
  2517. ImGuiContext& g = *GImGui;
  2518. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  2519. if (g.SettingsDirtyTimer <= 0.0f)
  2520. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  2521. }
  2522. // FIXME: Add a more explicit sort order in the window structure.
  2523. static int ChildWindowComparer(const void* lhs, const void* rhs)
  2524. {
  2525. const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
  2526. const ImGuiWindow* b = *(const ImGuiWindow**)rhs;
  2527. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  2528. return d;
  2529. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  2530. return d;
  2531. return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
  2532. }
  2533. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
  2534. {
  2535. out_sorted_windows->push_back(window);
  2536. if (window->Active)
  2537. {
  2538. int count = window->DC.ChildWindows.Size;
  2539. if (count > 1)
  2540. qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  2541. for (int i = 0; i < count; i++)
  2542. {
  2543. ImGuiWindow* child = window->DC.ChildWindows[i];
  2544. if (child->Active)
  2545. AddWindowToSortedBuffer(out_sorted_windows, child);
  2546. }
  2547. }
  2548. }
  2549. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_render_list, ImDrawList* draw_list)
  2550. {
  2551. if (draw_list->CmdBuffer.empty())
  2552. return;
  2553. // Remove trailing command if unused
  2554. ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
  2555. if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
  2556. {
  2557. draw_list->CmdBuffer.pop_back();
  2558. if (draw_list->CmdBuffer.empty())
  2559. return;
  2560. }
  2561. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
  2562. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  2563. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  2564. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  2565. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
  2566. // If this assert triggers because you are drawing lots of stuff manually:
  2567. // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
  2568. // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
  2569. // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
  2570. // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
  2571. // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
  2572. // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
  2573. if (sizeof(ImDrawIdx) == 2)
  2574. IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
  2575. out_render_list->push_back(draw_list);
  2576. }
  2577. static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
  2578. {
  2579. AddDrawListToDrawData(out_render_list, window->DrawList);
  2580. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  2581. {
  2582. ImGuiWindow* child = window->DC.ChildWindows[i];
  2583. if (child->Active && child->HiddenFrames <= 0) // clipped children may have been marked not active
  2584. AddWindowToDrawData(out_render_list, child);
  2585. }
  2586. }
  2587. static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window)
  2588. {
  2589. ImGuiContext& g = *GImGui;
  2590. g.IO.MetricsActiveWindows++;
  2591. if (window->Flags & ImGuiWindowFlags_Tooltip)
  2592. AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
  2593. else
  2594. AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
  2595. }
  2596. void ImDrawDataBuilder::FlattenIntoSingleLayer()
  2597. {
  2598. int n = Layers[0].Size;
  2599. int size = n;
  2600. for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
  2601. size += Layers[i].Size;
  2602. Layers[0].resize(size);
  2603. for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
  2604. {
  2605. ImVector<ImDrawList*>& layer = Layers[layer_n];
  2606. if (layer.empty())
  2607. continue;
  2608. memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  2609. n += layer.Size;
  2610. layer.resize(0);
  2611. }
  2612. }
  2613. static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* out_draw_data)
  2614. {
  2615. out_draw_data->Valid = true;
  2616. out_draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
  2617. out_draw_data->CmdListsCount = draw_lists->Size;
  2618. out_draw_data->TotalVtxCount = out_draw_data->TotalIdxCount = 0;
  2619. for (int n = 0; n < draw_lists->Size; n++)
  2620. {
  2621. out_draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
  2622. out_draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
  2623. }
  2624. }
  2625. // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
  2626. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  2627. {
  2628. ImGuiWindow* window = GetCurrentWindow();
  2629. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  2630. window->ClipRect = window->DrawList->_ClipRectStack.back();
  2631. }
  2632. void ImGui::PopClipRect()
  2633. {
  2634. ImGuiWindow* window = GetCurrentWindow();
  2635. window->DrawList->PopClipRect();
  2636. window->ClipRect = window->DrawList->_ClipRectStack.back();
  2637. }
  2638. // 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.
  2639. void ImGui::EndFrame()
  2640. {
  2641. ImGuiContext& g = *GImGui;
  2642. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2643. if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
  2644. return;
  2645. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  2646. if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
  2647. {
  2648. g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
  2649. g.OsImePosSet = g.OsImePosRequest;
  2650. }
  2651. // Hide implicit "Debug" window if it hasn't been used
  2652. IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
  2653. if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
  2654. g.CurrentWindow->Active = false;
  2655. End();
  2656. if (g.ActiveId == 0 && g.HoveredId == 0)
  2657. {
  2658. if (!g.NavWindow || !g.NavWindow->Appearing) // Unless we just made a window/popup appear
  2659. {
  2660. // Click to focus window and start moving (after we're done with all our widgets)
  2661. if (g.IO.MouseClicked[0])
  2662. {
  2663. if (g.HoveredRootWindow != NULL)
  2664. {
  2665. // Set ActiveId even if the _NoMove flag is set, without it dragging away from a window with _NoMove would activate hover on other windows.
  2666. FocusWindow(g.HoveredWindow);
  2667. SetActiveID(g.HoveredWindow->MoveId, g.HoveredWindow);
  2668. g.ActiveIdClickOffset = g.IO.MousePos - g.HoveredRootWindow->Pos;
  2669. if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove) && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoMove))
  2670. g.MovingWindow = g.HoveredWindow;
  2671. }
  2672. else if (g.NavWindow != NULL && GetFrontMostModalRootWindow() == NULL)
  2673. {
  2674. // Clicking on void disable focus
  2675. FocusWindow(NULL);
  2676. }
  2677. }
  2678. // With right mouse button we close popups without changing focus
  2679. // (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger)
  2680. if (g.IO.MouseClicked[1])
  2681. {
  2682. // Find the top-most window between HoveredWindow and the front most Modal Window.
  2683. // This is where we can trim the popup stack.
  2684. ImGuiWindow* modal = GetFrontMostModalRootWindow();
  2685. bool hovered_window_above_modal = false;
  2686. if (modal == NULL)
  2687. hovered_window_above_modal = true;
  2688. for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
  2689. {
  2690. ImGuiWindow* window = g.Windows[i];
  2691. if (window == modal)
  2692. break;
  2693. if (window == g.HoveredWindow)
  2694. hovered_window_above_modal = true;
  2695. }
  2696. ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal);
  2697. }
  2698. }
  2699. }
  2700. // Sort the window list so that all child windows are after their parent
  2701. // We cannot do that on FocusWindow() because childs may not exist yet
  2702. g.WindowsSortBuffer.resize(0);
  2703. g.WindowsSortBuffer.reserve(g.Windows.Size);
  2704. for (int i = 0; i != g.Windows.Size; i++)
  2705. {
  2706. ImGuiWindow* window = g.Windows[i];
  2707. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  2708. continue;
  2709. AddWindowToSortedBuffer(&g.WindowsSortBuffer, window);
  2710. }
  2711. IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
  2712. g.Windows.swap(g.WindowsSortBuffer);
  2713. // Clear Input data for next frame
  2714. g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
  2715. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  2716. g.FrameCountEnded = g.FrameCount;
  2717. }
  2718. void ImGui::Render()
  2719. {
  2720. ImGuiContext& g = *GImGui;
  2721. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2722. if (g.FrameCountEnded != g.FrameCount)
  2723. ImGui::EndFrame();
  2724. g.FrameCountRendered = g.FrameCount;
  2725. // Skip render altogether if alpha is 0.0
  2726. // 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.
  2727. if (g.Style.Alpha > 0.0f)
  2728. {
  2729. // Gather windows to render
  2730. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
  2731. g.DrawDataBuilder.Clear();
  2732. for (int n = 0; n != g.Windows.Size; n++)
  2733. {
  2734. ImGuiWindow* window = g.Windows[n];
  2735. if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
  2736. AddWindowToDrawDataSelectLayer(window);
  2737. }
  2738. g.DrawDataBuilder.FlattenIntoSingleLayer();
  2739. // Draw software mouse cursor if requested
  2740. ImVec2 offset, size, uv[4];
  2741. if (g.IO.MouseDrawCursor && g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &offset, &size, &uv[0], &uv[2]))
  2742. {
  2743. const ImVec2 pos = g.IO.MousePos - offset;
  2744. const ImTextureID tex_id = g.IO.Fonts->TexID;
  2745. const float sc = g.Style.MouseCursorScale;
  2746. g.OverlayDrawList.PushTextureID(tex_id);
  2747. g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(1,0)*sc, pos+ImVec2(1,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
  2748. g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(2,0)*sc, pos+ImVec2(2,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
  2749. g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[2], uv[3], IM_COL32(0,0,0,255)); // Black border
  2750. g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[0], uv[1], IM_COL32(255,255,255,255)); // White fill
  2751. g.OverlayDrawList.PopTextureID();
  2752. }
  2753. if (!g.OverlayDrawList.VtxBuffer.empty())
  2754. AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList);
  2755. // Setup ImDrawData structure for end-user
  2756. SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
  2757. g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
  2758. g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
  2759. // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
  2760. if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
  2761. g.IO.RenderDrawListsFn(&g.DrawData);
  2762. }
  2763. }
  2764. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  2765. {
  2766. const char* text_display_end = text;
  2767. if (!text_end)
  2768. text_end = (const char*)-1;
  2769. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2770. text_display_end++;
  2771. return text_display_end;
  2772. }
  2773. // Pass text data straight to log (without being displayed)
  2774. void ImGui::LogText(const char* fmt, ...)
  2775. {
  2776. ImGuiContext& g = *GImGui;
  2777. if (!g.LogEnabled)
  2778. return;
  2779. va_list args;
  2780. va_start(args, fmt);
  2781. if (g.LogFile)
  2782. {
  2783. vfprintf(g.LogFile, fmt, args);
  2784. }
  2785. else
  2786. {
  2787. g.LogClipboard->appendfv(fmt, args);
  2788. }
  2789. va_end(args);
  2790. }
  2791. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  2792. // We split text into individual lines to add current tree level padding
  2793. static void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL)
  2794. {
  2795. ImGuiContext& g = *GImGui;
  2796. ImGuiWindow* window = g.CurrentWindow;
  2797. if (!text_end)
  2798. text_end = ImGui::FindRenderedTextEnd(text, text_end);
  2799. const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1);
  2800. if (ref_pos)
  2801. window->DC.LogLinePosY = ref_pos->y;
  2802. const char* text_remaining = text;
  2803. if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
  2804. g.LogStartDepth = window->DC.TreeDepth;
  2805. const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
  2806. for (;;)
  2807. {
  2808. // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
  2809. const char* line_end = text_remaining;
  2810. while (line_end < text_end)
  2811. if (*line_end == '\n')
  2812. break;
  2813. else
  2814. line_end++;
  2815. if (line_end >= text_end)
  2816. line_end = NULL;
  2817. const bool is_first_line = (text == text_remaining);
  2818. bool is_last_line = false;
  2819. if (line_end == NULL)
  2820. {
  2821. is_last_line = true;
  2822. line_end = text_end;
  2823. }
  2824. if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
  2825. {
  2826. const int char_count = (int)(line_end - text_remaining);
  2827. if (log_new_line || !is_first_line)
  2828. ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining);
  2829. else
  2830. ImGui::LogText(" %.*s", char_count, text_remaining);
  2831. }
  2832. if (is_last_line)
  2833. break;
  2834. text_remaining = line_end + 1;
  2835. }
  2836. }
  2837. // Internal ImGui functions to render text
  2838. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  2839. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  2840. {
  2841. ImGuiContext& g = *GImGui;
  2842. ImGuiWindow* window = g.CurrentWindow;
  2843. // Hide anything after a '##' string
  2844. const char* text_display_end;
  2845. if (hide_text_after_hash)
  2846. {
  2847. text_display_end = FindRenderedTextEnd(text, text_end);
  2848. }
  2849. else
  2850. {
  2851. if (!text_end)
  2852. text_end = text + strlen(text); // FIXME-OPT
  2853. text_display_end = text_end;
  2854. }
  2855. const int text_len = (int)(text_display_end - text);
  2856. if (text_len > 0)
  2857. {
  2858. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  2859. if (g.LogEnabled)
  2860. LogRenderedText(&pos, text, text_display_end);
  2861. }
  2862. }
  2863. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  2864. {
  2865. ImGuiContext& g = *GImGui;
  2866. ImGuiWindow* window = g.CurrentWindow;
  2867. if (!text_end)
  2868. text_end = text + strlen(text); // FIXME-OPT
  2869. const int text_len = (int)(text_end - text);
  2870. if (text_len > 0)
  2871. {
  2872. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  2873. if (g.LogEnabled)
  2874. LogRenderedText(&pos, text, text_end);
  2875. }
  2876. }
  2877. // Default clip_rect uses (pos_min,pos_max)
  2878. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  2879. void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
  2880. {
  2881. // Hide anything after a '##' string
  2882. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  2883. const int text_len = (int)(text_display_end - text);
  2884. if (text_len == 0)
  2885. return;
  2886. ImGuiContext& g = *GImGui;
  2887. ImGuiWindow* window = g.CurrentWindow;
  2888. // Perform CPU side clipping for single clipped element to avoid using scissor state
  2889. ImVec2 pos = pos_min;
  2890. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  2891. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  2892. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  2893. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  2894. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  2895. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  2896. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  2897. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  2898. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  2899. // Render
  2900. if (need_clipping)
  2901. {
  2902. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  2903. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  2904. }
  2905. else
  2906. {
  2907. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2908. }
  2909. if (g.LogEnabled)
  2910. LogRenderedText(&pos, text, text_display_end);
  2911. }
  2912. // Render a rectangle shaped with optional rounding and borders
  2913. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2914. {
  2915. ImGuiContext& g = *GImGui;
  2916. ImGuiWindow* window = g.CurrentWindow;
  2917. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2918. const float border_size = g.Style.FrameBorderSize;
  2919. if (border && border_size > 0.0f)
  2920. {
  2921. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  2922. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  2923. }
  2924. }
  2925. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  2926. {
  2927. ImGuiContext& g = *GImGui;
  2928. ImGuiWindow* window = g.CurrentWindow;
  2929. const float border_size = g.Style.FrameBorderSize;
  2930. if (border_size > 0.0f)
  2931. {
  2932. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  2933. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  2934. }
  2935. }
  2936. // Render a triangle to denote expanded/collapsed state
  2937. void ImGui::RenderTriangle(ImVec2 p_min, ImGuiDir dir, float scale)
  2938. {
  2939. ImGuiContext& g = *GImGui;
  2940. ImGuiWindow* window = g.CurrentWindow;
  2941. const float h = g.FontSize * 1.00f;
  2942. float r = h * 0.40f * scale;
  2943. ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
  2944. ImVec2 a, b, c;
  2945. switch (dir)
  2946. {
  2947. case ImGuiDir_Up:
  2948. case ImGuiDir_Down:
  2949. if (dir == ImGuiDir_Up) r = -r;
  2950. center.y -= r * 0.25f;
  2951. a = ImVec2(0,1) * r;
  2952. b = ImVec2(-0.866f,-0.5f) * r;
  2953. c = ImVec2(+0.866f,-0.5f) * r;
  2954. break;
  2955. case ImGuiDir_Left:
  2956. case ImGuiDir_Right:
  2957. if (dir == ImGuiDir_Left) r = -r;
  2958. center.x -= r * 0.25f;
  2959. a = ImVec2(1,0) * r;
  2960. b = ImVec2(-0.500f,+0.866f) * r;
  2961. c = ImVec2(-0.500f,-0.866f) * r;
  2962. break;
  2963. case ImGuiDir_None:
  2964. case ImGuiDir_Count_:
  2965. IM_ASSERT(0);
  2966. break;
  2967. }
  2968. window->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
  2969. }
  2970. void ImGui::RenderBullet(ImVec2 pos)
  2971. {
  2972. ImGuiContext& g = *GImGui;
  2973. ImGuiWindow* window = g.CurrentWindow;
  2974. window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
  2975. }
  2976. void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
  2977. {
  2978. ImGuiContext& g = *GImGui;
  2979. ImGuiWindow* window = g.CurrentWindow;
  2980. float thickness = ImMax(sz / 5.0f, 1.0f);
  2981. sz -= thickness*0.5f;
  2982. pos += ImVec2(thickness*0.25f, thickness*0.25f);
  2983. float third = sz / 3.0f;
  2984. float bx = pos.x + third;
  2985. float by = pos.y + sz - third*0.5f;
  2986. window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
  2987. window->DrawList->PathLineTo(ImVec2(bx, by));
  2988. window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
  2989. window->DrawList->PathStroke(col, false, thickness);
  2990. }
  2991. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  2992. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
  2993. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  2994. {
  2995. ImGuiContext& g = *GImGui;
  2996. const char* text_display_end;
  2997. if (hide_text_after_double_hash)
  2998. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  2999. else
  3000. text_display_end = text_end;
  3001. ImFont* font = g.Font;
  3002. const float font_size = g.FontSize;
  3003. if (text == text_display_end)
  3004. return ImVec2(0.0f, font_size);
  3005. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  3006. // Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field)
  3007. const float font_scale = font_size / font->FontSize;
  3008. const float character_spacing_x = 1.0f * font_scale;
  3009. if (text_size.x > 0.0f)
  3010. text_size.x -= character_spacing_x;
  3011. text_size.x = (float)(int)(text_size.x + 0.95f);
  3012. return text_size;
  3013. }
  3014. // Helper to calculate coarse clipping of large list of evenly sized items.
  3015. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
  3016. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  3017. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  3018. {
  3019. ImGuiContext& g = *GImGui;
  3020. ImGuiWindow* window = g.CurrentWindow;
  3021. if (g.LogEnabled)
  3022. {
  3023. // If logging is active, do not perform any clipping
  3024. *out_items_display_start = 0;
  3025. *out_items_display_end = items_count;
  3026. return;
  3027. }
  3028. if (window->SkipItems)
  3029. {
  3030. *out_items_display_start = *out_items_display_end = 0;
  3031. return;
  3032. }
  3033. const ImVec2 pos = window->DC.CursorPos;
  3034. int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
  3035. int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
  3036. start = ImClamp(start, 0, items_count);
  3037. end = ImClamp(end + 1, start, items_count);
  3038. *out_items_display_start = start;
  3039. *out_items_display_end = end;
  3040. }
  3041. // Find window given position, search front-to-back
  3042. // FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected.
  3043. static ImGuiWindow* FindHoveredWindow(ImVec2 pos)
  3044. {
  3045. ImGuiContext& g = *GImGui;
  3046. for (int i = g.Windows.Size - 1; i >= 0; i--)
  3047. {
  3048. ImGuiWindow* window = g.Windows[i];
  3049. if (!window->Active)
  3050. continue;
  3051. if (window->Flags & ImGuiWindowFlags_NoInputs)
  3052. continue;
  3053. // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
  3054. ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
  3055. if (bb.Contains(pos))
  3056. return window;
  3057. }
  3058. return NULL;
  3059. }
  3060. // Test if mouse cursor is hovering given rectangle
  3061. // NB- Rectangle is clipped by our current clip setting
  3062. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  3063. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  3064. {
  3065. ImGuiContext& g = *GImGui;
  3066. ImGuiWindow* window = g.CurrentWindow;
  3067. // Clip
  3068. ImRect rect_clipped(r_min, r_max);
  3069. if (clip)
  3070. rect_clipped.ClipWith(window->ClipRect);
  3071. // Expand for touch input
  3072. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  3073. return rect_for_touch.Contains(g.IO.MousePos);
  3074. }
  3075. static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
  3076. {
  3077. const int key_index = GImGui->IO.KeyMap[key];
  3078. return (key_index >= 0) ? ImGui::IsKeyPressed(key_index, repeat) : false;
  3079. }
  3080. int ImGui::GetKeyIndex(ImGuiKey imgui_key)
  3081. {
  3082. IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
  3083. return GImGui->IO.KeyMap[imgui_key];
  3084. }
  3085. // Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]!
  3086. bool ImGui::IsKeyDown(int user_key_index)
  3087. {
  3088. if (user_key_index < 0) return false;
  3089. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
  3090. return GImGui->IO.KeysDown[user_key_index];
  3091. }
  3092. int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
  3093. {
  3094. if (t == 0.0f)
  3095. return 1;
  3096. if (t <= repeat_delay || repeat_rate <= 0.0f)
  3097. return 0;
  3098. const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
  3099. return (count > 0) ? count : 0;
  3100. }
  3101. int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
  3102. {
  3103. ImGuiContext& g = *GImGui;
  3104. if (key_index < 0) return false;
  3105. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3106. const float t = g.IO.KeysDownDuration[key_index];
  3107. return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
  3108. }
  3109. bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
  3110. {
  3111. ImGuiContext& g = *GImGui;
  3112. if (user_key_index < 0) return false;
  3113. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3114. const float t = g.IO.KeysDownDuration[user_key_index];
  3115. if (t == 0.0f)
  3116. return true;
  3117. if (repeat && t > g.IO.KeyRepeatDelay)
  3118. return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  3119. return false;
  3120. }
  3121. bool ImGui::IsKeyReleased(int user_key_index)
  3122. {
  3123. ImGuiContext& g = *GImGui;
  3124. if (user_key_index < 0) return false;
  3125. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3126. return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
  3127. }
  3128. bool ImGui::IsMouseDown(int button)
  3129. {
  3130. ImGuiContext& g = *GImGui;
  3131. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3132. return g.IO.MouseDown[button];
  3133. }
  3134. bool ImGui::IsMouseClicked(int button, bool repeat)
  3135. {
  3136. ImGuiContext& g = *GImGui;
  3137. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3138. const float t = g.IO.MouseDownDuration[button];
  3139. if (t == 0.0f)
  3140. return true;
  3141. if (repeat && t > g.IO.KeyRepeatDelay)
  3142. {
  3143. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  3144. if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  3145. return true;
  3146. }
  3147. return false;
  3148. }
  3149. bool ImGui::IsMouseReleased(int button)
  3150. {
  3151. ImGuiContext& g = *GImGui;
  3152. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3153. return g.IO.MouseReleased[button];
  3154. }
  3155. bool ImGui::IsMouseDoubleClicked(int button)
  3156. {
  3157. ImGuiContext& g = *GImGui;
  3158. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3159. return g.IO.MouseDoubleClicked[button];
  3160. }
  3161. bool ImGui::IsMouseDragging(int button, float lock_threshold)
  3162. {
  3163. ImGuiContext& g = *GImGui;
  3164. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3165. if (!g.IO.MouseDown[button])
  3166. return false;
  3167. if (lock_threshold < 0.0f)
  3168. lock_threshold = g.IO.MouseDragThreshold;
  3169. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  3170. }
  3171. ImVec2 ImGui::GetMousePos()
  3172. {
  3173. return GImGui->IO.MousePos;
  3174. }
  3175. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  3176. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  3177. {
  3178. ImGuiContext& g = *GImGui;
  3179. if (g.CurrentPopupStack.Size > 0)
  3180. return g.OpenPopupStack[g.CurrentPopupStack.Size-1].OpenMousePos;
  3181. return g.IO.MousePos;
  3182. }
  3183. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position
  3184. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  3185. {
  3186. if (mouse_pos == NULL)
  3187. mouse_pos = &GImGui->IO.MousePos;
  3188. const float MOUSE_INVALID = -256000.0f;
  3189. return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
  3190. }
  3191. // NB: This is only valid if IsMousePosValid(). Backends in theory should always keep mouse position valid when dragging even outside the client window.
  3192. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
  3193. {
  3194. ImGuiContext& g = *GImGui;
  3195. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3196. if (lock_threshold < 0.0f)
  3197. lock_threshold = g.IO.MouseDragThreshold;
  3198. if (g.IO.MouseDown[button])
  3199. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  3200. return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
  3201. return ImVec2(0.0f, 0.0f);
  3202. }
  3203. void ImGui::ResetMouseDragDelta(int button)
  3204. {
  3205. ImGuiContext& g = *GImGui;
  3206. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3207. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  3208. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  3209. }
  3210. ImGuiMouseCursor ImGui::GetMouseCursor()
  3211. {
  3212. return GImGui->MouseCursor;
  3213. }
  3214. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  3215. {
  3216. GImGui->MouseCursor = cursor_type;
  3217. }
  3218. void ImGui::CaptureKeyboardFromApp(bool capture)
  3219. {
  3220. GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
  3221. }
  3222. void ImGui::CaptureMouseFromApp(bool capture)
  3223. {
  3224. GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
  3225. }
  3226. bool ImGui::IsItemActive()
  3227. {
  3228. ImGuiContext& g = *GImGui;
  3229. if (g.ActiveId)
  3230. {
  3231. ImGuiWindow* window = g.CurrentWindow;
  3232. return g.ActiveId == window->DC.LastItemId;
  3233. }
  3234. return false;
  3235. }
  3236. bool ImGui::IsItemClicked(int mouse_button)
  3237. {
  3238. return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_Default);
  3239. }
  3240. bool ImGui::IsAnyItemHovered()
  3241. {
  3242. ImGuiContext& g = *GImGui;
  3243. return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
  3244. }
  3245. bool ImGui::IsAnyItemActive()
  3246. {
  3247. return GImGui->ActiveId != 0;
  3248. }
  3249. bool ImGui::IsItemVisible()
  3250. {
  3251. ImGuiWindow* window = GetCurrentWindowRead();
  3252. return window->ClipRect.Overlaps(window->DC.LastItemRect);
  3253. }
  3254. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  3255. void ImGui::SetItemAllowOverlap()
  3256. {
  3257. ImGuiContext& g = *GImGui;
  3258. if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
  3259. g.HoveredIdAllowOverlap = true;
  3260. if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
  3261. g.ActiveIdAllowOverlap = true;
  3262. }
  3263. ImVec2 ImGui::GetItemRectMin()
  3264. {
  3265. ImGuiWindow* window = GetCurrentWindowRead();
  3266. return window->DC.LastItemRect.Min;
  3267. }
  3268. ImVec2 ImGui::GetItemRectMax()
  3269. {
  3270. ImGuiWindow* window = GetCurrentWindowRead();
  3271. return window->DC.LastItemRect.Max;
  3272. }
  3273. ImVec2 ImGui::GetItemRectSize()
  3274. {
  3275. ImGuiWindow* window = GetCurrentWindowRead();
  3276. return window->DC.LastItemRect.GetSize();
  3277. }
  3278. static ImRect GetViewportRect()
  3279. {
  3280. ImGuiContext& g = *GImGui;
  3281. if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
  3282. return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
  3283. return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
  3284. }
  3285. // Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
  3286. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
  3287. {
  3288. ImGuiContext& g = *GImGui;
  3289. char window_name[16];
  3290. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
  3291. if (override_previous_tooltip)
  3292. if (ImGuiWindow* window = FindWindowByName(window_name))
  3293. if (window->Active)
  3294. {
  3295. // Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one.
  3296. window->HiddenFrames = 1;
  3297. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
  3298. }
  3299. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
  3300. Begin(window_name, NULL, flags | extra_flags);
  3301. }
  3302. void ImGui::SetTooltipV(const char* fmt, va_list args)
  3303. {
  3304. BeginTooltipEx(0, true);
  3305. TextV(fmt, args);
  3306. EndTooltip();
  3307. }
  3308. void ImGui::SetTooltip(const char* fmt, ...)
  3309. {
  3310. va_list args;
  3311. va_start(args, fmt);
  3312. SetTooltipV(fmt, args);
  3313. va_end(args);
  3314. }
  3315. void ImGui::BeginTooltip()
  3316. {
  3317. BeginTooltipEx(0, false);
  3318. }
  3319. void ImGui::EndTooltip()
  3320. {
  3321. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  3322. End();
  3323. }
  3324. // Mark popup as open (toggle toward open state).
  3325. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  3326. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  3327. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  3328. void ImGui::OpenPopupEx(ImGuiID id)
  3329. {
  3330. ImGuiContext& g = *GImGui;
  3331. ImGuiWindow* parent_window = g.CurrentWindow;
  3332. int current_stack_size = g.CurrentPopupStack.Size;
  3333. ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
  3334. popup_ref.PopupId = id;
  3335. popup_ref.Window = NULL;
  3336. popup_ref.ParentWindow = parent_window;
  3337. popup_ref.OpenFrameCount = g.FrameCount;
  3338. popup_ref.OpenParentId = parent_window->IDStack.back();
  3339. popup_ref.OpenMousePos = g.IO.MousePos;
  3340. popup_ref.OpenPopupPos = g.IO.MousePos; // NB: In the Navigation branch OpenPopupPos doesn't use the mouse position, hence the separation here.
  3341. if (g.OpenPopupStack.Size < current_stack_size + 1)
  3342. {
  3343. g.OpenPopupStack.push_back(popup_ref);
  3344. }
  3345. else
  3346. {
  3347. // Close child popups if any
  3348. g.OpenPopupStack.resize(current_stack_size + 1);
  3349. // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
  3350. // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
  3351. // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
  3352. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
  3353. g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
  3354. else
  3355. g.OpenPopupStack[current_stack_size] = popup_ref;
  3356. // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
  3357. // This is equivalent to what ClosePopupToLevel() does.
  3358. //if (g.OpenPopupStack[current_stack_size].PopupId == id)
  3359. // FocusWindow(parent_window);
  3360. }
  3361. }
  3362. void ImGui::OpenPopup(const char* str_id)
  3363. {
  3364. ImGuiContext& g = *GImGui;
  3365. OpenPopupEx(g.CurrentWindow->GetID(str_id));
  3366. }
  3367. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
  3368. {
  3369. ImGuiContext& g = *GImGui;
  3370. if (g.OpenPopupStack.empty())
  3371. return;
  3372. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  3373. // Don't close our own child popup windows.
  3374. int n = 0;
  3375. if (ref_window)
  3376. {
  3377. for (n = 0; n < g.OpenPopupStack.Size; n++)
  3378. {
  3379. ImGuiPopupRef& popup = g.OpenPopupStack[n];
  3380. if (!popup.Window)
  3381. continue;
  3382. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  3383. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  3384. continue;
  3385. // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow)
  3386. bool has_focus = false;
  3387. for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
  3388. has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow);
  3389. if (!has_focus)
  3390. break;
  3391. }
  3392. }
  3393. if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the block below
  3394. ClosePopupToLevel(n);
  3395. }
  3396. static ImGuiWindow* GetFrontMostModalRootWindow()
  3397. {
  3398. ImGuiContext& g = *GImGui;
  3399. for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
  3400. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  3401. if (popup->Flags & ImGuiWindowFlags_Modal)
  3402. return popup;
  3403. return NULL;
  3404. }
  3405. static void ClosePopupToLevel(int remaining)
  3406. {
  3407. ImGuiContext& g = *GImGui;
  3408. ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow;
  3409. ImGui::FocusWindow(focus_window);
  3410. g.OpenPopupStack.resize(remaining);
  3411. }
  3412. void ImGui::ClosePopup(ImGuiID id)
  3413. {
  3414. if (!IsPopupOpen(id))
  3415. return;
  3416. ImGuiContext& g = *GImGui;
  3417. ClosePopupToLevel(g.OpenPopupStack.Size - 1);
  3418. }
  3419. // Close the popup we have begin-ed into.
  3420. void ImGui::CloseCurrentPopup()
  3421. {
  3422. ImGuiContext& g = *GImGui;
  3423. int popup_idx = g.CurrentPopupStack.Size - 1;
  3424. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  3425. return;
  3426. while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
  3427. popup_idx--;
  3428. ClosePopupToLevel(popup_idx);
  3429. }
  3430. bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
  3431. {
  3432. ImGuiContext& g = *GImGui;
  3433. if (!IsPopupOpen(id))
  3434. {
  3435. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  3436. return false;
  3437. }
  3438. char name[20];
  3439. if (extra_flags & ImGuiWindowFlags_ChildMenu)
  3440. ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
  3441. else
  3442. ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
  3443. bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
  3444. if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
  3445. EndPopup();
  3446. return is_open;
  3447. }
  3448. bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
  3449. {
  3450. ImGuiContext& g = *GImGui;
  3451. if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance
  3452. {
  3453. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  3454. return false;
  3455. }
  3456. return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  3457. }
  3458. bool ImGui::IsPopupOpen(ImGuiID id)
  3459. {
  3460. ImGuiContext& g = *GImGui;
  3461. return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
  3462. }
  3463. bool ImGui::IsPopupOpen(const char* str_id)
  3464. {
  3465. ImGuiContext& g = *GImGui;
  3466. return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
  3467. }
  3468. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
  3469. {
  3470. ImGuiContext& g = *GImGui;
  3471. ImGuiWindow* window = g.CurrentWindow;
  3472. const ImGuiID id = window->GetID(name);
  3473. if (!IsPopupOpen(id))
  3474. {
  3475. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  3476. return false;
  3477. }
  3478. // Center modal windows by default
  3479. // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
  3480. if (g.NextWindowData.PosCond == 0)
  3481. SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
  3482. bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings);
  3483. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  3484. {
  3485. EndPopup();
  3486. if (is_open)
  3487. ClosePopup(id);
  3488. return false;
  3489. }
  3490. return is_open;
  3491. }
  3492. void ImGui::EndPopup()
  3493. {
  3494. ImGuiContext& g = *GImGui; (void)g;
  3495. IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  3496. IM_ASSERT(g.CurrentPopupStack.Size > 0);
  3497. End();
  3498. }
  3499. bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
  3500. {
  3501. ImGuiWindow* window = GImGui->CurrentWindow;
  3502. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  3503. {
  3504. ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  3505. IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  3506. OpenPopupEx(id);
  3507. return true;
  3508. }
  3509. return false;
  3510. }
  3511. // This is a helper to handle the simplest case of associating one named popup to one given widget.
  3512. // You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
  3513. // You can pass a NULL str_id to use the identifier of the last item.
  3514. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
  3515. {
  3516. ImGuiWindow* window = GImGui->CurrentWindow;
  3517. ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  3518. IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  3519. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  3520. OpenPopupEx(id);
  3521. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  3522. }
  3523. bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
  3524. {
  3525. if (!str_id)
  3526. str_id = "window_context";
  3527. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  3528. if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  3529. if (also_over_items || !IsAnyItemHovered())
  3530. OpenPopupEx(id);
  3531. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  3532. }
  3533. bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
  3534. {
  3535. if (!str_id)
  3536. str_id = "void_context";
  3537. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  3538. if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
  3539. OpenPopupEx(id);
  3540. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  3541. }
  3542. static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3543. {
  3544. ImGuiContext& g = *GImGui;
  3545. ImGuiWindow* parent_window = ImGui::GetCurrentWindow();
  3546. ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
  3547. flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
  3548. const ImVec2 content_avail = ImGui::GetContentRegionAvail();
  3549. ImVec2 size = ImFloor(size_arg);
  3550. const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
  3551. if (size.x <= 0.0f)
  3552. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  3553. if (size.y <= 0.0f)
  3554. size.y = ImMax(content_avail.y + size.y, 4.0f);
  3555. const float backup_border_size = g.Style.ChildBorderSize;
  3556. if (!border)
  3557. g.Style.ChildBorderSize = 0.0f;
  3558. flags |= extra_flags;
  3559. char title[256];
  3560. if (name)
  3561. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
  3562. else
  3563. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
  3564. ImGui::SetNextWindowSize(size);
  3565. bool ret = ImGui::Begin(title, NULL, flags);
  3566. ImGuiWindow* child_window = ImGui::GetCurrentWindow();
  3567. child_window->AutoFitChildAxises = auto_fit_axises;
  3568. g.Style.ChildBorderSize = backup_border_size;
  3569. return ret;
  3570. }
  3571. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3572. {
  3573. ImGuiWindow* window = GetCurrentWindow();
  3574. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  3575. }
  3576. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3577. {
  3578. IM_ASSERT(id != 0);
  3579. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  3580. }
  3581. void ImGui::EndChild()
  3582. {
  3583. ImGuiContext& g = *GImGui;
  3584. ImGuiWindow* window = g.CurrentWindow;
  3585. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
  3586. if (window->BeginCount > 1)
  3587. {
  3588. End();
  3589. }
  3590. else
  3591. {
  3592. // 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.
  3593. ImVec2 sz = GetWindowSize();
  3594. if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  3595. sz.x = ImMax(4.0f, sz.x);
  3596. if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
  3597. sz.y = ImMax(4.0f, sz.y);
  3598. End();
  3599. ImGuiWindow* parent_window = g.CurrentWindow;
  3600. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  3601. ItemSize(sz);
  3602. ItemAdd(bb, 0);
  3603. }
  3604. }
  3605. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  3606. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  3607. {
  3608. ImGuiContext& g = *GImGui;
  3609. const ImGuiStyle& style = g.Style;
  3610. PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
  3611. PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
  3612. PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
  3613. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  3614. return BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  3615. }
  3616. void ImGui::EndChildFrame()
  3617. {
  3618. EndChild();
  3619. PopStyleVar(3);
  3620. PopStyleColor();
  3621. }
  3622. // Save and compare stack sizes on Begin()/End() to detect usage errors
  3623. static void CheckStacksSize(ImGuiWindow* window, bool write)
  3624. {
  3625. // 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)
  3626. ImGuiContext& g = *GImGui;
  3627. int* p_backup = &window->DC.StackSizesBackup[0];
  3628. { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
  3629. { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
  3630. { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
  3631. { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
  3632. { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
  3633. { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
  3634. IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
  3635. }
  3636. enum ImGuiPopupPositionPolicy
  3637. {
  3638. ImGuiPopupPositionPolicy_Default,
  3639. ImGuiPopupPositionPolicy_ComboBox
  3640. };
  3641. static ImVec2 FindBestWindowPosForPopup(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default)
  3642. {
  3643. const ImGuiStyle& style = GImGui->Style;
  3644. // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
  3645. // r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
  3646. ImVec2 safe_padding = style.DisplaySafeAreaPadding;
  3647. ImRect r_outer(GetViewportRect());
  3648. r_outer.Expand(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));
  3649. ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
  3650. //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
  3651. //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
  3652. // Combo Box policy (we want a connecting edge)
  3653. if (policy == ImGuiPopupPositionPolicy_ComboBox)
  3654. {
  3655. const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
  3656. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++)
  3657. {
  3658. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  3659. if (n != -1 && dir == *last_dir) // Already tried this direction?
  3660. continue;
  3661. ImVec2 pos;
  3662. if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
  3663. if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
  3664. if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
  3665. if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
  3666. if (!r_outer.Contains(ImRect(pos, pos + size)))
  3667. continue;
  3668. *last_dir = dir;
  3669. return pos;
  3670. }
  3671. }
  3672. // Default popup policy
  3673. const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
  3674. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++)
  3675. {
  3676. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  3677. if (n != -1 && dir == *last_dir) // Already tried this direction?
  3678. continue;
  3679. float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
  3680. float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
  3681. if (avail_w < size.x || avail_h < size.y)
  3682. continue;
  3683. ImVec2 pos;
  3684. pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
  3685. pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
  3686. *last_dir = dir;
  3687. return pos;
  3688. }
  3689. // Fallback, try to keep within display
  3690. *last_dir = ImGuiDir_None;
  3691. ImVec2 pos = ref_pos;
  3692. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  3693. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  3694. return pos;
  3695. }
  3696. static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
  3697. {
  3698. window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
  3699. window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
  3700. window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
  3701. }
  3702. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  3703. {
  3704. ImGuiContext& g = *GImGui;
  3705. ImGuiID id = ImHash(name, 0);
  3706. return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
  3707. }
  3708. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
  3709. {
  3710. ImGuiContext& g = *GImGui;
  3711. // Create window the first time
  3712. ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
  3713. window->Flags = flags;
  3714. g.WindowsById.SetVoidPtr(window->ID, window);
  3715. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  3716. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  3717. {
  3718. // Retrieve settings from .ini file
  3719. // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  3720. window->Pos = window->PosFloat = ImVec2(60, 60);
  3721. if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
  3722. {
  3723. SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
  3724. window->PosFloat = settings->Pos;
  3725. window->Pos = ImFloor(window->PosFloat);
  3726. window->Collapsed = settings->Collapsed;
  3727. if (ImLengthSqr(settings->Size) > 0.00001f)
  3728. size = settings->Size;
  3729. }
  3730. }
  3731. window->Size = window->SizeFull = window->SizeFullAtLastBegin = size;
  3732. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  3733. {
  3734. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  3735. window->AutoFitOnlyGrows = false;
  3736. }
  3737. else
  3738. {
  3739. if (window->Size.x <= 0.0f)
  3740. window->AutoFitFramesX = 2;
  3741. if (window->Size.y <= 0.0f)
  3742. window->AutoFitFramesY = 2;
  3743. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  3744. }
  3745. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  3746. g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
  3747. else
  3748. g.Windows.push_back(window);
  3749. return window;
  3750. }
  3751. static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
  3752. {
  3753. ImGuiContext& g = *GImGui;
  3754. if (g.NextWindowData.SizeConstraintCond != 0)
  3755. {
  3756. // Using -1,-1 on either X/Y axis to preserve the current size.
  3757. ImRect cr = g.NextWindowData.SizeConstraintRect;
  3758. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  3759. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  3760. if (g.NextWindowData.SizeCallback)
  3761. {
  3762. ImGuiSizeCallbackData data;
  3763. data.UserData = g.NextWindowData.SizeCallbackUserData;
  3764. data.Pos = window->Pos;
  3765. data.CurrentSize = window->SizeFull;
  3766. data.DesiredSize = new_size;
  3767. g.NextWindowData.SizeCallback(&data);
  3768. new_size = data.DesiredSize;
  3769. }
  3770. }
  3771. // Minimum size
  3772. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  3773. {
  3774. new_size = ImMax(new_size, g.Style.WindowMinSize);
  3775. new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
  3776. }
  3777. return new_size;
  3778. }
  3779. static ImVec2 CalcSizeContents(ImGuiWindow* window)
  3780. {
  3781. ImVec2 sz;
  3782. sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
  3783. sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
  3784. return sz + window->WindowPadding;
  3785. }
  3786. static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
  3787. {
  3788. ImGuiContext& g = *GImGui;
  3789. ImGuiStyle& style = g.Style;
  3790. ImGuiWindowFlags flags = window->Flags;
  3791. ImVec2 size_auto_fit;
  3792. if ((flags & ImGuiWindowFlags_Tooltip) != 0)
  3793. {
  3794. // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
  3795. size_auto_fit = size_contents;
  3796. }
  3797. else
  3798. {
  3799. // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
  3800. size_auto_fit = ImClamp(size_contents, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
  3801. ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
  3802. if (size_auto_fit_after_constraint.x < size_contents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
  3803. size_auto_fit.y += style.ScrollbarSize;
  3804. if (size_auto_fit_after_constraint.y < size_contents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
  3805. size_auto_fit.x += style.ScrollbarSize;
  3806. }
  3807. return size_auto_fit;
  3808. }
  3809. static float GetScrollMaxX(ImGuiWindow* window)
  3810. {
  3811. return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
  3812. }
  3813. static float GetScrollMaxY(ImGuiWindow* window)
  3814. {
  3815. return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
  3816. }
  3817. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
  3818. {
  3819. ImVec2 scroll = window->Scroll;
  3820. float cr_x = window->ScrollTargetCenterRatio.x;
  3821. float cr_y = window->ScrollTargetCenterRatio.y;
  3822. if (window->ScrollTarget.x < FLT_MAX)
  3823. scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
  3824. if (window->ScrollTarget.y < FLT_MAX)
  3825. scroll.y = window->ScrollTarget.y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
  3826. scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
  3827. if (!window->Collapsed && !window->SkipItems)
  3828. {
  3829. scroll.x = ImMin(scroll.x, GetScrollMaxX(window));
  3830. scroll.y = ImMin(scroll.y, GetScrollMaxY(window));
  3831. }
  3832. return scroll;
  3833. }
  3834. static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
  3835. {
  3836. if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  3837. return ImGuiCol_PopupBg;
  3838. if (flags & ImGuiWindowFlags_ChildWindow)
  3839. return ImGuiCol_ChildBg;
  3840. return ImGuiCol_WindowBg;
  3841. }
  3842. static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
  3843. {
  3844. ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
  3845. ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
  3846. ImVec2 size_expected = pos_max - pos_min;
  3847. ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
  3848. *out_pos = pos_min;
  3849. if (corner_norm.x == 0.0f)
  3850. out_pos->x -= (size_constrained.x - size_expected.x);
  3851. if (corner_norm.y == 0.0f)
  3852. out_pos->y -= (size_constrained.y - size_expected.y);
  3853. *out_size = size_constrained;
  3854. }
  3855. struct ImGuiResizeGripDef
  3856. {
  3857. ImVec2 CornerPos;
  3858. ImVec2 InnerDir;
  3859. int AngleMin12, AngleMax12;
  3860. };
  3861. const ImGuiResizeGripDef resize_grip_def[4] =
  3862. {
  3863. { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
  3864. { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
  3865. { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
  3866. { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
  3867. };
  3868. static ImRect GetBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
  3869. {
  3870. ImRect rect = window->Rect();
  3871. if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
  3872. if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y, rect.Max.x - perp_padding, rect.Min.y + thickness);
  3873. if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x, rect.Max.y - perp_padding);
  3874. if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y);
  3875. if (border_n == 3) return ImRect(rect.Min.x, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding);
  3876. IM_ASSERT(0);
  3877. return ImRect();
  3878. }
  3879. // Handle resize for: Resize Grips, Borders, Gamepad
  3880. static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
  3881. {
  3882. ImGuiContext& g = *GImGui;
  3883. ImGuiWindowFlags flags = window->Flags;
  3884. if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  3885. return;
  3886. const int resize_border_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 4 : 0;
  3887. const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
  3888. const float grip_hover_size = (float)(int)(grip_draw_size * 0.75f);
  3889. ImVec2 pos_target(FLT_MAX, FLT_MAX);
  3890. ImVec2 size_target(FLT_MAX, FLT_MAX);
  3891. // Manual resize grips
  3892. PushID("#RESIZE");
  3893. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  3894. {
  3895. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  3896. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
  3897. // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
  3898. ImRect resize_rect(corner, corner + grip.InnerDir * grip_hover_size);
  3899. resize_rect.FixInverted();
  3900. bool hovered, held;
  3901. ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
  3902. if (hovered || held)
  3903. g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  3904. if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
  3905. {
  3906. // Manual auto-fit when double-clicking
  3907. size_target = CalcSizeAfterConstraint(window, size_auto_fit);
  3908. ClearActiveID();
  3909. }
  3910. else if (held)
  3911. {
  3912. // Resize from any of the four corners
  3913. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  3914. ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize() * grip.CornerPos; // Corner of the window corresponding to our corner grip
  3915. CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target);
  3916. }
  3917. if (resize_grip_n == 0 || held || hovered)
  3918. resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  3919. }
  3920. for (int border_n = 0; border_n < resize_border_count; border_n++)
  3921. {
  3922. const float BORDER_SIZE = 5.0f; // FIXME: Only works _inside_ window because of HoveredWindow check.
  3923. const float BORDER_APPEAR_TIMER = 0.05f; // Reduce visual noise
  3924. bool hovered, held;
  3925. ImRect border_rect = GetBorderRect(window, border_n, grip_hover_size, BORDER_SIZE);
  3926. ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
  3927. if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held)
  3928. {
  3929. g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
  3930. if (held) *border_held = border_n;
  3931. }
  3932. if (held)
  3933. {
  3934. ImVec2 border_target = window->Pos;
  3935. ImVec2 border_posn;
  3936. if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y); }
  3937. if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + BORDER_SIZE); }
  3938. if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + BORDER_SIZE); }
  3939. if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x); }
  3940. CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
  3941. }
  3942. }
  3943. PopID();
  3944. // Apply back modified position/size to window
  3945. if (size_target.x != FLT_MAX)
  3946. {
  3947. window->SizeFull = size_target;
  3948. MarkIniSettingsDirty(window);
  3949. }
  3950. if (pos_target.x != FLT_MAX)
  3951. {
  3952. window->Pos = window->PosFloat = ImFloor(pos_target);
  3953. MarkIniSettingsDirty(window);
  3954. }
  3955. window->Size = window->SizeFull;
  3956. }
  3957. // Push a new ImGui window to add widgets to.
  3958. // - 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.
  3959. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  3960. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  3961. // 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.
  3962. // - 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.
  3963. // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
  3964. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  3965. {
  3966. ImGuiContext& g = *GImGui;
  3967. const ImGuiStyle& style = g.Style;
  3968. IM_ASSERT(name != NULL); // Window name required
  3969. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  3970. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  3971. // Find or create
  3972. ImGuiWindow* window = FindWindowByName(name);
  3973. if (!window)
  3974. {
  3975. ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
  3976. window = CreateNewWindow(name, size_on_first_use, flags);
  3977. }
  3978. // Automatically disable manual moving/resizing when NoInputs is set
  3979. if (flags & ImGuiWindowFlags_NoInputs)
  3980. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  3981. //if (flags & ImGuiWindowFlags_NavFlattened)
  3982. // IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
  3983. const int current_frame = g.FrameCount;
  3984. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  3985. if (first_begin_of_the_frame)
  3986. window->Flags = (ImGuiWindowFlags)flags;
  3987. else
  3988. flags = window->Flags;
  3989. // Update the Appearing flag
  3990. bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  3991. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames == 1);
  3992. if (flags & ImGuiWindowFlags_Popup)
  3993. {
  3994. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
  3995. window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
  3996. window_just_activated_by_user |= (window != popup_ref.Window);
  3997. }
  3998. window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
  3999. window->CloseButton = (p_open != NULL);
  4000. if (window->Appearing)
  4001. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
  4002. // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
  4003. ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
  4004. ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
  4005. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  4006. // Add to stack
  4007. g.CurrentWindowStack.push_back(window);
  4008. SetCurrentWindow(window);
  4009. CheckStacksSize(window, true);
  4010. if (flags & ImGuiWindowFlags_Popup)
  4011. {
  4012. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
  4013. popup_ref.Window = window;
  4014. g.CurrentPopupStack.push_back(popup_ref);
  4015. window->PopupId = popup_ref.PopupId;
  4016. }
  4017. // Process SetNextWindow***() calls
  4018. bool window_pos_set_by_api = false;
  4019. bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
  4020. if (g.NextWindowData.PosCond)
  4021. {
  4022. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
  4023. if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
  4024. {
  4025. // May be processed on the next frame if this is our first frame and we are measuring size
  4026. // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
  4027. window->SetWindowPosVal = g.NextWindowData.PosVal;
  4028. window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
  4029. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  4030. }
  4031. else
  4032. {
  4033. SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
  4034. }
  4035. g.NextWindowData.PosCond = 0;
  4036. }
  4037. if (g.NextWindowData.SizeCond)
  4038. {
  4039. window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
  4040. window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
  4041. SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
  4042. g.NextWindowData.SizeCond = 0;
  4043. }
  4044. if (g.NextWindowData.ContentSizeCond)
  4045. {
  4046. // Adjust passed "client size" to become a "window size"
  4047. window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
  4048. if (window->SizeContentsExplicit.y != 0.0f)
  4049. window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
  4050. g.NextWindowData.ContentSizeCond = 0;
  4051. }
  4052. else if (first_begin_of_the_frame)
  4053. {
  4054. window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  4055. }
  4056. if (g.NextWindowData.CollapsedCond)
  4057. {
  4058. SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
  4059. g.NextWindowData.CollapsedCond = 0;
  4060. }
  4061. if (g.NextWindowData.FocusCond)
  4062. {
  4063. SetWindowFocus();
  4064. g.NextWindowData.FocusCond = 0;
  4065. }
  4066. if (window->Appearing)
  4067. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
  4068. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  4069. if (first_begin_of_the_frame)
  4070. {
  4071. const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
  4072. // Initialize
  4073. window->ParentWindow = parent_window;
  4074. window->RootWindow = window->RootNonPopupWindow = window;
  4075. if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !window_is_child_tooltip)
  4076. window->RootWindow = parent_window->RootWindow;
  4077. if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  4078. window->RootNonPopupWindow = parent_window->RootNonPopupWindow;
  4079. //window->NavRootWindow = window;
  4080. //while (window->NavRootWindow->Flags & ImGuiWindowFlags_NavFlattened)
  4081. // window->NavRootWindow = window->NavRootWindow->ParentWindow;
  4082. window->Active = true;
  4083. window->BeginOrderWithinParent = 0;
  4084. window->BeginOrderWithinContext = g.WindowsActiveCount++;
  4085. window->BeginCount = 0;
  4086. window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
  4087. window->LastFrameActive = current_frame;
  4088. window->IDStack.resize(1);
  4089. // Lock window rounding, border size and rounding so that altering the border sizes for children doesn't have side-effects.
  4090. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
  4091. window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
  4092. window->WindowPadding = style.WindowPadding;
  4093. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
  4094. window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
  4095. // Collapse window by double-clicking on title bar
  4096. // 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
  4097. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  4098. {
  4099. ImRect title_bar_rect = window->TitleBarRect();
  4100. if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
  4101. {
  4102. window->Collapsed = !window->Collapsed;
  4103. MarkIniSettingsDirty(window);
  4104. FocusWindow(window);
  4105. }
  4106. }
  4107. else
  4108. {
  4109. window->Collapsed = false;
  4110. }
  4111. // SIZE
  4112. // Update contents size from last frame for auto-fitting (unless explicitly specified)
  4113. window->SizeContents = CalcSizeContents(window);
  4114. // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
  4115. if (window->HiddenFrames > 0)
  4116. window->HiddenFrames--;
  4117. if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && window_just_activated_by_user)
  4118. {
  4119. window->HiddenFrames = 1;
  4120. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  4121. {
  4122. if (!window_size_x_set_by_api)
  4123. window->Size.x = window->SizeFull.x = 0.f;
  4124. if (!window_size_y_set_by_api)
  4125. window->Size.y = window->SizeFull.y = 0.f;
  4126. window->SizeContents = ImVec2(0.f, 0.f);
  4127. }
  4128. }
  4129. // Calculate auto-fit size, handle automatic resize
  4130. const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
  4131. ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
  4132. if (flags & ImGuiWindowFlags_AlwaysAutoResize && !window->Collapsed)
  4133. {
  4134. // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
  4135. if (!window_size_x_set_by_api)
  4136. window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
  4137. if (!window_size_y_set_by_api)
  4138. window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
  4139. }
  4140. else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  4141. {
  4142. // Auto-fit only grows during the first few frames
  4143. // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  4144. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
  4145. window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  4146. if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
  4147. window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  4148. if (!window->Collapsed)
  4149. MarkIniSettingsDirty(window);
  4150. }
  4151. // Apply minimum/maximum window size constraints and final size
  4152. window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
  4153. window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
  4154. // SCROLLBAR STATUS
  4155. // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
  4156. if (!window->Collapsed)
  4157. {
  4158. // When reading the current size we need to read it after size constraints have been applied
  4159. float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
  4160. float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
  4161. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
  4162. window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
  4163. if (window->ScrollbarX && !window->ScrollbarY)
  4164. window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
  4165. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  4166. }
  4167. // POSITION
  4168. // Popup latch its initial position, will position itself when it appears next frame
  4169. if (window_just_activated_by_user)
  4170. {
  4171. window->AutoPosLastDirection = ImGuiDir_None;
  4172. if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
  4173. window->Pos = window->PosFloat = g.CurrentPopupStack.back().OpenPopupPos;
  4174. }
  4175. // Position child window
  4176. if (flags & ImGuiWindowFlags_ChildWindow)
  4177. {
  4178. window->BeginOrderWithinParent = parent_window->DC.ChildWindows.Size;
  4179. parent_window->DC.ChildWindows.push_back(window);
  4180. if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
  4181. window->Pos = window->PosFloat = parent_window->DC.CursorPos;
  4182. }
  4183. const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFrames == 0);
  4184. if (window_pos_with_pivot)
  4185. {
  4186. // Position given a pivot (e.g. for centering)
  4187. SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0);
  4188. }
  4189. else if (flags & ImGuiWindowFlags_ChildMenu)
  4190. {
  4191. // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds.
  4192. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  4193. IM_ASSERT(window_pos_set_by_api);
  4194. float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value).
  4195. ImGuiWindow* parent_menu = parent_window_in_stack;
  4196. ImRect rect_to_avoid;
  4197. if (parent_menu->DC.MenuBarAppending)
  4198. rect_to_avoid = ImRect(-FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight(), FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight() + parent_menu->MenuBarHeight());
  4199. else
  4200. rect_to_avoid = ImRect(parent_menu->Pos.x + horizontal_overlap, -FLT_MAX, parent_menu->Pos.x + parent_menu->Size.x - horizontal_overlap - parent_menu->ScrollbarSizes.x, FLT_MAX);
  4201. window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4202. }
  4203. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
  4204. {
  4205. ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
  4206. window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4207. }
  4208. // Position tooltip (always follows mouse)
  4209. if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
  4210. {
  4211. float sc = g.Style.MouseCursorScale;
  4212. ImVec2 ref_pos = g.IO.MousePos;
  4213. ImRect rect_to_avoid(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
  4214. window->PosFloat = FindBestWindowPosForPopup(ref_pos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4215. if (window->AutoPosLastDirection == ImGuiDir_None)
  4216. window->PosFloat = ref_pos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  4217. }
  4218. // Clamp position so it stays visible
  4219. if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  4220. {
  4221. 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.
  4222. {
  4223. ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  4224. window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size;
  4225. window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
  4226. }
  4227. }
  4228. window->Pos = ImFloor(window->PosFloat);
  4229. // Default item width. Make it proportional to window size if window manually resizes
  4230. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  4231. window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
  4232. else
  4233. window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
  4234. // Prepare for focus requests
  4235. window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
  4236. window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
  4237. window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
  4238. window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
  4239. // Apply scrolling
  4240. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  4241. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  4242. // Apply focus, new windows appears in front
  4243. bool want_focus = false;
  4244. if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  4245. if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
  4246. want_focus = true;
  4247. // Handle manual resize: Resize Grips, Borders, Gamepad
  4248. int border_held = -1;
  4249. ImU32 resize_grip_col[4] = { 0 };
  4250. const int resize_grip_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 2 : 1; // 4
  4251. const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
  4252. if (!window->Collapsed)
  4253. UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
  4254. // DRAWING
  4255. // Setup draw list and outer clipping rectangle
  4256. window->DrawList->Clear();
  4257. window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
  4258. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  4259. ImRect viewport_rect(GetViewportRect());
  4260. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
  4261. PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
  4262. else
  4263. PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
  4264. // Draw modal window background (darkens what is behind them)
  4265. if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
  4266. window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
  4267. // Draw window + handle manual resize
  4268. const float window_rounding = window->WindowRounding;
  4269. const float window_border_size = window->WindowBorderSize;
  4270. ImRect title_bar_rect = window->TitleBarRect();
  4271. const bool window_is_focused = want_focus || (g.NavWindow && window->RootNonPopupWindow == g.NavWindow->RootNonPopupWindow);
  4272. ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  4273. if (window->Collapsed)
  4274. {
  4275. // Title bar only
  4276. float backup_border_size = style.FrameBorderSize;
  4277. g.Style.FrameBorderSize = window->WindowBorderSize;
  4278. RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
  4279. g.Style.FrameBorderSize = backup_border_size;
  4280. }
  4281. else
  4282. {
  4283. // Window background
  4284. ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
  4285. if (g.NextWindowData.BgAlphaCond != 0)
  4286. {
  4287. bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
  4288. g.NextWindowData.BgAlphaCond = 0;
  4289. }
  4290. window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
  4291. // Title bar
  4292. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4293. window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
  4294. // Menu bar
  4295. if (flags & ImGuiWindowFlags_MenuBar)
  4296. {
  4297. ImRect menu_bar_rect = window->MenuBarRect();
  4298. menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
  4299. window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
  4300. if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
  4301. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  4302. }
  4303. // Scrollbars
  4304. if (window->ScrollbarX)
  4305. Scrollbar(ImGuiLayoutType_Horizontal);
  4306. if (window->ScrollbarY)
  4307. Scrollbar(ImGuiLayoutType_Vertical);
  4308. // Render resize grips (after their input handling so we don't have a frame of latency)
  4309. if (!(flags & ImGuiWindowFlags_NoResize))
  4310. {
  4311. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  4312. {
  4313. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  4314. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
  4315. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size)));
  4316. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size)));
  4317. window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
  4318. window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
  4319. }
  4320. }
  4321. // Borders
  4322. if (window_border_size > 0.0f)
  4323. window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size);
  4324. if (border_held != -1)
  4325. {
  4326. ImRect border = GetBorderRect(window, border_held, grip_draw_size, 0.0f);
  4327. window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size));
  4328. }
  4329. if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar))
  4330. window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize,-1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  4331. }
  4332. // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
  4333. window->SizeFullAtLastBegin = window->SizeFull;
  4334. // Update ContentsRegionMax. All the variable it depends on are set above in this function.
  4335. window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
  4336. window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
  4337. window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
  4338. window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
  4339. // Setup drawing context
  4340. // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
  4341. window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
  4342. window->DC.GroupOffsetX = 0.0f;
  4343. window->DC.ColumnsOffsetX = 0.0f;
  4344. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
  4345. window->DC.CursorPos = window->DC.CursorStartPos;
  4346. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  4347. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  4348. window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
  4349. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  4350. window->DC.MenuBarAppending = false;
  4351. window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
  4352. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  4353. window->DC.ChildWindows.resize(0);
  4354. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  4355. window->DC.ItemFlags = ImGuiItemFlags_Default_;
  4356. window->DC.ItemWidth = window->ItemWidthDefault;
  4357. window->DC.TextWrapPos = -1.0f; // disabled
  4358. window->DC.ItemFlagsStack.resize(0);
  4359. window->DC.ItemWidthStack.resize(0);
  4360. window->DC.TextWrapPosStack.resize(0);
  4361. window->DC.ColumnsSet = NULL;
  4362. window->DC.TreeDepth = 0;
  4363. window->DC.StateStorage = &window->StateStorage;
  4364. window->DC.GroupStack.resize(0);
  4365. window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
  4366. if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
  4367. {
  4368. window->DC.ItemFlags = parent_window->DC.ItemFlags;
  4369. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  4370. }
  4371. if (window->AutoFitFramesX > 0)
  4372. window->AutoFitFramesX--;
  4373. if (window->AutoFitFramesY > 0)
  4374. window->AutoFitFramesY--;
  4375. // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  4376. if (want_focus)
  4377. FocusWindow(window);
  4378. // Title bar
  4379. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4380. {
  4381. // Collapse button
  4382. if (!(flags & ImGuiWindowFlags_NoCollapse))
  4383. {
  4384. RenderTriangle(window->Pos + style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
  4385. }
  4386. // Close button
  4387. if (p_open != NULL)
  4388. {
  4389. const float PAD = 2.0f;
  4390. const float rad = (window->TitleBarHeight() - PAD*2.0f) * 0.5f;
  4391. if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-PAD - rad, PAD + rad), rad))
  4392. *p_open = false;
  4393. }
  4394. // Title text (FIXME: refactor text alignment facilities along with RenderText helpers)
  4395. ImVec2 text_size = CalcTextSize(name, NULL, true);
  4396. ImRect text_r = title_bar_rect;
  4397. float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  4398. float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  4399. if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
  4400. text_r.Min.x += pad_left;
  4401. text_r.Max.x -= pad_right;
  4402. ImRect clip_rect = text_r;
  4403. clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
  4404. RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
  4405. }
  4406. // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
  4407. window->WindowRectClipped = window->Rect();
  4408. window->WindowRectClipped.ClipWith(window->ClipRect);
  4409. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  4410. // 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.
  4411. // Maybe we can support CTRL+C on every element?
  4412. /*
  4413. if (g.ActiveId == move_id)
  4414. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  4415. ImGui::LogToClipboard();
  4416. */
  4417. // Inner rectangle
  4418. // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
  4419. // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
  4420. window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
  4421. window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
  4422. window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize;
  4423. window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
  4424. //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
  4425. // After Begin() we fill the last item / hovered data using the title bar data. Make that a standard behavior (to allow usage of context menus on title bar only, etc.).
  4426. window->DC.LastItemId = window->MoveId;
  4427. window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
  4428. window->DC.LastItemRect = title_bar_rect;
  4429. }
  4430. // Inner clipping rectangle
  4431. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  4432. const float border_size = window->WindowBorderSize;
  4433. ImRect clip_rect;
  4434. clip_rect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size)));
  4435. clip_rect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y);
  4436. clip_rect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size)));
  4437. clip_rect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y);
  4438. PushClipRect(clip_rect.Min, clip_rect.Max, true);
  4439. // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
  4440. if (first_begin_of_the_frame)
  4441. window->WriteAccessed = false;
  4442. window->BeginCount++;
  4443. g.NextWindowData.SizeConstraintCond = 0;
  4444. // Child window can be out of sight and have "negative" clip windows.
  4445. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
  4446. if (flags & ImGuiWindowFlags_ChildWindow)
  4447. {
  4448. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  4449. window->Collapsed = parent_window && parent_window->Collapsed;
  4450. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  4451. window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y);
  4452. // We also hide the window from rendering because we've already added its border to the command list.
  4453. // (we could perform the check earlier in the function but it is simpler at this point)
  4454. if (window->Collapsed)
  4455. window->Active = false;
  4456. }
  4457. if (style.Alpha <= 0.0f)
  4458. window->Active = false;
  4459. // Return false if we don't intend to display anything to allow user to perform an early out optimization
  4460. window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
  4461. return !window->SkipItems;
  4462. }
  4463. // Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
  4464. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  4465. bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
  4466. {
  4467. // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
  4468. if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
  4469. ImGui::SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
  4470. // Old API feature: override the window background alpha with a parameter.
  4471. if (bg_alpha_override >= 0.0f)
  4472. ImGui::SetNextWindowBgAlpha(bg_alpha_override);
  4473. return ImGui::Begin(name, p_open, flags);
  4474. }
  4475. #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  4476. void ImGui::End()
  4477. {
  4478. ImGuiContext& g = *GImGui;
  4479. ImGuiWindow* window = g.CurrentWindow;
  4480. if (window->DC.ColumnsSet != NULL)
  4481. EndColumns();
  4482. PopClipRect(); // inner window clip rectangle
  4483. // Stop logging
  4484. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  4485. LogFinish();
  4486. // Pop
  4487. // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin().
  4488. g.CurrentWindowStack.pop_back();
  4489. if (window->Flags & ImGuiWindowFlags_Popup)
  4490. g.CurrentPopupStack.pop_back();
  4491. CheckStacksSize(window, false);
  4492. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  4493. }
  4494. // Vertical scrollbar
  4495. // The entire piece of code below is rather confusing because:
  4496. // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
  4497. // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
  4498. // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
  4499. void ImGui::Scrollbar(ImGuiLayoutType direction)
  4500. {
  4501. ImGuiContext& g = *GImGui;
  4502. ImGuiWindow* window = g.CurrentWindow;
  4503. const bool horizontal = (direction == ImGuiLayoutType_Horizontal);
  4504. const ImGuiStyle& style = g.Style;
  4505. const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
  4506. // Render background
  4507. bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
  4508. float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
  4509. const ImRect window_rect = window->Rect();
  4510. const float border_size = window->WindowBorderSize;
  4511. ImRect bb = horizontal
  4512. ? 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)
  4513. : 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);
  4514. if (!horizontal)
  4515. bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
  4516. if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f)
  4517. return;
  4518. int window_rounding_corners;
  4519. if (horizontal)
  4520. window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
  4521. else
  4522. window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
  4523. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners);
  4524. bb.Expand(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)));
  4525. // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
  4526. float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
  4527. float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
  4528. float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w;
  4529. float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
  4530. // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
  4531. // But we maintain a minimum size in pixel to allow for the user to still aim inside.
  4532. IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
  4533. const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f);
  4534. const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
  4535. const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
  4536. // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
  4537. bool held = false;
  4538. bool hovered = false;
  4539. const bool previously_held = (g.ActiveId == id);
  4540. ButtonBehavior(bb, id, &hovered, &held);
  4541. float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
  4542. float scroll_ratio = ImSaturate(scroll_v / scroll_max);
  4543. float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  4544. if (held && grab_h_norm < 1.0f)
  4545. {
  4546. float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
  4547. float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  4548. float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y;
  4549. // Click position in scrollbar normalized space (0.0f->1.0f)
  4550. const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
  4551. SetHoveredID(id);
  4552. bool seek_absolute = false;
  4553. if (!previously_held)
  4554. {
  4555. // On initial click calculate the distance between mouse and the center of the grab
  4556. if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
  4557. {
  4558. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  4559. }
  4560. else
  4561. {
  4562. seek_absolute = true;
  4563. *click_delta_to_grab_center_v = 0.0f;
  4564. }
  4565. }
  4566. // Apply scroll
  4567. // 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
  4568. 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));
  4569. scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
  4570. if (horizontal)
  4571. window->Scroll.x = scroll_v;
  4572. else
  4573. window->Scroll.y = scroll_v;
  4574. // Update values for rendering
  4575. scroll_ratio = ImSaturate(scroll_v / scroll_max);
  4576. grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  4577. // Update distance to grab now that we have seeked and saturated
  4578. if (seek_absolute)
  4579. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  4580. }
  4581. // Render
  4582. const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
  4583. ImRect grab_rect;
  4584. if (horizontal)
  4585. grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y);
  4586. else
  4587. grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y));
  4588. window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
  4589. }
  4590. void ImGui::BringWindowToFront(ImGuiWindow* window)
  4591. {
  4592. ImGuiContext& g = *GImGui;
  4593. ImGuiWindow* current_front_window = g.Windows.back();
  4594. if (current_front_window == window || current_front_window->RootWindow == window)
  4595. return;
  4596. for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
  4597. if (g.Windows[i] == window)
  4598. {
  4599. g.Windows.erase(g.Windows.Data + i);
  4600. g.Windows.push_back(window);
  4601. break;
  4602. }
  4603. }
  4604. void ImGui::BringWindowToBack(ImGuiWindow* window)
  4605. {
  4606. ImGuiContext& g = *GImGui;
  4607. if (g.Windows[0] == window)
  4608. return;
  4609. for (int i = 0; i < g.Windows.Size; i++)
  4610. if (g.Windows[i] == window)
  4611. {
  4612. memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
  4613. g.Windows[0] = window;
  4614. break;
  4615. }
  4616. }
  4617. // Moving window to front of display and set focus (which happens to be back of our sorted list)
  4618. void ImGui::FocusWindow(ImGuiWindow* window)
  4619. {
  4620. ImGuiContext& g = *GImGui;
  4621. // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
  4622. g.NavWindow = window;
  4623. // Passing NULL allow to disable keyboard focus
  4624. if (!window)
  4625. return;
  4626. // Move the root window to the top of the pile
  4627. if (window->RootWindow)
  4628. window = window->RootWindow;
  4629. // Steal focus on active widgets
  4630. if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
  4631. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
  4632. ClearActiveID();
  4633. // Bring to front
  4634. if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
  4635. BringWindowToFront(window);
  4636. }
  4637. void ImGui::FocusFrontMostActiveWindow(ImGuiWindow* ignore_window)
  4638. {
  4639. ImGuiContext& g = *GImGui;
  4640. for (int i = g.Windows.Size - 1; i >= 0; i--)
  4641. if (g.Windows[i] != ignore_window && g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
  4642. {
  4643. FocusWindow(g.Windows[i]);
  4644. return;
  4645. }
  4646. }
  4647. void ImGui::PushItemWidth(float item_width)
  4648. {
  4649. ImGuiWindow* window = GetCurrentWindow();
  4650. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  4651. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
  4652. }
  4653. void ImGui::PushMultiItemsWidths(int components, float w_full)
  4654. {
  4655. ImGuiWindow* window = GetCurrentWindow();
  4656. const ImGuiStyle& style = GImGui->Style;
  4657. if (w_full <= 0.0f)
  4658. w_full = CalcItemWidth();
  4659. const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  4660. const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  4661. window->DC.ItemWidthStack.push_back(w_item_last);
  4662. for (int i = 0; i < components-1; i++)
  4663. window->DC.ItemWidthStack.push_back(w_item_one);
  4664. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  4665. }
  4666. void ImGui::PopItemWidth()
  4667. {
  4668. ImGuiWindow* window = GetCurrentWindow();
  4669. window->DC.ItemWidthStack.pop_back();
  4670. window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
  4671. }
  4672. float ImGui::CalcItemWidth()
  4673. {
  4674. ImGuiWindow* window = GetCurrentWindowRead();
  4675. float w = window->DC.ItemWidth;
  4676. if (w < 0.0f)
  4677. {
  4678. // 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.
  4679. float width_to_right_edge = GetContentRegionAvail().x;
  4680. w = ImMax(1.0f, width_to_right_edge + w);
  4681. }
  4682. w = (float)(int)w;
  4683. return w;
  4684. }
  4685. static ImFont* GetDefaultFont()
  4686. {
  4687. ImGuiContext& g = *GImGui;
  4688. return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0];
  4689. }
  4690. void ImGui::SetCurrentFont(ImFont* font)
  4691. {
  4692. ImGuiContext& g = *GImGui;
  4693. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  4694. IM_ASSERT(font->Scale > 0.0f);
  4695. g.Font = font;
  4696. g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
  4697. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  4698. ImFontAtlas* atlas = g.Font->ContainerAtlas;
  4699. g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
  4700. g.DrawListSharedData.Font = g.Font;
  4701. g.DrawListSharedData.FontSize = g.FontSize;
  4702. }
  4703. void ImGui::PushFont(ImFont* font)
  4704. {
  4705. ImGuiContext& g = *GImGui;
  4706. if (!font)
  4707. font = GetDefaultFont();
  4708. SetCurrentFont(font);
  4709. g.FontStack.push_back(font);
  4710. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  4711. }
  4712. void ImGui::PopFont()
  4713. {
  4714. ImGuiContext& g = *GImGui;
  4715. g.CurrentWindow->DrawList->PopTextureID();
  4716. g.FontStack.pop_back();
  4717. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  4718. }
  4719. void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
  4720. {
  4721. ImGuiWindow* window = GetCurrentWindow();
  4722. if (enabled)
  4723. window->DC.ItemFlags |= option;
  4724. else
  4725. window->DC.ItemFlags &= ~option;
  4726. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  4727. }
  4728. void ImGui::PopItemFlag()
  4729. {
  4730. ImGuiWindow* window = GetCurrentWindow();
  4731. window->DC.ItemFlagsStack.pop_back();
  4732. window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
  4733. }
  4734. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  4735. {
  4736. PushItemFlag(ImGuiItemFlags_AllowKeyboardFocus, allow_keyboard_focus);
  4737. }
  4738. void ImGui::PopAllowKeyboardFocus()
  4739. {
  4740. PopItemFlag();
  4741. }
  4742. void ImGui::PushButtonRepeat(bool repeat)
  4743. {
  4744. PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
  4745. }
  4746. void ImGui::PopButtonRepeat()
  4747. {
  4748. PopItemFlag();
  4749. }
  4750. void ImGui::PushTextWrapPos(float wrap_pos_x)
  4751. {
  4752. ImGuiWindow* window = GetCurrentWindow();
  4753. window->DC.TextWrapPos = wrap_pos_x;
  4754. window->DC.TextWrapPosStack.push_back(wrap_pos_x);
  4755. }
  4756. void ImGui::PopTextWrapPos()
  4757. {
  4758. ImGuiWindow* window = GetCurrentWindow();
  4759. window->DC.TextWrapPosStack.pop_back();
  4760. window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
  4761. }
  4762. // FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
  4763. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  4764. {
  4765. ImGuiContext& g = *GImGui;
  4766. ImGuiColMod backup;
  4767. backup.Col = idx;
  4768. backup.BackupValue = g.Style.Colors[idx];
  4769. g.ColorModifiers.push_back(backup);
  4770. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  4771. }
  4772. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  4773. {
  4774. ImGuiContext& g = *GImGui;
  4775. ImGuiColMod backup;
  4776. backup.Col = idx;
  4777. backup.BackupValue = g.Style.Colors[idx];
  4778. g.ColorModifiers.push_back(backup);
  4779. g.Style.Colors[idx] = col;
  4780. }
  4781. void ImGui::PopStyleColor(int count)
  4782. {
  4783. ImGuiContext& g = *GImGui;
  4784. while (count > 0)
  4785. {
  4786. ImGuiColMod& backup = g.ColorModifiers.back();
  4787. g.Style.Colors[backup.Col] = backup.BackupValue;
  4788. g.ColorModifiers.pop_back();
  4789. count--;
  4790. }
  4791. }
  4792. struct ImGuiStyleVarInfo
  4793. {
  4794. ImGuiDataType Type;
  4795. ImU32 Offset;
  4796. void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  4797. };
  4798. static const ImGuiStyleVarInfo GStyleVarInfo[] =
  4799. {
  4800. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  4801. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  4802. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  4803. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
  4804. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  4805. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
  4806. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
  4807. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
  4808. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
  4809. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
  4810. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  4811. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  4812. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
  4813. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  4814. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  4815. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  4816. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
  4817. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
  4818. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  4819. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
  4820. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  4821. };
  4822. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  4823. {
  4824. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_);
  4825. IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_Count_);
  4826. return &GStyleVarInfo[idx];
  4827. }
  4828. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  4829. {
  4830. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  4831. if (var_info->Type == ImGuiDataType_Float)
  4832. {
  4833. ImGuiContext& g = *GImGui;
  4834. float* pvar = (float*)var_info->GetVarPtr(&g.Style);
  4835. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  4836. *pvar = val;
  4837. return;
  4838. }
  4839. IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
  4840. }
  4841. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  4842. {
  4843. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  4844. if (var_info->Type == ImGuiDataType_Float2)
  4845. {
  4846. ImGuiContext& g = *GImGui;
  4847. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
  4848. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  4849. *pvar = val;
  4850. return;
  4851. }
  4852. IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
  4853. }
  4854. void ImGui::PopStyleVar(int count)
  4855. {
  4856. ImGuiContext& g = *GImGui;
  4857. while (count > 0)
  4858. {
  4859. ImGuiStyleMod& backup = g.StyleModifiers.back();
  4860. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  4861. if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr(&g.Style)) = backup.BackupFloat[0];
  4862. else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr(&g.Style)) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]);
  4863. else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr(&g.Style)) = backup.BackupInt[0];
  4864. g.StyleModifiers.pop_back();
  4865. count--;
  4866. }
  4867. }
  4868. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  4869. {
  4870. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  4871. switch (idx)
  4872. {
  4873. case ImGuiCol_Text: return "Text";
  4874. case ImGuiCol_TextDisabled: return "TextDisabled";
  4875. case ImGuiCol_WindowBg: return "WindowBg";
  4876. case ImGuiCol_ChildBg: return "ChildBg";
  4877. case ImGuiCol_PopupBg: return "PopupBg";
  4878. case ImGuiCol_Border: return "Border";
  4879. case ImGuiCol_BorderShadow: return "BorderShadow";
  4880. case ImGuiCol_FrameBg: return "FrameBg";
  4881. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  4882. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  4883. case ImGuiCol_TitleBg: return "TitleBg";
  4884. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  4885. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  4886. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  4887. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  4888. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  4889. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  4890. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  4891. case ImGuiCol_CheckMark: return "CheckMark";
  4892. case ImGuiCol_SliderGrab: return "SliderGrab";
  4893. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  4894. case ImGuiCol_Button: return "Button";
  4895. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  4896. case ImGuiCol_ButtonActive: return "ButtonActive";
  4897. case ImGuiCol_Header: return "Header";
  4898. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  4899. case ImGuiCol_HeaderActive: return "HeaderActive";
  4900. case ImGuiCol_Separator: return "Separator";
  4901. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  4902. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  4903. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  4904. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  4905. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  4906. case ImGuiCol_CloseButton: return "CloseButton";
  4907. case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered";
  4908. case ImGuiCol_CloseButtonActive: return "CloseButtonActive";
  4909. case ImGuiCol_PlotLines: return "PlotLines";
  4910. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  4911. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  4912. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  4913. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  4914. case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
  4915. case ImGuiCol_DragDropTarget: return "DragDropTarget";
  4916. }
  4917. IM_ASSERT(0);
  4918. return "Unknown";
  4919. }
  4920. bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
  4921. {
  4922. if (window->RootWindow == potential_parent)
  4923. return true;
  4924. while (window != NULL)
  4925. {
  4926. if (window == potential_parent)
  4927. return true;
  4928. window = window->ParentWindow;
  4929. }
  4930. return false;
  4931. }
  4932. bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
  4933. {
  4934. IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
  4935. ImGuiContext& g = *GImGui;
  4936. if (flags & ImGuiHoveredFlags_AnyWindow)
  4937. {
  4938. if (g.HoveredWindow == NULL)
  4939. return false;
  4940. }
  4941. else
  4942. {
  4943. switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
  4944. {
  4945. case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
  4946. if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
  4947. return false;
  4948. break;
  4949. case ImGuiHoveredFlags_RootWindow:
  4950. if (g.HoveredWindow != g.CurrentWindow->RootWindow)
  4951. return false;
  4952. break;
  4953. case ImGuiHoveredFlags_ChildWindows:
  4954. if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
  4955. return false;
  4956. break;
  4957. default:
  4958. if (g.HoveredWindow != g.CurrentWindow)
  4959. return false;
  4960. break;
  4961. }
  4962. }
  4963. if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
  4964. return false;
  4965. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  4966. if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
  4967. return false;
  4968. return true;
  4969. }
  4970. bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
  4971. {
  4972. ImGuiContext& g = *GImGui;
  4973. IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
  4974. if (flags & ImGuiFocusedFlags_AnyWindow)
  4975. return g.NavWindow != NULL;
  4976. switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
  4977. {
  4978. case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
  4979. return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
  4980. case ImGuiFocusedFlags_RootWindow:
  4981. return g.NavWindow == g.CurrentWindow->RootWindow;
  4982. case ImGuiFocusedFlags_ChildWindows:
  4983. return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
  4984. default:
  4985. return g.NavWindow == g.CurrentWindow;
  4986. }
  4987. }
  4988. float ImGui::GetWindowWidth()
  4989. {
  4990. ImGuiWindow* window = GImGui->CurrentWindow;
  4991. return window->Size.x;
  4992. }
  4993. float ImGui::GetWindowHeight()
  4994. {
  4995. ImGuiWindow* window = GImGui->CurrentWindow;
  4996. return window->Size.y;
  4997. }
  4998. ImVec2 ImGui::GetWindowPos()
  4999. {
  5000. ImGuiContext& g = *GImGui;
  5001. ImGuiWindow* window = g.CurrentWindow;
  5002. return window->Pos;
  5003. }
  5004. static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
  5005. {
  5006. window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
  5007. window->Scroll.x = new_scroll_x;
  5008. window->DC.CursorMaxPos.x -= window->Scroll.x;
  5009. }
  5010. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
  5011. {
  5012. window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
  5013. window->Scroll.y = new_scroll_y;
  5014. window->DC.CursorMaxPos.y -= window->Scroll.y;
  5015. }
  5016. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  5017. {
  5018. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5019. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  5020. return;
  5021. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5022. window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
  5023. // Set
  5024. const ImVec2 old_pos = window->Pos;
  5025. window->PosFloat = pos;
  5026. window->Pos = ImFloor(pos);
  5027. 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
  5028. window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
  5029. }
  5030. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  5031. {
  5032. ImGuiWindow* window = GetCurrentWindowRead();
  5033. SetWindowPos(window, pos, cond);
  5034. }
  5035. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  5036. {
  5037. if (ImGuiWindow* window = FindWindowByName(name))
  5038. SetWindowPos(window, pos, cond);
  5039. }
  5040. ImVec2 ImGui::GetWindowSize()
  5041. {
  5042. ImGuiWindow* window = GetCurrentWindowRead();
  5043. return window->Size;
  5044. }
  5045. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  5046. {
  5047. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5048. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  5049. return;
  5050. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5051. // Set
  5052. if (size.x > 0.0f)
  5053. {
  5054. window->AutoFitFramesX = 0;
  5055. window->SizeFull.x = size.x;
  5056. }
  5057. else
  5058. {
  5059. window->AutoFitFramesX = 2;
  5060. window->AutoFitOnlyGrows = false;
  5061. }
  5062. if (size.y > 0.0f)
  5063. {
  5064. window->AutoFitFramesY = 0;
  5065. window->SizeFull.y = size.y;
  5066. }
  5067. else
  5068. {
  5069. window->AutoFitFramesY = 2;
  5070. window->AutoFitOnlyGrows = false;
  5071. }
  5072. }
  5073. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  5074. {
  5075. SetWindowSize(GImGui->CurrentWindow, size, cond);
  5076. }
  5077. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  5078. {
  5079. if (ImGuiWindow* window = FindWindowByName(name))
  5080. SetWindowSize(window, size, cond);
  5081. }
  5082. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  5083. {
  5084. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5085. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  5086. return;
  5087. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5088. // Set
  5089. window->Collapsed = collapsed;
  5090. }
  5091. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  5092. {
  5093. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  5094. }
  5095. bool ImGui::IsWindowCollapsed()
  5096. {
  5097. ImGuiWindow* window = GetCurrentWindowRead();
  5098. return window->Collapsed;
  5099. }
  5100. bool ImGui::IsWindowAppearing()
  5101. {
  5102. ImGuiWindow* window = GetCurrentWindowRead();
  5103. return window->Appearing;
  5104. }
  5105. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  5106. {
  5107. if (ImGuiWindow* window = FindWindowByName(name))
  5108. SetWindowCollapsed(window, collapsed, cond);
  5109. }
  5110. void ImGui::SetWindowFocus()
  5111. {
  5112. FocusWindow(GImGui->CurrentWindow);
  5113. }
  5114. void ImGui::SetWindowFocus(const char* name)
  5115. {
  5116. if (name)
  5117. {
  5118. if (ImGuiWindow* window = FindWindowByName(name))
  5119. FocusWindow(window);
  5120. }
  5121. else
  5122. {
  5123. FocusWindow(NULL);
  5124. }
  5125. }
  5126. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
  5127. {
  5128. ImGuiContext& g = *GImGui;
  5129. g.NextWindowData.PosVal = pos;
  5130. g.NextWindowData.PosPivotVal = pivot;
  5131. g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
  5132. }
  5133. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  5134. {
  5135. ImGuiContext& g = *GImGui;
  5136. g.NextWindowData.SizeVal = size;
  5137. g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
  5138. }
  5139. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
  5140. {
  5141. ImGuiContext& g = *GImGui;
  5142. g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
  5143. g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
  5144. g.NextWindowData.SizeCallback = custom_callback;
  5145. g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
  5146. }
  5147. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  5148. {
  5149. ImGuiContext& g = *GImGui;
  5150. g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
  5151. g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
  5152. }
  5153. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  5154. {
  5155. ImGuiContext& g = *GImGui;
  5156. g.NextWindowData.CollapsedVal = collapsed;
  5157. g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
  5158. }
  5159. void ImGui::SetNextWindowFocus()
  5160. {
  5161. ImGuiContext& g = *GImGui;
  5162. g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
  5163. }
  5164. void ImGui::SetNextWindowBgAlpha(float alpha)
  5165. {
  5166. ImGuiContext& g = *GImGui;
  5167. g.NextWindowData.BgAlphaVal = alpha;
  5168. g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
  5169. }
  5170. // In window space (not screen space!)
  5171. ImVec2 ImGui::GetContentRegionMax()
  5172. {
  5173. ImGuiWindow* window = GetCurrentWindowRead();
  5174. ImVec2 mx = window->ContentsRegionRect.Max;
  5175. if (window->DC.ColumnsSet)
  5176. mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x;
  5177. return mx;
  5178. }
  5179. ImVec2 ImGui::GetContentRegionAvail()
  5180. {
  5181. ImGuiWindow* window = GetCurrentWindowRead();
  5182. return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
  5183. }
  5184. float ImGui::GetContentRegionAvailWidth()
  5185. {
  5186. return GetContentRegionAvail().x;
  5187. }
  5188. // In window space (not screen space!)
  5189. ImVec2 ImGui::GetWindowContentRegionMin()
  5190. {
  5191. ImGuiWindow* window = GetCurrentWindowRead();
  5192. return window->ContentsRegionRect.Min;
  5193. }
  5194. ImVec2 ImGui::GetWindowContentRegionMax()
  5195. {
  5196. ImGuiWindow* window = GetCurrentWindowRead();
  5197. return window->ContentsRegionRect.Max;
  5198. }
  5199. float ImGui::GetWindowContentRegionWidth()
  5200. {
  5201. ImGuiWindow* window = GetCurrentWindowRead();
  5202. return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x;
  5203. }
  5204. float ImGui::GetTextLineHeight()
  5205. {
  5206. ImGuiContext& g = *GImGui;
  5207. return g.FontSize;
  5208. }
  5209. float ImGui::GetTextLineHeightWithSpacing()
  5210. {
  5211. ImGuiContext& g = *GImGui;
  5212. return g.FontSize + g.Style.ItemSpacing.y;
  5213. }
  5214. float ImGui::GetFrameHeight()
  5215. {
  5216. ImGuiContext& g = *GImGui;
  5217. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  5218. }
  5219. float ImGui::GetFrameHeightWithSpacing()
  5220. {
  5221. ImGuiContext& g = *GImGui;
  5222. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  5223. }
  5224. ImDrawList* ImGui::GetWindowDrawList()
  5225. {
  5226. ImGuiWindow* window = GetCurrentWindow();
  5227. return window->DrawList;
  5228. }
  5229. ImFont* ImGui::GetFont()
  5230. {
  5231. return GImGui->Font;
  5232. }
  5233. float ImGui::GetFontSize()
  5234. {
  5235. return GImGui->FontSize;
  5236. }
  5237. ImVec2 ImGui::GetFontTexUvWhitePixel()
  5238. {
  5239. return GImGui->DrawListSharedData.TexUvWhitePixel;
  5240. }
  5241. void ImGui::SetWindowFontScale(float scale)
  5242. {
  5243. ImGuiContext& g = *GImGui;
  5244. ImGuiWindow* window = GetCurrentWindow();
  5245. window->FontWindowScale = scale;
  5246. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  5247. }
  5248. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  5249. // 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'.
  5250. ImVec2 ImGui::GetCursorPos()
  5251. {
  5252. ImGuiWindow* window = GetCurrentWindowRead();
  5253. return window->DC.CursorPos - window->Pos + window->Scroll;
  5254. }
  5255. float ImGui::GetCursorPosX()
  5256. {
  5257. ImGuiWindow* window = GetCurrentWindowRead();
  5258. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  5259. }
  5260. float ImGui::GetCursorPosY()
  5261. {
  5262. ImGuiWindow* window = GetCurrentWindowRead();
  5263. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  5264. }
  5265. void ImGui::SetCursorPos(const ImVec2& local_pos)
  5266. {
  5267. ImGuiWindow* window = GetCurrentWindow();
  5268. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  5269. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5270. }
  5271. void ImGui::SetCursorPosX(float x)
  5272. {
  5273. ImGuiWindow* window = GetCurrentWindow();
  5274. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  5275. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  5276. }
  5277. void ImGui::SetCursorPosY(float y)
  5278. {
  5279. ImGuiWindow* window = GetCurrentWindow();
  5280. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  5281. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  5282. }
  5283. ImVec2 ImGui::GetCursorStartPos()
  5284. {
  5285. ImGuiWindow* window = GetCurrentWindowRead();
  5286. return window->DC.CursorStartPos - window->Pos;
  5287. }
  5288. ImVec2 ImGui::GetCursorScreenPos()
  5289. {
  5290. ImGuiWindow* window = GetCurrentWindowRead();
  5291. return window->DC.CursorPos;
  5292. }
  5293. void ImGui::SetCursorScreenPos(const ImVec2& screen_pos)
  5294. {
  5295. ImGuiWindow* window = GetCurrentWindow();
  5296. window->DC.CursorPos = screen_pos;
  5297. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5298. }
  5299. float ImGui::GetScrollX()
  5300. {
  5301. return GImGui->CurrentWindow->Scroll.x;
  5302. }
  5303. float ImGui::GetScrollY()
  5304. {
  5305. return GImGui->CurrentWindow->Scroll.y;
  5306. }
  5307. float ImGui::GetScrollMaxX()
  5308. {
  5309. return GetScrollMaxX(GImGui->CurrentWindow);
  5310. }
  5311. float ImGui::GetScrollMaxY()
  5312. {
  5313. return GetScrollMaxY(GImGui->CurrentWindow);
  5314. }
  5315. void ImGui::SetScrollX(float scroll_x)
  5316. {
  5317. ImGuiWindow* window = GetCurrentWindow();
  5318. window->ScrollTarget.x = scroll_x;
  5319. window->ScrollTargetCenterRatio.x = 0.0f;
  5320. }
  5321. void ImGui::SetScrollY(float scroll_y)
  5322. {
  5323. ImGuiWindow* window = GetCurrentWindow();
  5324. window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
  5325. window->ScrollTargetCenterRatio.y = 0.0f;
  5326. }
  5327. void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
  5328. {
  5329. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  5330. ImGuiWindow* window = GetCurrentWindow();
  5331. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  5332. window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
  5333. window->ScrollTargetCenterRatio.y = center_y_ratio;
  5334. // Minor hack to to make scrolling to top/bottom of window take account of WindowPadding, it looks more right to the user this way
  5335. if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y)
  5336. window->ScrollTarget.y = 0.0f;
  5337. else if (center_y_ratio >= 1.0f && window->ScrollTarget.y >= window->SizeContents.y - window->WindowPadding.y + GImGui->Style.ItemSpacing.y)
  5338. window->ScrollTarget.y = window->SizeContents.y;
  5339. }
  5340. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  5341. void ImGui::SetScrollHere(float center_y_ratio)
  5342. {
  5343. ImGuiWindow* window = GetCurrentWindow();
  5344. float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
  5345. target_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.
  5346. SetScrollFromPosY(target_y, center_y_ratio);
  5347. }
  5348. // FIXME-NAV: This function is a placeholder for the upcoming Navigation branch + Focusing features.
  5349. // In the current branch this function will only set the scrolling, in the navigation branch it will also set your navigation cursor.
  5350. // Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHere()" when applicable.
  5351. void ImGui::SetItemDefaultFocus()
  5352. {
  5353. if (IsWindowAppearing())
  5354. SetScrollHere();
  5355. }
  5356. void ImGui::SetKeyboardFocusHere(int offset)
  5357. {
  5358. IM_ASSERT(offset >= -1); // -1 is allowed but not below
  5359. ImGuiWindow* window = GetCurrentWindow();
  5360. window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
  5361. window->FocusIdxTabRequestNext = INT_MAX;
  5362. }
  5363. void ImGui::SetStateStorage(ImGuiStorage* tree)
  5364. {
  5365. ImGuiWindow* window = GetCurrentWindow();
  5366. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  5367. }
  5368. ImGuiStorage* ImGui::GetStateStorage()
  5369. {
  5370. ImGuiWindow* window = GetCurrentWindowRead();
  5371. return window->DC.StateStorage;
  5372. }
  5373. void ImGui::TextV(const char* fmt, va_list args)
  5374. {
  5375. ImGuiWindow* window = GetCurrentWindow();
  5376. if (window->SkipItems)
  5377. return;
  5378. ImGuiContext& g = *GImGui;
  5379. const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5380. TextUnformatted(g.TempBuffer, text_end);
  5381. }
  5382. void ImGui::Text(const char* fmt, ...)
  5383. {
  5384. va_list args;
  5385. va_start(args, fmt);
  5386. TextV(fmt, args);
  5387. va_end(args);
  5388. }
  5389. void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
  5390. {
  5391. PushStyleColor(ImGuiCol_Text, col);
  5392. TextV(fmt, args);
  5393. PopStyleColor();
  5394. }
  5395. void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
  5396. {
  5397. va_list args;
  5398. va_start(args, fmt);
  5399. TextColoredV(col, fmt, args);
  5400. va_end(args);
  5401. }
  5402. void ImGui::TextDisabledV(const char* fmt, va_list args)
  5403. {
  5404. PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
  5405. TextV(fmt, args);
  5406. PopStyleColor();
  5407. }
  5408. void ImGui::TextDisabled(const char* fmt, ...)
  5409. {
  5410. va_list args;
  5411. va_start(args, fmt);
  5412. TextDisabledV(fmt, args);
  5413. va_end(args);
  5414. }
  5415. void ImGui::TextWrappedV(const char* fmt, va_list args)
  5416. {
  5417. bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set
  5418. if (need_wrap) PushTextWrapPos(0.0f);
  5419. TextV(fmt, args);
  5420. if (need_wrap) PopTextWrapPos();
  5421. }
  5422. void ImGui::TextWrapped(const char* fmt, ...)
  5423. {
  5424. va_list args;
  5425. va_start(args, fmt);
  5426. TextWrappedV(fmt, args);
  5427. va_end(args);
  5428. }
  5429. void ImGui::TextUnformatted(const char* text, const char* text_end)
  5430. {
  5431. ImGuiWindow* window = GetCurrentWindow();
  5432. if (window->SkipItems)
  5433. return;
  5434. ImGuiContext& g = *GImGui;
  5435. IM_ASSERT(text != NULL);
  5436. const char* text_begin = text;
  5437. if (text_end == NULL)
  5438. text_end = text + strlen(text); // FIXME-OPT
  5439. const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
  5440. const float wrap_pos_x = window->DC.TextWrapPos;
  5441. const bool wrap_enabled = wrap_pos_x >= 0.0f;
  5442. if (text_end - text > 2000 && !wrap_enabled)
  5443. {
  5444. // Long text!
  5445. // Perform manual coarse clipping to optimize for long multi-line text
  5446. // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
  5447. // 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.
  5448. const char* line = text;
  5449. const float line_height = GetTextLineHeight();
  5450. const ImRect clip_rect = window->ClipRect;
  5451. ImVec2 text_size(0,0);
  5452. if (text_pos.y <= clip_rect.Max.y)
  5453. {
  5454. ImVec2 pos = text_pos;
  5455. // Lines to skip (can't skip when logging text)
  5456. if (!g.LogEnabled)
  5457. {
  5458. int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height);
  5459. if (lines_skippable > 0)
  5460. {
  5461. int lines_skipped = 0;
  5462. while (line < text_end && lines_skipped < lines_skippable)
  5463. {
  5464. const char* line_end = strchr(line, '\n');
  5465. if (!line_end)
  5466. line_end = text_end;
  5467. line = line_end + 1;
  5468. lines_skipped++;
  5469. }
  5470. pos.y += lines_skipped * line_height;
  5471. }
  5472. }
  5473. // Lines to render
  5474. if (line < text_end)
  5475. {
  5476. ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
  5477. while (line < text_end)
  5478. {
  5479. const char* line_end = strchr(line, '\n');
  5480. if (IsClippedEx(line_rect, 0, false))
  5481. break;
  5482. const ImVec2 line_size = CalcTextSize(line, line_end, false);
  5483. text_size.x = ImMax(text_size.x, line_size.x);
  5484. RenderText(pos, line, line_end, false);
  5485. if (!line_end)
  5486. line_end = text_end;
  5487. line = line_end + 1;
  5488. line_rect.Min.y += line_height;
  5489. line_rect.Max.y += line_height;
  5490. pos.y += line_height;
  5491. }
  5492. // Count remaining lines
  5493. int lines_skipped = 0;
  5494. while (line < text_end)
  5495. {
  5496. const char* line_end = strchr(line, '\n');
  5497. if (!line_end)
  5498. line_end = text_end;
  5499. line = line_end + 1;
  5500. lines_skipped++;
  5501. }
  5502. pos.y += lines_skipped * line_height;
  5503. }
  5504. text_size.y += (pos - text_pos).y;
  5505. }
  5506. ImRect bb(text_pos, text_pos + text_size);
  5507. ItemSize(bb);
  5508. ItemAdd(bb, 0);
  5509. }
  5510. else
  5511. {
  5512. const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
  5513. const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
  5514. // Account of baseline offset
  5515. ImRect bb(text_pos, text_pos + text_size);
  5516. ItemSize(text_size);
  5517. if (!ItemAdd(bb, 0))
  5518. return;
  5519. // Render (we don't hide text after ## in this end-user function)
  5520. RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
  5521. }
  5522. }
  5523. void ImGui::AlignTextToFramePadding()
  5524. {
  5525. ImGuiWindow* window = GetCurrentWindow();
  5526. if (window->SkipItems)
  5527. return;
  5528. ImGuiContext& g = *GImGui;
  5529. window->DC.CurrentLineHeight = ImMax(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y * 2);
  5530. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  5531. }
  5532. // Add a label+text combo aligned to other label+value widgets
  5533. void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
  5534. {
  5535. ImGuiWindow* window = GetCurrentWindow();
  5536. if (window->SkipItems)
  5537. return;
  5538. ImGuiContext& g = *GImGui;
  5539. const ImGuiStyle& style = g.Style;
  5540. const float w = CalcItemWidth();
  5541. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5542. const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
  5543. 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);
  5544. ItemSize(total_bb, style.FramePadding.y);
  5545. if (!ItemAdd(total_bb, 0))
  5546. return;
  5547. // Render
  5548. const char* value_text_begin = &g.TempBuffer[0];
  5549. const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5550. RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
  5551. if (label_size.x > 0.0f)
  5552. RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
  5553. }
  5554. void ImGui::LabelText(const char* label, const char* fmt, ...)
  5555. {
  5556. va_list args;
  5557. va_start(args, fmt);
  5558. LabelTextV(label, fmt, args);
  5559. va_end(args);
  5560. }
  5561. bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
  5562. {
  5563. ImGuiContext& g = *GImGui;
  5564. ImGuiWindow* window = GetCurrentWindow();
  5565. if (flags & ImGuiButtonFlags_Disabled)
  5566. {
  5567. if (out_hovered) *out_hovered = false;
  5568. if (out_held) *out_held = false;
  5569. if (g.ActiveId == id) ClearActiveID();
  5570. return false;
  5571. }
  5572. // Default behavior requires click+release on same spot
  5573. if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
  5574. flags |= ImGuiButtonFlags_PressedOnClickRelease;
  5575. ImGuiWindow* backup_hovered_window = g.HoveredWindow;
  5576. if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
  5577. g.HoveredWindow = window;
  5578. bool pressed = false;
  5579. bool hovered = ItemHoverable(bb, id);
  5580. // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
  5581. if ((flags & ImGuiButtonFlags_PressedOnDragDropHold) && g.DragDropActive && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
  5582. if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  5583. {
  5584. hovered = true;
  5585. SetHoveredID(id);
  5586. if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy
  5587. {
  5588. pressed = true;
  5589. FocusWindow(window);
  5590. }
  5591. }
  5592. if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
  5593. g.HoveredWindow = backup_hovered_window;
  5594. // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
  5595. if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
  5596. hovered = false;
  5597. if (hovered)
  5598. {
  5599. if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
  5600. {
  5601. // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
  5602. // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
  5603. // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
  5604. // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
  5605. // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
  5606. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
  5607. {
  5608. SetActiveID(id, window); // Hold on ID
  5609. FocusWindow(window);
  5610. }
  5611. if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
  5612. {
  5613. pressed = true;
  5614. if (flags & ImGuiButtonFlags_NoHoldingActiveID)
  5615. ClearActiveID();
  5616. else
  5617. SetActiveID(id, window); // Hold on ID
  5618. FocusWindow(window);
  5619. }
  5620. if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
  5621. {
  5622. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  5623. pressed = true;
  5624. ClearActiveID();
  5625. }
  5626. // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
  5627. // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
  5628. if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
  5629. pressed = true;
  5630. }
  5631. }
  5632. bool held = false;
  5633. if (g.ActiveId == id)
  5634. {
  5635. if (g.ActiveIdIsJustActivated)
  5636. g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
  5637. if (g.IO.MouseDown[0])
  5638. {
  5639. held = true;
  5640. }
  5641. else
  5642. {
  5643. if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
  5644. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  5645. if (!g.DragDropActive)
  5646. pressed = true;
  5647. ClearActiveID();
  5648. }
  5649. }
  5650. if (out_hovered) *out_hovered = hovered;
  5651. if (out_held) *out_held = held;
  5652. return pressed;
  5653. }
  5654. bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
  5655. {
  5656. ImGuiWindow* window = GetCurrentWindow();
  5657. if (window->SkipItems)
  5658. return false;
  5659. ImGuiContext& g = *GImGui;
  5660. const ImGuiStyle& style = g.Style;
  5661. const ImGuiID id = window->GetID(label);
  5662. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5663. ImVec2 pos = window->DC.CursorPos;
  5664. if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
  5665. pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;
  5666. ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
  5667. const ImRect bb(pos, pos + size);
  5668. ItemSize(bb, style.FramePadding.y);
  5669. if (!ItemAdd(bb, id))
  5670. return false;
  5671. if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
  5672. flags |= ImGuiButtonFlags_Repeat;
  5673. bool hovered, held;
  5674. bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
  5675. // Render
  5676. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5677. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  5678. RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
  5679. // Automatically close popups
  5680. //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  5681. // CloseCurrentPopup();
  5682. return pressed;
  5683. }
  5684. bool ImGui::Button(const char* label, const ImVec2& size_arg)
  5685. {
  5686. return ButtonEx(label, size_arg, 0);
  5687. }
  5688. // Small buttons fits within text without additional vertical spacing.
  5689. bool ImGui::SmallButton(const char* label)
  5690. {
  5691. ImGuiContext& g = *GImGui;
  5692. float backup_padding_y = g.Style.FramePadding.y;
  5693. g.Style.FramePadding.y = 0.0f;
  5694. bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine);
  5695. g.Style.FramePadding.y = backup_padding_y;
  5696. return pressed;
  5697. }
  5698. // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
  5699. // 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)
  5700. bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
  5701. {
  5702. ImGuiWindow* window = GetCurrentWindow();
  5703. if (window->SkipItems)
  5704. return false;
  5705. const ImGuiID id = window->GetID(str_id);
  5706. ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
  5707. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  5708. ItemSize(bb);
  5709. if (!ItemAdd(bb, id))
  5710. return false;
  5711. bool hovered, held;
  5712. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5713. return pressed;
  5714. }
  5715. // Button to close a window
  5716. bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
  5717. {
  5718. ImGuiWindow* window = GetCurrentWindow();
  5719. const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
  5720. bool hovered, held;
  5721. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5722. // Render
  5723. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
  5724. ImVec2 center = bb.GetCenter();
  5725. window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12);
  5726. const float cross_extent = (radius * 0.7071f) - 1.0f;
  5727. if (hovered)
  5728. {
  5729. center -= ImVec2(0.5f, 0.5f);
  5730. window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text));
  5731. window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text));
  5732. }
  5733. return pressed;
  5734. }
  5735. // [Internal]
  5736. bool ImGui::ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags)
  5737. {
  5738. ImGuiContext& g = *GImGui;
  5739. ImGuiWindow* window = g.CurrentWindow;
  5740. if (window->SkipItems)
  5741. return false;
  5742. const ImGuiStyle& style = g.Style;
  5743. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + padding.x * 2.0f, g.FontSize + padding.y * 2.0f));
  5744. ItemSize(bb, style.FramePadding.y);
  5745. if (!ItemAdd(bb, id))
  5746. return false;
  5747. bool hovered, held;
  5748. bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
  5749. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5750. #ifdef IMGUI_HAS_NAV
  5751. RenderNavHighlight(bb, id);
  5752. #endif
  5753. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  5754. RenderTriangle(bb.Min + padding, dir, 1.0f);
  5755. return pressed;
  5756. }
  5757. void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
  5758. {
  5759. ImGuiWindow* window = GetCurrentWindow();
  5760. if (window->SkipItems)
  5761. return;
  5762. ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  5763. if (border_col.w > 0.0f)
  5764. bb.Max += ImVec2(2,2);
  5765. ItemSize(bb);
  5766. if (!ItemAdd(bb, 0))
  5767. return;
  5768. if (border_col.w > 0.0f)
  5769. {
  5770. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
  5771. window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col));
  5772. }
  5773. else
  5774. {
  5775. window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
  5776. }
  5777. }
  5778. // frame_padding < 0: uses FramePadding from style (default)
  5779. // frame_padding = 0: no framing
  5780. // frame_padding > 0: set framing size
  5781. // The color used are the button colors.
  5782. 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)
  5783. {
  5784. ImGuiWindow* window = GetCurrentWindow();
  5785. if (window->SkipItems)
  5786. return false;
  5787. ImGuiContext& g = *GImGui;
  5788. const ImGuiStyle& style = g.Style;
  5789. // Default to using texture ID as ID. User can still push string/integer prefixes.
  5790. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
  5791. PushID((void *)user_texture_id);
  5792. const ImGuiID id = window->GetID("#image");
  5793. PopID();
  5794. const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
  5795. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2);
  5796. const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
  5797. ItemSize(bb);
  5798. if (!ItemAdd(bb, id))
  5799. return false;
  5800. bool hovered, held;
  5801. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5802. // Render
  5803. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5804. RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
  5805. if (bg_col.w > 0.0f)
  5806. window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
  5807. window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
  5808. return pressed;
  5809. }
  5810. // Start logging ImGui output to TTY
  5811. void ImGui::LogToTTY(int max_depth)
  5812. {
  5813. ImGuiContext& g = *GImGui;
  5814. if (g.LogEnabled)
  5815. return;
  5816. ImGuiWindow* window = g.CurrentWindow;
  5817. IM_ASSERT(g.LogFile == NULL);
  5818. g.LogFile = stdout;
  5819. g.LogEnabled = true;
  5820. g.LogStartDepth = window->DC.TreeDepth;
  5821. if (max_depth >= 0)
  5822. g.LogAutoExpandMaxDepth = max_depth;
  5823. }
  5824. // Start logging ImGui output to given file
  5825. void ImGui::LogToFile(int max_depth, const char* filename)
  5826. {
  5827. ImGuiContext& g = *GImGui;
  5828. if (g.LogEnabled)
  5829. return;
  5830. ImGuiWindow* window = g.CurrentWindow;
  5831. if (!filename)
  5832. {
  5833. filename = g.IO.LogFilename;
  5834. if (!filename)
  5835. return;
  5836. }
  5837. IM_ASSERT(g.LogFile == NULL);
  5838. g.LogFile = ImFileOpen(filename, "ab");
  5839. if (!g.LogFile)
  5840. {
  5841. IM_ASSERT(g.LogFile != NULL); // Consider this an error
  5842. return;
  5843. }
  5844. g.LogEnabled = true;
  5845. g.LogStartDepth = window->DC.TreeDepth;
  5846. if (max_depth >= 0)
  5847. g.LogAutoExpandMaxDepth = max_depth;
  5848. }
  5849. // Start logging ImGui output to clipboard
  5850. void ImGui::LogToClipboard(int max_depth)
  5851. {
  5852. ImGuiContext& g = *GImGui;
  5853. if (g.LogEnabled)
  5854. return;
  5855. ImGuiWindow* window = g.CurrentWindow;
  5856. IM_ASSERT(g.LogFile == NULL);
  5857. g.LogFile = NULL;
  5858. g.LogEnabled = true;
  5859. g.LogStartDepth = window->DC.TreeDepth;
  5860. if (max_depth >= 0)
  5861. g.LogAutoExpandMaxDepth = max_depth;
  5862. }
  5863. void ImGui::LogFinish()
  5864. {
  5865. ImGuiContext& g = *GImGui;
  5866. if (!g.LogEnabled)
  5867. return;
  5868. LogText(IM_NEWLINE);
  5869. if (g.LogFile != NULL)
  5870. {
  5871. if (g.LogFile == stdout)
  5872. fflush(g.LogFile);
  5873. else
  5874. fclose(g.LogFile);
  5875. g.LogFile = NULL;
  5876. }
  5877. if (g.LogClipboard->size() > 1)
  5878. {
  5879. SetClipboardText(g.LogClipboard->begin());
  5880. g.LogClipboard->clear();
  5881. }
  5882. g.LogEnabled = false;
  5883. }
  5884. // Helper to display logging buttons
  5885. void ImGui::LogButtons()
  5886. {
  5887. ImGuiContext& g = *GImGui;
  5888. PushID("LogButtons");
  5889. const bool log_to_tty = Button("Log To TTY"); SameLine();
  5890. const bool log_to_file = Button("Log To File"); SameLine();
  5891. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  5892. PushItemWidth(80.0f);
  5893. PushAllowKeyboardFocus(false);
  5894. SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
  5895. PopAllowKeyboardFocus();
  5896. PopItemWidth();
  5897. PopID();
  5898. // Start logging at the end of the function so that the buttons don't appear in the log
  5899. if (log_to_tty)
  5900. LogToTTY(g.LogAutoExpandMaxDepth);
  5901. if (log_to_file)
  5902. LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
  5903. if (log_to_clipboard)
  5904. LogToClipboard(g.LogAutoExpandMaxDepth);
  5905. }
  5906. bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
  5907. {
  5908. if (flags & ImGuiTreeNodeFlags_Leaf)
  5909. return true;
  5910. // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions)
  5911. ImGuiContext& g = *GImGui;
  5912. ImGuiWindow* window = g.CurrentWindow;
  5913. ImGuiStorage* storage = window->DC.StateStorage;
  5914. bool is_open;
  5915. if (g.NextTreeNodeOpenCond != 0)
  5916. {
  5917. if (g.NextTreeNodeOpenCond & ImGuiCond_Always)
  5918. {
  5919. is_open = g.NextTreeNodeOpenVal;
  5920. storage->SetInt(id, is_open);
  5921. }
  5922. else
  5923. {
  5924. // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
  5925. const int stored_value = storage->GetInt(id, -1);
  5926. if (stored_value == -1)
  5927. {
  5928. is_open = g.NextTreeNodeOpenVal;
  5929. storage->SetInt(id, is_open);
  5930. }
  5931. else
  5932. {
  5933. is_open = stored_value != 0;
  5934. }
  5935. }
  5936. g.NextTreeNodeOpenCond = 0;
  5937. }
  5938. else
  5939. {
  5940. is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
  5941. }
  5942. // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
  5943. // NB- If we are above max depth we still allow manually opened nodes to be logged.
  5944. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth)
  5945. is_open = true;
  5946. return is_open;
  5947. }
  5948. bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
  5949. {
  5950. ImGuiWindow* window = GetCurrentWindow();
  5951. if (window->SkipItems)
  5952. return false;
  5953. ImGuiContext& g = *GImGui;
  5954. const ImGuiStyle& style = g.Style;
  5955. const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
  5956. const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
  5957. if (!label_end)
  5958. label_end = FindRenderedTextEnd(label);
  5959. const ImVec2 label_size = CalcTextSize(label, label_end, false);
  5960. // We vertically grow up to current line height up the typical widget height.
  5961. const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
  5962. const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
  5963. ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
  5964. if (display_frame)
  5965. {
  5966. // Framed header expand a little outside the default padding
  5967. frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
  5968. frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
  5969. }
  5970. const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing
  5971. const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
  5972. ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
  5973. // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
  5974. // (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
  5975. const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y);
  5976. bool is_open = TreeNodeBehaviorIsOpen(id, flags);
  5977. bool item_add = ItemAdd(interact_bb, id);
  5978. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
  5979. window->DC.LastItemDisplayRect = frame_bb;
  5980. if (!item_add)
  5981. {
  5982. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  5983. TreePushRawID(id);
  5984. return is_open;
  5985. }
  5986. // Flags that affects opening behavior:
  5987. // - 0(default) ..................... single-click anywhere to open
  5988. // - OpenOnDoubleClick .............. double-click anywhere to open
  5989. // - OpenOnArrow .................... single-click on arrow to open
  5990. // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
  5991. ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0);
  5992. if (!(flags & ImGuiTreeNodeFlags_Leaf))
  5993. button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
  5994. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  5995. button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
  5996. bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
  5997. if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf))
  5998. {
  5999. bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick));
  6000. if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
  6001. toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y));
  6002. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  6003. toggled |= g.IO.MouseDoubleClicked[0];
  6004. if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
  6005. toggled = false;
  6006. if (toggled)
  6007. {
  6008. is_open = !is_open;
  6009. window->DC.StateStorage->SetInt(id, is_open);
  6010. }
  6011. }
  6012. if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
  6013. SetItemAllowOverlap();
  6014. // Render
  6015. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  6016. const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
  6017. if (display_frame)
  6018. {
  6019. // Framed type
  6020. RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding);
  6021. RenderTriangle(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
  6022. if (g.LogEnabled)
  6023. {
  6024. // 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.
  6025. const char log_prefix[] = "\n##";
  6026. const char log_suffix[] = "##";
  6027. LogRenderedText(&text_pos, log_prefix, log_prefix+3);
  6028. RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
  6029. LogRenderedText(&text_pos, log_suffix+1, log_suffix+3);
  6030. }
  6031. else
  6032. {
  6033. RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
  6034. }
  6035. }
  6036. else
  6037. {
  6038. // Unframed typed for tree nodes
  6039. if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
  6040. RenderFrame(frame_bb.Min, frame_bb.Max, col, false);
  6041. if (flags & ImGuiTreeNodeFlags_Bullet)
  6042. RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
  6043. else if (!(flags & ImGuiTreeNodeFlags_Leaf))
  6044. RenderTriangle(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
  6045. if (g.LogEnabled)
  6046. LogRenderedText(&text_pos, ">");
  6047. RenderText(text_pos, label, label_end, false);
  6048. }
  6049. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  6050. TreePushRawID(id);
  6051. return is_open;
  6052. }
  6053. // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
  6054. // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
  6055. bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
  6056. {
  6057. ImGuiWindow* window = GetCurrentWindow();
  6058. if (window->SkipItems)
  6059. return false;
  6060. return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
  6061. }
  6062. bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
  6063. {
  6064. ImGuiWindow* window = GetCurrentWindow();
  6065. if (window->SkipItems)
  6066. return false;
  6067. if (p_open && !*p_open)
  6068. return false;
  6069. ImGuiID id = window->GetID(label);
  6070. bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label);
  6071. if (p_open)
  6072. {
  6073. // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
  6074. ImGuiContext& g = *GImGui;
  6075. float button_sz = g.FontSize * 0.5f;
  6076. ImGuiItemHoveredDataBackup last_item_backup;
  6077. if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz))
  6078. *p_open = false;
  6079. last_item_backup.Restore();
  6080. }
  6081. return is_open;
  6082. }
  6083. bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
  6084. {
  6085. ImGuiWindow* window = GetCurrentWindow();
  6086. if (window->SkipItems)
  6087. return false;
  6088. return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
  6089. }
  6090. bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  6091. {
  6092. ImGuiWindow* window = GetCurrentWindow();
  6093. if (window->SkipItems)
  6094. return false;
  6095. ImGuiContext& g = *GImGui;
  6096. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6097. return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
  6098. }
  6099. bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  6100. {
  6101. ImGuiWindow* window = GetCurrentWindow();
  6102. if (window->SkipItems)
  6103. return false;
  6104. ImGuiContext& g = *GImGui;
  6105. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6106. return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
  6107. }
  6108. bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
  6109. {
  6110. return TreeNodeExV(str_id, 0, fmt, args);
  6111. }
  6112. bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
  6113. {
  6114. return TreeNodeExV(ptr_id, 0, fmt, args);
  6115. }
  6116. bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  6117. {
  6118. va_list args;
  6119. va_start(args, fmt);
  6120. bool is_open = TreeNodeExV(str_id, flags, fmt, args);
  6121. va_end(args);
  6122. return is_open;
  6123. }
  6124. bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  6125. {
  6126. va_list args;
  6127. va_start(args, fmt);
  6128. bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
  6129. va_end(args);
  6130. return is_open;
  6131. }
  6132. bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
  6133. {
  6134. va_list args;
  6135. va_start(args, fmt);
  6136. bool is_open = TreeNodeExV(str_id, 0, fmt, args);
  6137. va_end(args);
  6138. return is_open;
  6139. }
  6140. bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
  6141. {
  6142. va_list args;
  6143. va_start(args, fmt);
  6144. bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
  6145. va_end(args);
  6146. return is_open;
  6147. }
  6148. bool ImGui::TreeNode(const char* label)
  6149. {
  6150. ImGuiWindow* window = GetCurrentWindow();
  6151. if (window->SkipItems)
  6152. return false;
  6153. return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
  6154. }
  6155. void ImGui::TreeAdvanceToLabelPos()
  6156. {
  6157. ImGuiContext& g = *GImGui;
  6158. g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
  6159. }
  6160. // Horizontal distance preceding label when using TreeNode() or Bullet()
  6161. float ImGui::GetTreeNodeToLabelSpacing()
  6162. {
  6163. ImGuiContext& g = *GImGui;
  6164. return g.FontSize + (g.Style.FramePadding.x * 2.0f);
  6165. }
  6166. void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond)
  6167. {
  6168. ImGuiContext& g = *GImGui;
  6169. if (g.CurrentWindow->SkipItems)
  6170. return;
  6171. g.NextTreeNodeOpenVal = is_open;
  6172. g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
  6173. }
  6174. void ImGui::PushID(const char* str_id)
  6175. {
  6176. ImGuiWindow* window = GetCurrentWindowRead();
  6177. window->IDStack.push_back(window->GetID(str_id));
  6178. }
  6179. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  6180. {
  6181. ImGuiWindow* window = GetCurrentWindowRead();
  6182. window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
  6183. }
  6184. void ImGui::PushID(const void* ptr_id)
  6185. {
  6186. ImGuiWindow* window = GetCurrentWindowRead();
  6187. window->IDStack.push_back(window->GetID(ptr_id));
  6188. }
  6189. void ImGui::PushID(int int_id)
  6190. {
  6191. const void* ptr_id = (void*)(intptr_t)int_id;
  6192. ImGuiWindow* window = GetCurrentWindowRead();
  6193. window->IDStack.push_back(window->GetID(ptr_id));
  6194. }
  6195. void ImGui::PopID()
  6196. {
  6197. ImGuiWindow* window = GetCurrentWindowRead();
  6198. window->IDStack.pop_back();
  6199. }
  6200. ImGuiID ImGui::GetID(const char* str_id)
  6201. {
  6202. return GImGui->CurrentWindow->GetID(str_id);
  6203. }
  6204. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  6205. {
  6206. return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
  6207. }
  6208. ImGuiID ImGui::GetID(const void* ptr_id)
  6209. {
  6210. return GImGui->CurrentWindow->GetID(ptr_id);
  6211. }
  6212. void ImGui::Bullet()
  6213. {
  6214. ImGuiWindow* window = GetCurrentWindow();
  6215. if (window->SkipItems)
  6216. return;
  6217. ImGuiContext& g = *GImGui;
  6218. const ImGuiStyle& style = g.Style;
  6219. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  6220. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
  6221. ItemSize(bb);
  6222. if (!ItemAdd(bb, 0))
  6223. {
  6224. SameLine(0, style.FramePadding.x*2);
  6225. return;
  6226. }
  6227. // Render and stay on same line
  6228. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  6229. SameLine(0, style.FramePadding.x*2);
  6230. }
  6231. // Text with a little bullet aligned to the typical tree node.
  6232. void ImGui::BulletTextV(const char* fmt, va_list args)
  6233. {
  6234. ImGuiWindow* window = GetCurrentWindow();
  6235. if (window->SkipItems)
  6236. return;
  6237. ImGuiContext& g = *GImGui;
  6238. const ImGuiStyle& style = g.Style;
  6239. const char* text_begin = g.TempBuffer;
  6240. const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6241. const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
  6242. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
  6243. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  6244. 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
  6245. ItemSize(bb);
  6246. if (!ItemAdd(bb, 0))
  6247. return;
  6248. // Render
  6249. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  6250. RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false);
  6251. }
  6252. void ImGui::BulletText(const char* fmt, ...)
  6253. {
  6254. va_list args;
  6255. va_start(args, fmt);
  6256. BulletTextV(fmt, args);
  6257. va_end(args);
  6258. }
  6259. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
  6260. {
  6261. if (data_type == ImGuiDataType_Int)
  6262. ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
  6263. else if (data_type == ImGuiDataType_Float)
  6264. ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
  6265. }
  6266. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
  6267. {
  6268. if (data_type == ImGuiDataType_Int)
  6269. {
  6270. if (decimal_precision < 0)
  6271. ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
  6272. else
  6273. ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
  6274. }
  6275. else if (data_type == ImGuiDataType_Float)
  6276. {
  6277. if (decimal_precision < 0)
  6278. 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?
  6279. else
  6280. ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
  6281. }
  6282. }
  6283. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
  6284. {
  6285. if (data_type == ImGuiDataType_Int)
  6286. {
  6287. if (op == '+')
  6288. *(int*)value1 = *(int*)value1 + *(const int*)value2;
  6289. else if (op == '-')
  6290. *(int*)value1 = *(int*)value1 - *(const int*)value2;
  6291. }
  6292. else if (data_type == ImGuiDataType_Float)
  6293. {
  6294. if (op == '+')
  6295. *(float*)value1 = *(float*)value1 + *(const float*)value2;
  6296. else if (op == '-')
  6297. *(float*)value1 = *(float*)value1 - *(const float*)value2;
  6298. }
  6299. }
  6300. // User can input math operators (e.g. +100) to edit a numerical values.
  6301. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
  6302. {
  6303. while (ImCharIsSpace(*buf))
  6304. buf++;
  6305. // We don't support '-' op because it would conflict with inputing negative value.
  6306. // Instead you can use +-100 to subtract from an existing value
  6307. char op = buf[0];
  6308. if (op == '+' || op == '*' || op == '/')
  6309. {
  6310. buf++;
  6311. while (ImCharIsSpace(*buf))
  6312. buf++;
  6313. }
  6314. else
  6315. {
  6316. op = 0;
  6317. }
  6318. if (!buf[0])
  6319. return false;
  6320. if (data_type == ImGuiDataType_Int)
  6321. {
  6322. if (!scalar_format)
  6323. scalar_format = "%d";
  6324. int* v = (int*)data_ptr;
  6325. const int old_v = *v;
  6326. int arg0i = *v;
  6327. if (op && sscanf(initial_value_buf, scalar_format, &arg0i) < 1)
  6328. return false;
  6329. // 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
  6330. float arg1f = 0.0f;
  6331. if (op == '+') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i + arg1f); } // Add (use "+-" to subtract)
  6332. else if (op == '*') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i * arg1f); } // Multiply
  6333. else if (op == '/') { if (sscanf(buf, "%f", &arg1f) == 1 && arg1f != 0.0f) *v = (int)(arg0i / arg1f); }// Divide
  6334. else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign constant (read as integer so big values are not lossy)
  6335. return (old_v != *v);
  6336. }
  6337. else if (data_type == ImGuiDataType_Float)
  6338. {
  6339. // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
  6340. scalar_format = "%f";
  6341. float* v = (float*)data_ptr;
  6342. const float old_v = *v;
  6343. float arg0f = *v;
  6344. if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
  6345. return false;
  6346. float arg1f = 0.0f;
  6347. if (sscanf(buf, scalar_format, &arg1f) < 1)
  6348. return false;
  6349. if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
  6350. else if (op == '*') { *v = arg0f * arg1f; } // Multiply
  6351. else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
  6352. else { *v = arg1f; } // Assign constant
  6353. return (old_v != *v);
  6354. }
  6355. return false;
  6356. }
  6357. // Create text input in place of a slider (when CTRL+Clicking on slider)
  6358. // FIXME: Logic is messy and confusing.
  6359. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
  6360. {
  6361. ImGuiContext& g = *GImGui;
  6362. ImGuiWindow* window = GetCurrentWindow();
  6363. // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
  6364. // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id
  6365. SetActiveID(g.ScalarAsInputTextId, window);
  6366. SetHoveredID(0);
  6367. FocusableItemUnregister(window);
  6368. char buf[32];
  6369. DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
  6370. bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
  6371. if (g.ScalarAsInputTextId == 0) // First frame we started displaying the InputText widget
  6372. {
  6373. 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)
  6374. g.ScalarAsInputTextId = g.ActiveId;
  6375. SetHoveredID(id);
  6376. }
  6377. if (text_value_changed)
  6378. return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
  6379. return false;
  6380. }
  6381. // Parse display precision back from the display format string
  6382. int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
  6383. {
  6384. int precision = default_precision;
  6385. while ((fmt = strchr(fmt, '%')) != NULL)
  6386. {
  6387. fmt++;
  6388. if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
  6389. while (*fmt >= '0' && *fmt <= '9')
  6390. fmt++;
  6391. if (*fmt == '.')
  6392. {
  6393. fmt = ImAtoi(fmt + 1, &precision);
  6394. if (precision < 0 || precision > 10)
  6395. precision = default_precision;
  6396. }
  6397. if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
  6398. precision = -1;
  6399. break;
  6400. }
  6401. return precision;
  6402. }
  6403. static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
  6404. {
  6405. 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 };
  6406. return (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
  6407. }
  6408. float ImGui::RoundScalar(float value, int decimal_precision)
  6409. {
  6410. // Round past decimal precision
  6411. // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
  6412. // FIXME: Investigate better rounding methods
  6413. if (decimal_precision < 0)
  6414. return value;
  6415. const float min_step = GetMinimumStepAtDecimalPrecision(decimal_precision);
  6416. bool negative = value < 0.0f;
  6417. value = fabsf(value);
  6418. float remainder = fmodf(value, min_step);
  6419. if (remainder <= min_step*0.5f)
  6420. value -= remainder;
  6421. else
  6422. value += (min_step - remainder);
  6423. return negative ? -value : value;
  6424. }
  6425. static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos)
  6426. {
  6427. if (v_min == v_max)
  6428. return 0.0f;
  6429. const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
  6430. const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
  6431. if (is_non_linear)
  6432. {
  6433. if (v_clamped < 0.0f)
  6434. {
  6435. const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min);
  6436. return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos;
  6437. }
  6438. else
  6439. {
  6440. const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min));
  6441. return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos);
  6442. }
  6443. }
  6444. // Linear slider
  6445. return (v_clamped - v_min) / (v_max - v_min);
  6446. }
  6447. bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
  6448. {
  6449. ImGuiContext& g = *GImGui;
  6450. ImGuiWindow* window = GetCurrentWindow();
  6451. const ImGuiStyle& style = g.Style;
  6452. // Draw frame
  6453. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  6454. const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
  6455. const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
  6456. const float grab_padding = 2.0f;
  6457. const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
  6458. float grab_sz;
  6459. if (decimal_precision != 0)
  6460. grab_sz = ImMin(style.GrabMinSize, slider_sz);
  6461. else
  6462. grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
  6463. const float slider_usable_sz = slider_sz - grab_sz;
  6464. const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
  6465. const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
  6466. // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
  6467. float linear_zero_pos = 0.0f; // 0.0->1.0f
  6468. if (v_min * v_max < 0.0f)
  6469. {
  6470. // Different sign
  6471. const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power);
  6472. const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power);
  6473. linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0);
  6474. }
  6475. else
  6476. {
  6477. // Same sign
  6478. linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
  6479. }
  6480. // Process clicking on the slider
  6481. bool value_changed = false;
  6482. if (g.ActiveId == id)
  6483. {
  6484. bool set_new_value = false;
  6485. float clicked_t = 0.0f;
  6486. if (g.IO.MouseDown[0])
  6487. {
  6488. const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  6489. clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
  6490. if (!is_horizontal)
  6491. clicked_t = 1.0f - clicked_t;
  6492. set_new_value = true;
  6493. }
  6494. else
  6495. {
  6496. ClearActiveID();
  6497. }
  6498. if (set_new_value)
  6499. {
  6500. float new_value;
  6501. if (is_non_linear)
  6502. {
  6503. // Account for logarithmic scale on both sides of the zero
  6504. if (clicked_t < linear_zero_pos)
  6505. {
  6506. // Negative: rescale to the negative range before powering
  6507. float a = 1.0f - (clicked_t / linear_zero_pos);
  6508. a = powf(a, power);
  6509. new_value = ImLerp(ImMin(v_max,0.0f), v_min, a);
  6510. }
  6511. else
  6512. {
  6513. // Positive: rescale to the positive range before powering
  6514. float a;
  6515. if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f)
  6516. a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
  6517. else
  6518. a = clicked_t;
  6519. a = powf(a, power);
  6520. new_value = ImLerp(ImMax(v_min,0.0f), v_max, a);
  6521. }
  6522. }
  6523. else
  6524. {
  6525. // Linear slider
  6526. new_value = ImLerp(v_min, v_max, clicked_t);
  6527. }
  6528. // Round past decimal precision
  6529. new_value = RoundScalar(new_value, decimal_precision);
  6530. if (*v != new_value)
  6531. {
  6532. *v = new_value;
  6533. value_changed = true;
  6534. }
  6535. }
  6536. }
  6537. // Draw
  6538. float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
  6539. if (!is_horizontal)
  6540. grab_t = 1.0f - grab_t;
  6541. const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
  6542. ImRect grab_bb;
  6543. if (is_horizontal)
  6544. 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));
  6545. else
  6546. 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));
  6547. window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
  6548. return value_changed;
  6549. }
  6550. // Use power!=1.0 for logarithmic sliders.
  6551. // Adjust display_format to decorate the value with a prefix or a suffix.
  6552. // "%.3f" 1.234
  6553. // "%5.2f secs" 01.23 secs
  6554. // "Gold: %.0f" Gold: 1
  6555. bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
  6556. {
  6557. ImGuiWindow* window = GetCurrentWindow();
  6558. if (window->SkipItems)
  6559. return false;
  6560. ImGuiContext& g = *GImGui;
  6561. const ImGuiStyle& style = g.Style;
  6562. const ImGuiID id = window->GetID(label);
  6563. const float w = CalcItemWidth();
  6564. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6565. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  6566. 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));
  6567. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  6568. if (!ItemAdd(total_bb, id))
  6569. {
  6570. ItemSize(total_bb, style.FramePadding.y);
  6571. return false;
  6572. }
  6573. const bool hovered = ItemHoverable(frame_bb, id);
  6574. if (!display_format)
  6575. display_format = "%.3f";
  6576. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6577. // Tabbing or CTRL-clicking on Slider turns it into an input box
  6578. bool start_text_input = false;
  6579. const bool tab_focus_requested = FocusableItemRegister(window, id);
  6580. if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
  6581. {
  6582. SetActiveID(id, window);
  6583. FocusWindow(window);
  6584. if (tab_focus_requested || g.IO.KeyCtrl)
  6585. {
  6586. start_text_input = true;
  6587. g.ScalarAsInputTextId = 0;
  6588. }
  6589. }
  6590. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  6591. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  6592. // Actual slider behavior + render grab
  6593. ItemSize(total_bb, style.FramePadding.y);
  6594. const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
  6595. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  6596. char value_buf[64];
  6597. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  6598. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
  6599. if (label_size.x > 0.0f)
  6600. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  6601. return value_changed;
  6602. }
  6603. bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power)
  6604. {
  6605. ImGuiWindow* window = GetCurrentWindow();
  6606. if (window->SkipItems)
  6607. return false;
  6608. ImGuiContext& g = *GImGui;
  6609. const ImGuiStyle& style = g.Style;
  6610. const ImGuiID id = window->GetID(label);
  6611. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6612. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  6613. 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));
  6614. ItemSize(bb, style.FramePadding.y);
  6615. if (!ItemAdd(frame_bb, id))
  6616. return false;
  6617. const bool hovered = ItemHoverable(frame_bb, id);
  6618. if (!display_format)
  6619. display_format = "%.3f";
  6620. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6621. if (hovered && g.IO.MouseClicked[0])
  6622. {
  6623. SetActiveID(id, window);
  6624. FocusWindow(window);
  6625. }
  6626. // Actual slider behavior + render grab
  6627. bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
  6628. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  6629. // For the vertical slider we allow centered text to overlap the frame padding
  6630. char value_buf[64];
  6631. char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  6632. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f));
  6633. if (label_size.x > 0.0f)
  6634. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  6635. return value_changed;
  6636. }
  6637. bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
  6638. {
  6639. float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
  6640. bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f);
  6641. *v_rad = v_deg * (2*IM_PI) / 360.0f;
  6642. return value_changed;
  6643. }
  6644. bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format)
  6645. {
  6646. if (!display_format)
  6647. display_format = "%.0f";
  6648. float v_f = (float)*v;
  6649. bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  6650. *v = (int)v_f;
  6651. return value_changed;
  6652. }
  6653. bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
  6654. {
  6655. if (!display_format)
  6656. display_format = "%.0f";
  6657. float v_f = (float)*v;
  6658. bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  6659. *v = (int)v_f;
  6660. return value_changed;
  6661. }
  6662. // Add multiple sliders on 1 line for compact edition of multiple components
  6663. bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
  6664. {
  6665. ImGuiWindow* window = GetCurrentWindow();
  6666. if (window->SkipItems)
  6667. return false;
  6668. ImGuiContext& g = *GImGui;
  6669. bool value_changed = false;
  6670. BeginGroup();
  6671. PushID(label);
  6672. PushMultiItemsWidths(components);
  6673. for (int i = 0; i < components; i++)
  6674. {
  6675. PushID(i);
  6676. value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
  6677. SameLine(0, g.Style.ItemInnerSpacing.x);
  6678. PopID();
  6679. PopItemWidth();
  6680. }
  6681. PopID();
  6682. TextUnformatted(label, FindRenderedTextEnd(label));
  6683. EndGroup();
  6684. return value_changed;
  6685. }
  6686. bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
  6687. {
  6688. return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
  6689. }
  6690. bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
  6691. {
  6692. return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
  6693. }
  6694. bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
  6695. {
  6696. return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
  6697. }
  6698. bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
  6699. {
  6700. ImGuiWindow* window = GetCurrentWindow();
  6701. if (window->SkipItems)
  6702. return false;
  6703. ImGuiContext& g = *GImGui;
  6704. bool value_changed = false;
  6705. BeginGroup();
  6706. PushID(label);
  6707. PushMultiItemsWidths(components);
  6708. for (int i = 0; i < components; i++)
  6709. {
  6710. PushID(i);
  6711. value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format);
  6712. SameLine(0, g.Style.ItemInnerSpacing.x);
  6713. PopID();
  6714. PopItemWidth();
  6715. }
  6716. PopID();
  6717. TextUnformatted(label, FindRenderedTextEnd(label));
  6718. EndGroup();
  6719. return value_changed;
  6720. }
  6721. bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
  6722. {
  6723. return SliderIntN(label, v, 2, v_min, v_max, display_format);
  6724. }
  6725. bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
  6726. {
  6727. return SliderIntN(label, v, 3, v_min, v_max, display_format);
  6728. }
  6729. bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
  6730. {
  6731. return SliderIntN(label, v, 4, v_min, v_max, display_format);
  6732. }
  6733. 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)
  6734. {
  6735. ImGuiContext& g = *GImGui;
  6736. const ImGuiStyle& style = g.Style;
  6737. // Draw frame
  6738. const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
  6739. RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
  6740. bool value_changed = false;
  6741. // Process clicking on the drag
  6742. if (g.ActiveId == id)
  6743. {
  6744. if (g.IO.MouseDown[0])
  6745. {
  6746. if (g.ActiveIdIsJustActivated)
  6747. {
  6748. // Lock current value on click
  6749. g.DragCurrentValue = *v;
  6750. g.DragLastMouseDelta = ImVec2(0.f, 0.f);
  6751. }
  6752. if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
  6753. v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
  6754. float v_cur = g.DragCurrentValue;
  6755. const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
  6756. float adjust_delta = 0.0f;
  6757. if (IsMousePosValid())
  6758. {
  6759. adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x;
  6760. if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
  6761. adjust_delta *= g.DragSpeedScaleFast;
  6762. if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
  6763. adjust_delta *= g.DragSpeedScaleSlow;
  6764. g.DragLastMouseDelta.x = mouse_drag_delta.x;
  6765. }
  6766. adjust_delta *= v_speed;
  6767. if (fabsf(adjust_delta) > 0.0f)
  6768. {
  6769. if (fabsf(power - 1.0f) > 0.001f)
  6770. {
  6771. // Logarithmic curve on both side of 0.0
  6772. float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
  6773. float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
  6774. float v1 = powf(v0_abs, 1.0f / power) + (adjust_delta * v0_sign);
  6775. float v1_abs = v1 >= 0.0f ? v1 : -v1;
  6776. float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
  6777. v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
  6778. }
  6779. else
  6780. {
  6781. v_cur += adjust_delta;
  6782. }
  6783. // Clamp
  6784. if (v_min < v_max)
  6785. v_cur = ImClamp(v_cur, v_min, v_max);
  6786. g.DragCurrentValue = v_cur;
  6787. }
  6788. // Round to user desired precision, then apply
  6789. v_cur = RoundScalar(v_cur, decimal_precision);
  6790. if (*v != v_cur)
  6791. {
  6792. *v = v_cur;
  6793. value_changed = true;
  6794. }
  6795. }
  6796. else
  6797. {
  6798. ClearActiveID();
  6799. }
  6800. }
  6801. return value_changed;
  6802. }
  6803. bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
  6804. {
  6805. ImGuiWindow* window = GetCurrentWindow();
  6806. if (window->SkipItems)
  6807. return false;
  6808. ImGuiContext& g = *GImGui;
  6809. const ImGuiStyle& style = g.Style;
  6810. const ImGuiID id = window->GetID(label);
  6811. const float w = CalcItemWidth();
  6812. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6813. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  6814. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  6815. 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));
  6816. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  6817. if (!ItemAdd(total_bb, id))
  6818. {
  6819. ItemSize(total_bb, style.FramePadding.y);
  6820. return false;
  6821. }
  6822. const bool hovered = ItemHoverable(frame_bb, id);
  6823. if (!display_format)
  6824. display_format = "%.3f";
  6825. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6826. // Tabbing or CTRL-clicking on Drag turns it into an input box
  6827. bool start_text_input = false;
  6828. const bool tab_focus_requested = FocusableItemRegister(window, id);
  6829. if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])))
  6830. {
  6831. SetActiveID(id, window);
  6832. FocusWindow(window);
  6833. if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
  6834. {
  6835. start_text_input = true;
  6836. g.ScalarAsInputTextId = 0;
  6837. }
  6838. }
  6839. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  6840. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  6841. // Actual drag behavior
  6842. ItemSize(total_bb, style.FramePadding.y);
  6843. const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
  6844. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  6845. char value_buf[64];
  6846. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  6847. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
  6848. if (label_size.x > 0.0f)
  6849. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  6850. return value_changed;
  6851. }
  6852. 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)
  6853. {
  6854. ImGuiWindow* window = GetCurrentWindow();
  6855. if (window->SkipItems)
  6856. return false;
  6857. ImGuiContext& g = *GImGui;
  6858. bool value_changed = false;
  6859. BeginGroup();
  6860. PushID(label);
  6861. PushMultiItemsWidths(components);
  6862. for (int i = 0; i < components; i++)
  6863. {
  6864. PushID(i);
  6865. value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
  6866. SameLine(0, g.Style.ItemInnerSpacing.x);
  6867. PopID();
  6868. PopItemWidth();
  6869. }
  6870. PopID();
  6871. TextUnformatted(label, FindRenderedTextEnd(label));
  6872. EndGroup();
  6873. return value_changed;
  6874. }
  6875. bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
  6876. {
  6877. return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
  6878. }
  6879. bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
  6880. {
  6881. return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
  6882. }
  6883. bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
  6884. {
  6885. return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power);
  6886. }
  6887. 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)
  6888. {
  6889. ImGuiWindow* window = GetCurrentWindow();
  6890. if (window->SkipItems)
  6891. return false;
  6892. ImGuiContext& g = *GImGui;
  6893. PushID(label);
  6894. BeginGroup();
  6895. PushMultiItemsWidths(2);
  6896. bool value_changed = 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);
  6897. PopItemWidth();
  6898. SameLine(0, g.Style.ItemInnerSpacing.x);
  6899. value_changed |= 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);
  6900. PopItemWidth();
  6901. SameLine(0, g.Style.ItemInnerSpacing.x);
  6902. TextUnformatted(label, FindRenderedTextEnd(label));
  6903. EndGroup();
  6904. PopID();
  6905. return value_changed;
  6906. }
  6907. // NB: v_speed is float to allow adjusting the drag speed with more precision
  6908. bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
  6909. {
  6910. if (!display_format)
  6911. display_format = "%.0f";
  6912. float v_f = (float)*v;
  6913. bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
  6914. *v = (int)v_f;
  6915. return value_changed;
  6916. }
  6917. bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
  6918. {
  6919. ImGuiWindow* window = GetCurrentWindow();
  6920. if (window->SkipItems)
  6921. return false;
  6922. ImGuiContext& g = *GImGui;
  6923. bool value_changed = false;
  6924. BeginGroup();
  6925. PushID(label);
  6926. PushMultiItemsWidths(components);
  6927. for (int i = 0; i < components; i++)
  6928. {
  6929. PushID(i);
  6930. value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
  6931. SameLine(0, g.Style.ItemInnerSpacing.x);
  6932. PopID();
  6933. PopItemWidth();
  6934. }
  6935. PopID();
  6936. TextUnformatted(label, FindRenderedTextEnd(label));
  6937. EndGroup();
  6938. return value_changed;
  6939. }
  6940. bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
  6941. {
  6942. return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
  6943. }
  6944. bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
  6945. {
  6946. return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
  6947. }
  6948. bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
  6949. {
  6950. return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format);
  6951. }
  6952. 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)
  6953. {
  6954. ImGuiWindow* window = GetCurrentWindow();
  6955. if (window->SkipItems)
  6956. return false;
  6957. ImGuiContext& g = *GImGui;
  6958. PushID(label);
  6959. BeginGroup();
  6960. PushMultiItemsWidths(2);
  6961. bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format);
  6962. PopItemWidth();
  6963. SameLine(0, g.Style.ItemInnerSpacing.x);
  6964. value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format);
  6965. PopItemWidth();
  6966. SameLine(0, g.Style.ItemInnerSpacing.x);
  6967. TextUnformatted(label, FindRenderedTextEnd(label));
  6968. EndGroup();
  6969. PopID();
  6970. return value_changed;
  6971. }
  6972. 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)
  6973. {
  6974. ImGuiWindow* window = GetCurrentWindow();
  6975. if (window->SkipItems)
  6976. return;
  6977. ImGuiContext& g = *GImGui;
  6978. const ImGuiStyle& style = g.Style;
  6979. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6980. if (graph_size.x == 0.0f)
  6981. graph_size.x = CalcItemWidth();
  6982. if (graph_size.y == 0.0f)
  6983. graph_size.y = label_size.y + (style.FramePadding.y * 2);
  6984. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y));
  6985. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  6986. 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));
  6987. ItemSize(total_bb, style.FramePadding.y);
  6988. if (!ItemAdd(total_bb, 0))
  6989. return;
  6990. const bool hovered = ItemHoverable(inner_bb, 0);
  6991. // Determine scale from values if not specified
  6992. if (scale_min == FLT_MAX || scale_max == FLT_MAX)
  6993. {
  6994. float v_min = FLT_MAX;
  6995. float v_max = -FLT_MAX;
  6996. for (int i = 0; i < values_count; i++)
  6997. {
  6998. const float v = values_getter(data, i);
  6999. v_min = ImMin(v_min, v);
  7000. v_max = ImMax(v_max, v);
  7001. }
  7002. if (scale_min == FLT_MAX)
  7003. scale_min = v_min;
  7004. if (scale_max == FLT_MAX)
  7005. scale_max = v_max;
  7006. }
  7007. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7008. if (values_count > 0)
  7009. {
  7010. int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  7011. int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  7012. // Tooltip on hover
  7013. int v_hovered = -1;
  7014. if (hovered)
  7015. {
  7016. const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
  7017. const int v_idx = (int)(t * item_count);
  7018. IM_ASSERT(v_idx >= 0 && v_idx < values_count);
  7019. const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
  7020. const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
  7021. if (plot_type == ImGuiPlotType_Lines)
  7022. SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
  7023. else if (plot_type == ImGuiPlotType_Histogram)
  7024. SetTooltip("%d: %8.4g", v_idx, v0);
  7025. v_hovered = v_idx;
  7026. }
  7027. const float t_step = 1.0f / (float)res_w;
  7028. float v0 = values_getter(data, (0 + values_offset) % values_count);
  7029. float t0 = 0.0f;
  7030. ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
  7031. float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min / (scale_max - scale_min)) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
  7032. const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
  7033. const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
  7034. for (int n = 0; n < res_w; n++)
  7035. {
  7036. const float t1 = t0 + t_step;
  7037. const int v1_idx = (int)(t0 * item_count + 0.5f);
  7038. IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
  7039. const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
  7040. const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) );
  7041. // 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.
  7042. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
  7043. ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
  7044. if (plot_type == ImGuiPlotType_Lines)
  7045. {
  7046. window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  7047. }
  7048. else if (plot_type == ImGuiPlotType_Histogram)
  7049. {
  7050. if (pos1.x >= pos0.x + 2.0f)
  7051. pos1.x -= 1.0f;
  7052. window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  7053. }
  7054. t0 = t1;
  7055. tp0 = tp1;
  7056. }
  7057. }
  7058. // Text overlay
  7059. if (overlay_text)
  7060. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f));
  7061. if (label_size.x > 0.0f)
  7062. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  7063. }
  7064. struct ImGuiPlotArrayGetterData
  7065. {
  7066. const float* Values;
  7067. int Stride;
  7068. ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
  7069. };
  7070. static float Plot_ArrayGetter(void* data, int idx)
  7071. {
  7072. ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
  7073. const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
  7074. return v;
  7075. }
  7076. 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)
  7077. {
  7078. ImGuiPlotArrayGetterData data(values, stride);
  7079. PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7080. }
  7081. 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)
  7082. {
  7083. PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7084. }
  7085. 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)
  7086. {
  7087. ImGuiPlotArrayGetterData data(values, stride);
  7088. PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7089. }
  7090. 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)
  7091. {
  7092. PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7093. }
  7094. // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
  7095. void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
  7096. {
  7097. ImGuiWindow* window = GetCurrentWindow();
  7098. if (window->SkipItems)
  7099. return;
  7100. ImGuiContext& g = *GImGui;
  7101. const ImGuiStyle& style = g.Style;
  7102. ImVec2 pos = window->DC.CursorPos;
  7103. ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
  7104. ItemSize(bb, style.FramePadding.y);
  7105. if (!ItemAdd(bb, 0))
  7106. return;
  7107. // Render
  7108. fraction = ImSaturate(fraction);
  7109. RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7110. bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
  7111. const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
  7112. RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
  7113. // Default displaying the fraction as percentage string, but user can override it
  7114. char overlay_buf[32];
  7115. if (!overlay)
  7116. {
  7117. ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
  7118. overlay = overlay_buf;
  7119. }
  7120. ImVec2 overlay_size = CalcTextSize(overlay, NULL);
  7121. if (overlay_size.x > 0.0f)
  7122. 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, ImVec2(0.0f,0.5f), &bb);
  7123. }
  7124. bool ImGui::Checkbox(const char* label, bool* v)
  7125. {
  7126. ImGuiWindow* window = GetCurrentWindow();
  7127. if (window->SkipItems)
  7128. return false;
  7129. ImGuiContext& g = *GImGui;
  7130. const ImGuiStyle& style = g.Style;
  7131. const ImGuiID id = window->GetID(label);
  7132. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7133. 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)); // We want a square shape to we use Y twice
  7134. ItemSize(check_bb, style.FramePadding.y);
  7135. ImRect total_bb = check_bb;
  7136. if (label_size.x > 0)
  7137. SameLine(0, style.ItemInnerSpacing.x);
  7138. const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size);
  7139. if (label_size.x > 0)
  7140. {
  7141. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  7142. total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
  7143. }
  7144. if (!ItemAdd(total_bb, id))
  7145. return false;
  7146. bool hovered, held;
  7147. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  7148. if (pressed)
  7149. *v = !(*v);
  7150. RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
  7151. if (*v)
  7152. {
  7153. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  7154. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  7155. RenderCheckMark(check_bb.Min + ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad*2.0f);
  7156. }
  7157. if (g.LogEnabled)
  7158. LogRenderedText(&text_bb.Min, *v ? "[x]" : "[ ]");
  7159. if (label_size.x > 0.0f)
  7160. RenderText(text_bb.Min, label);
  7161. return pressed;
  7162. }
  7163. bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
  7164. {
  7165. bool v = ((*flags & flags_value) == flags_value);
  7166. bool pressed = Checkbox(label, &v);
  7167. if (pressed)
  7168. {
  7169. if (v)
  7170. *flags |= flags_value;
  7171. else
  7172. *flags &= ~flags_value;
  7173. }
  7174. return pressed;
  7175. }
  7176. bool ImGui::RadioButton(const char* label, bool active)
  7177. {
  7178. ImGuiWindow* window = GetCurrentWindow();
  7179. if (window->SkipItems)
  7180. return false;
  7181. ImGuiContext& g = *GImGui;
  7182. const ImGuiStyle& style = g.Style;
  7183. const ImGuiID id = window->GetID(label);
  7184. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7185. 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));
  7186. ItemSize(check_bb, style.FramePadding.y);
  7187. ImRect total_bb = check_bb;
  7188. if (label_size.x > 0)
  7189. SameLine(0, style.ItemInnerSpacing.x);
  7190. const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
  7191. if (label_size.x > 0)
  7192. {
  7193. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  7194. total_bb.Add(text_bb);
  7195. }
  7196. if (!ItemAdd(total_bb, id))
  7197. return false;
  7198. ImVec2 center = check_bb.GetCenter();
  7199. center.x = (float)(int)center.x + 0.5f;
  7200. center.y = (float)(int)center.y + 0.5f;
  7201. const float radius = check_bb.GetHeight() * 0.5f;
  7202. bool hovered, held;
  7203. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  7204. window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
  7205. if (active)
  7206. {
  7207. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  7208. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  7209. window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16);
  7210. }
  7211. if (style.FrameBorderSize > 0.0f)
  7212. {
  7213. window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
  7214. window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);
  7215. }
  7216. if (g.LogEnabled)
  7217. LogRenderedText(&text_bb.Min, active ? "(x)" : "( )");
  7218. if (label_size.x > 0.0f)
  7219. RenderText(text_bb.Min, label);
  7220. return pressed;
  7221. }
  7222. bool ImGui::RadioButton(const char* label, int* v, int v_button)
  7223. {
  7224. const bool pressed = RadioButton(label, *v == v_button);
  7225. if (pressed)
  7226. {
  7227. *v = v_button;
  7228. }
  7229. return pressed;
  7230. }
  7231. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
  7232. {
  7233. int line_count = 0;
  7234. const char* s = text_begin;
  7235. while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
  7236. if (c == '\n')
  7237. line_count++;
  7238. s--;
  7239. if (s[0] != '\n' && s[0] != '\r')
  7240. line_count++;
  7241. *out_text_end = s;
  7242. return line_count;
  7243. }
  7244. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
  7245. {
  7246. ImFont* font = GImGui->Font;
  7247. const float line_height = GImGui->FontSize;
  7248. const float scale = line_height / font->FontSize;
  7249. ImVec2 text_size = ImVec2(0,0);
  7250. float line_width = 0.0f;
  7251. const ImWchar* s = text_begin;
  7252. while (s < text_end)
  7253. {
  7254. unsigned int c = (unsigned int)(*s++);
  7255. if (c == '\n')
  7256. {
  7257. text_size.x = ImMax(text_size.x, line_width);
  7258. text_size.y += line_height;
  7259. line_width = 0.0f;
  7260. if (stop_on_new_line)
  7261. break;
  7262. continue;
  7263. }
  7264. if (c == '\r')
  7265. continue;
  7266. const float char_width = font->GetCharAdvance((unsigned short)c) * scale;
  7267. line_width += char_width;
  7268. }
  7269. if (text_size.x < line_width)
  7270. text_size.x = line_width;
  7271. if (out_offset)
  7272. *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
  7273. if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
  7274. text_size.y += line_height;
  7275. if (remaining)
  7276. *remaining = s;
  7277. return text_size;
  7278. }
  7279. // 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)
  7280. namespace ImGuiStb
  7281. {
  7282. static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
  7283. static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; }
  7284. 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); }
  7285. static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
  7286. static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
  7287. static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
  7288. {
  7289. const ImWchar* text = obj->Text.Data;
  7290. const ImWchar* text_remaining = NULL;
  7291. const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
  7292. r->x0 = 0.0f;
  7293. r->x1 = size.x;
  7294. r->baseline_y_delta = size.y;
  7295. r->ymin = 0.0f;
  7296. r->ymax = size.y;
  7297. r->num_chars = (int)(text_remaining - (text + line_start_idx));
  7298. }
  7299. static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
  7300. static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; }
  7301. static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
  7302. #ifdef __APPLE__ // FIXME: Move setting to IO structure
  7303. static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; }
  7304. static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
  7305. #else
  7306. static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
  7307. #endif
  7308. #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
  7309. #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
  7310. static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
  7311. {
  7312. ImWchar* dst = obj->Text.Data + pos;
  7313. // We maintain our buffer length in both UTF-8 and wchar formats
  7314. obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
  7315. obj->CurLenW -= n;
  7316. // Offset remaining text
  7317. const ImWchar* src = obj->Text.Data + pos + n;
  7318. while (ImWchar c = *src++)
  7319. *dst++ = c;
  7320. *dst = '\0';
  7321. }
  7322. static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
  7323. {
  7324. const int text_len = obj->CurLenW;
  7325. IM_ASSERT(pos <= text_len);
  7326. if (new_text_len + text_len + 1 > obj->Text.Size)
  7327. return false;
  7328. const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
  7329. if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
  7330. return false;
  7331. ImWchar* text = obj->Text.Data;
  7332. if (pos != text_len)
  7333. memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
  7334. memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
  7335. obj->CurLenW += new_text_len;
  7336. obj->CurLenA += new_text_len_utf8;
  7337. obj->Text[obj->CurLenW] = '\0';
  7338. return true;
  7339. }
  7340. // 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)
  7341. #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
  7342. #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
  7343. #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
  7344. #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
  7345. #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
  7346. #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
  7347. #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
  7348. #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
  7349. #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
  7350. #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
  7351. #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
  7352. #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
  7353. #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
  7354. #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
  7355. #define STB_TEXTEDIT_K_SHIFT 0x20000
  7356. #define STB_TEXTEDIT_IMPLEMENTATION
  7357. #include "stb_textedit.h"
  7358. }
  7359. void ImGuiTextEditState::OnKeyPressed(int key)
  7360. {
  7361. stb_textedit_key(this, &StbState, key);
  7362. CursorFollow = true;
  7363. CursorAnimReset();
  7364. }
  7365. // Public API to manipulate UTF-8 text
  7366. // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
  7367. // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
  7368. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count)
  7369. {
  7370. IM_ASSERT(pos + bytes_count <= BufTextLen);
  7371. char* dst = Buf + pos;
  7372. const char* src = Buf + pos + bytes_count;
  7373. while (char c = *src++)
  7374. *dst++ = c;
  7375. *dst = '\0';
  7376. if (CursorPos + bytes_count >= pos)
  7377. CursorPos -= bytes_count;
  7378. else if (CursorPos >= pos)
  7379. CursorPos = pos;
  7380. SelectionStart = SelectionEnd = CursorPos;
  7381. BufDirty = true;
  7382. BufTextLen -= bytes_count;
  7383. }
  7384. void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
  7385. {
  7386. const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
  7387. if (new_text_len + BufTextLen + 1 >= BufSize)
  7388. return;
  7389. if (BufTextLen != pos)
  7390. memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
  7391. memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
  7392. Buf[BufTextLen + new_text_len] = '\0';
  7393. if (CursorPos >= pos)
  7394. CursorPos += new_text_len;
  7395. SelectionStart = SelectionEnd = CursorPos;
  7396. BufDirty = true;
  7397. BufTextLen += new_text_len;
  7398. }
  7399. // Return false to discard a character.
  7400. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7401. {
  7402. unsigned int c = *p_char;
  7403. if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
  7404. {
  7405. bool pass = false;
  7406. pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
  7407. pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
  7408. if (!pass)
  7409. return false;
  7410. }
  7411. 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.
  7412. return false;
  7413. if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank))
  7414. {
  7415. if (flags & ImGuiInputTextFlags_CharsDecimal)
  7416. if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
  7417. return false;
  7418. if (flags & ImGuiInputTextFlags_CharsHexadecimal)
  7419. if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
  7420. return false;
  7421. if (flags & ImGuiInputTextFlags_CharsUppercase)
  7422. if (c >= 'a' && c <= 'z')
  7423. *p_char = (c += (unsigned int)('A'-'a'));
  7424. if (flags & ImGuiInputTextFlags_CharsNoBlank)
  7425. if (ImCharIsSpace(c))
  7426. return false;
  7427. }
  7428. if (flags & ImGuiInputTextFlags_CallbackCharFilter)
  7429. {
  7430. ImGuiTextEditCallbackData callback_data;
  7431. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  7432. callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
  7433. callback_data.EventChar = (ImWchar)c;
  7434. callback_data.Flags = flags;
  7435. callback_data.UserData = user_data;
  7436. if (callback(&callback_data) != 0)
  7437. return false;
  7438. *p_char = callback_data.EventChar;
  7439. if (!callback_data.EventChar)
  7440. return false;
  7441. }
  7442. return true;
  7443. }
  7444. // Edit a string of text
  7445. // 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.
  7446. // 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
  7447. bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7448. {
  7449. ImGuiWindow* window = GetCurrentWindow();
  7450. if (window->SkipItems)
  7451. return false;
  7452. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
  7453. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
  7454. ImGuiContext& g = *GImGui;
  7455. const ImGuiIO& io = g.IO;
  7456. const ImGuiStyle& style = g.Style;
  7457. const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
  7458. const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
  7459. const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
  7460. const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
  7461. if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn
  7462. BeginGroup();
  7463. const ImGuiID id = window->GetID(label);
  7464. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7465. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
  7466. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  7467. 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));
  7468. ImGuiWindow* draw_window = window;
  7469. if (is_multiline)
  7470. {
  7471. if (!BeginChildFrame(id, frame_bb.GetSize()))
  7472. {
  7473. EndChildFrame();
  7474. EndGroup();
  7475. return false;
  7476. }
  7477. draw_window = GetCurrentWindow();
  7478. size.x -= draw_window->ScrollbarSizes.x;
  7479. }
  7480. else
  7481. {
  7482. ItemSize(total_bb, style.FramePadding.y);
  7483. if (!ItemAdd(total_bb, id))
  7484. return false;
  7485. }
  7486. const bool hovered = ItemHoverable(frame_bb, id);
  7487. if (hovered)
  7488. g.MouseCursor = ImGuiMouseCursor_TextInput;
  7489. // Password pushes a temporary font with only a fallback glyph
  7490. if (is_password)
  7491. {
  7492. const ImFontGlyph* glyph = g.Font->FindGlyph('*');
  7493. ImFont* password_font = &g.InputTextPasswordFont;
  7494. password_font->FontSize = g.Font->FontSize;
  7495. password_font->Scale = g.Font->Scale;
  7496. password_font->DisplayOffset = g.Font->DisplayOffset;
  7497. password_font->Ascent = g.Font->Ascent;
  7498. password_font->Descent = g.Font->Descent;
  7499. password_font->ContainerAtlas = g.Font->ContainerAtlas;
  7500. password_font->FallbackGlyph = glyph;
  7501. password_font->FallbackAdvanceX = glyph->AdvanceX;
  7502. IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
  7503. PushFont(password_font);
  7504. }
  7505. // NB: we are only allowed to access 'edit_state' if we are the active widget.
  7506. ImGuiTextEditState& edit_state = g.InputTextState;
  7507. const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
  7508. const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
  7509. const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
  7510. const bool user_clicked = hovered && io.MouseClicked[0];
  7511. const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
  7512. bool clear_active_id = false;
  7513. bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
  7514. if (focus_requested || user_clicked || user_scrolled)
  7515. {
  7516. if (g.ActiveId != id)
  7517. {
  7518. // Start edition
  7519. // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
  7520. // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
  7521. const int prev_len_w = edit_state.CurLenW;
  7522. 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.
  7523. 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.
  7524. ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size);
  7525. const char* buf_end = NULL;
  7526. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  7527. 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.
  7528. edit_state.CursorAnimReset();
  7529. // Preserve cursor position and undo/redo stack if we come back to same widget
  7530. // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar).
  7531. const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW);
  7532. if (recycle_state)
  7533. {
  7534. // Recycle existing cursor/selection/undo stack but clamp position
  7535. // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
  7536. edit_state.CursorClamp();
  7537. }
  7538. else
  7539. {
  7540. edit_state.Id = id;
  7541. edit_state.ScrollX = 0.0f;
  7542. stb_textedit_initialize_state(&edit_state.StbState, !is_multiline);
  7543. if (!is_multiline && focus_requested_by_code)
  7544. select_all = true;
  7545. }
  7546. if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
  7547. edit_state.StbState.insert_mode = true;
  7548. if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
  7549. select_all = true;
  7550. }
  7551. SetActiveID(id, window);
  7552. FocusWindow(window);
  7553. }
  7554. else if (io.MouseClicked[0])
  7555. {
  7556. // Release focus when we click outside
  7557. clear_active_id = true;
  7558. }
  7559. bool value_changed = false;
  7560. bool enter_pressed = false;
  7561. if (g.ActiveId == id)
  7562. {
  7563. if (!is_editable && !g.ActiveIdIsJustActivated)
  7564. {
  7565. // When read-only we always use the live data passed to the function
  7566. edit_state.Text.resize(buf_size+1);
  7567. const char* buf_end = NULL;
  7568. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  7569. edit_state.CurLenA = (int)(buf_end - buf);
  7570. edit_state.CursorClamp();
  7571. }
  7572. edit_state.BufSizeA = buf_size;
  7573. // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
  7574. // Down the line we should have a cleaner library-wide concept of Selected vs Active.
  7575. g.ActiveIdAllowOverlap = !io.MouseDown[0];
  7576. g.WantTextInputNextFrame = 1;
  7577. // Edit in progress
  7578. const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
  7579. const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
  7580. const bool osx_double_click_selects_words = io.OptMacOSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
  7581. if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0]))
  7582. {
  7583. edit_state.SelectAll();
  7584. edit_state.SelectedAllMouseLock = true;
  7585. }
  7586. else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0])
  7587. {
  7588. // Select a word only, OS X style (by simulating keystrokes)
  7589. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
  7590. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
  7591. }
  7592. else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
  7593. {
  7594. if (hovered)
  7595. {
  7596. stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  7597. edit_state.CursorAnimReset();
  7598. }
  7599. }
  7600. else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
  7601. {
  7602. stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  7603. edit_state.CursorAnimReset();
  7604. edit_state.CursorFollow = true;
  7605. }
  7606. if (edit_state.SelectedAllMouseLock && !io.MouseDown[0])
  7607. edit_state.SelectedAllMouseLock = false;
  7608. if (io.InputCharacters[0])
  7609. {
  7610. // Process text input (before we check for Return because using some IME will effectively send a Return?)
  7611. // 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.
  7612. if (!(io.KeyCtrl && !io.KeyAlt) && is_editable)
  7613. {
  7614. for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++)
  7615. if (unsigned int c = (unsigned int)io.InputCharacters[n])
  7616. {
  7617. // Insert character if they pass filtering
  7618. if (!InputTextFilterCharacter(&c, flags, callback, user_data))
  7619. continue;
  7620. edit_state.OnKeyPressed((int)c);
  7621. }
  7622. }
  7623. // Consume characters
  7624. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  7625. }
  7626. }
  7627. bool cancel_edit = false;
  7628. if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
  7629. {
  7630. // Handle key-presses
  7631. const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
  7632. const bool is_shortcut_key_only = (io.OptMacOSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
  7633. const bool is_wordmove_key_down = io.OptMacOSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
  7634. const bool is_startend_key_down = io.OptMacOSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
  7635. const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper;
  7636. const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
  7637. const bool is_cut = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection());
  7638. const bool is_copy = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection());
  7639. const bool is_paste = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable;
  7640. if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
  7641. else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
  7642. else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
  7643. else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
  7644. else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
  7645. else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
  7646. else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
  7647. else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable)
  7648. {
  7649. if (!edit_state.HasSelection())
  7650. {
  7651. if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
  7652. else if (io.OptMacOSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
  7653. }
  7654. edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
  7655. }
  7656. else if (IsKeyPressedMap(ImGuiKey_Enter))
  7657. {
  7658. bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
  7659. if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
  7660. {
  7661. enter_pressed = clear_active_id = true;
  7662. }
  7663. else if (is_editable)
  7664. {
  7665. unsigned int c = '\n'; // Insert new line
  7666. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  7667. edit_state.OnKeyPressed((int)c);
  7668. }
  7669. }
  7670. else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable)
  7671. {
  7672. unsigned int c = '\t'; // Insert TAB
  7673. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  7674. edit_state.OnKeyPressed((int)c);
  7675. }
  7676. else if (IsKeyPressedMap(ImGuiKey_Escape)) { clear_active_id = cancel_edit = true; }
  7677. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
  7678. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
  7679. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
  7680. else if (is_cut || is_copy)
  7681. {
  7682. // Cut, Copy
  7683. if (io.SetClipboardTextFn)
  7684. {
  7685. const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
  7686. const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW;
  7687. edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1);
  7688. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie);
  7689. SetClipboardText(edit_state.TempTextBuffer.Data);
  7690. }
  7691. if (is_cut)
  7692. {
  7693. if (!edit_state.HasSelection())
  7694. edit_state.SelectAll();
  7695. edit_state.CursorFollow = true;
  7696. stb_textedit_cut(&edit_state, &edit_state.StbState);
  7697. }
  7698. }
  7699. else if (is_paste)
  7700. {
  7701. // Paste
  7702. if (const char* clipboard = GetClipboardText())
  7703. {
  7704. // Filter pasted buffer
  7705. const int clipboard_len = (int)strlen(clipboard);
  7706. ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar));
  7707. int clipboard_filtered_len = 0;
  7708. for (const char* s = clipboard; *s; )
  7709. {
  7710. unsigned int c;
  7711. s += ImTextCharFromUtf8(&c, s, NULL);
  7712. if (c == 0)
  7713. break;
  7714. if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data))
  7715. continue;
  7716. clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
  7717. }
  7718. clipboard_filtered[clipboard_filtered_len] = 0;
  7719. if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
  7720. {
  7721. stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len);
  7722. edit_state.CursorFollow = true;
  7723. }
  7724. ImGui::MemFree(clipboard_filtered);
  7725. }
  7726. }
  7727. }
  7728. if (g.ActiveId == id)
  7729. {
  7730. if (cancel_edit)
  7731. {
  7732. // Restore initial value
  7733. if (is_editable)
  7734. {
  7735. ImStrncpy(buf, edit_state.InitialText.Data, buf_size);
  7736. value_changed = true;
  7737. }
  7738. }
  7739. // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
  7740. // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage.
  7741. bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
  7742. if (apply_edit_back_to_user_buffer)
  7743. {
  7744. // Apply new value immediately - copy modified buffer back
  7745. // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
  7746. // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
  7747. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
  7748. if (is_editable)
  7749. {
  7750. edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4);
  7751. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL);
  7752. }
  7753. // User callback
  7754. if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
  7755. {
  7756. IM_ASSERT(callback != NULL);
  7757. // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
  7758. ImGuiInputTextFlags event_flag = 0;
  7759. ImGuiKey event_key = ImGuiKey_COUNT;
  7760. if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
  7761. {
  7762. event_flag = ImGuiInputTextFlags_CallbackCompletion;
  7763. event_key = ImGuiKey_Tab;
  7764. }
  7765. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
  7766. {
  7767. event_flag = ImGuiInputTextFlags_CallbackHistory;
  7768. event_key = ImGuiKey_UpArrow;
  7769. }
  7770. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
  7771. {
  7772. event_flag = ImGuiInputTextFlags_CallbackHistory;
  7773. event_key = ImGuiKey_DownArrow;
  7774. }
  7775. else if (flags & ImGuiInputTextFlags_CallbackAlways)
  7776. event_flag = ImGuiInputTextFlags_CallbackAlways;
  7777. if (event_flag)
  7778. {
  7779. ImGuiTextEditCallbackData callback_data;
  7780. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  7781. callback_data.EventFlag = event_flag;
  7782. callback_data.Flags = flags;
  7783. callback_data.UserData = user_data;
  7784. callback_data.ReadOnly = !is_editable;
  7785. callback_data.EventKey = event_key;
  7786. callback_data.Buf = edit_state.TempTextBuffer.Data;
  7787. callback_data.BufTextLen = edit_state.CurLenA;
  7788. callback_data.BufSize = edit_state.BufSizeA;
  7789. callback_data.BufDirty = false;
  7790. // 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)
  7791. ImWchar* text = edit_state.Text.Data;
  7792. const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor);
  7793. const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start);
  7794. const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end);
  7795. // Call user code
  7796. callback(&callback_data);
  7797. // Read back what user may have modified
  7798. IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields
  7799. IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
  7800. IM_ASSERT(callback_data.Flags == flags);
  7801. if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos);
  7802. if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart);
  7803. if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd);
  7804. if (callback_data.BufDirty)
  7805. {
  7806. IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
  7807. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL);
  7808. edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
  7809. edit_state.CursorAnimReset();
  7810. }
  7811. }
  7812. }
  7813. // Copy back to user buffer
  7814. if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
  7815. {
  7816. ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size);
  7817. value_changed = true;
  7818. }
  7819. }
  7820. }
  7821. // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
  7822. if (clear_active_id && g.ActiveId == id)
  7823. ClearActiveID();
  7824. // Render
  7825. // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on.
  7826. const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
  7827. if (!is_multiline)
  7828. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7829. 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
  7830. ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
  7831. ImVec2 text_size(0.f, 0.f);
  7832. const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY"));
  7833. if (g.ActiveId == id || is_currently_scrolling)
  7834. {
  7835. edit_state.CursorAnim += io.DeltaTime;
  7836. // This is going to be messy. We need to:
  7837. // - Display the text (this alone can be more easily clipped)
  7838. // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
  7839. // - Measure text height (for scrollbar)
  7840. // 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)
  7841. // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
  7842. const ImWchar* text_begin = edit_state.Text.Data;
  7843. ImVec2 cursor_offset, select_start_offset;
  7844. {
  7845. // Count lines + find lines numbers straddling 'cursor' and 'select_start' position.
  7846. const ImWchar* searches_input_ptr[2];
  7847. searches_input_ptr[0] = text_begin + edit_state.StbState.cursor;
  7848. searches_input_ptr[1] = NULL;
  7849. int searches_remaining = 1;
  7850. int searches_result_line_number[2] = { -1, -999 };
  7851. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  7852. {
  7853. searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  7854. searches_result_line_number[1] = -1;
  7855. searches_remaining++;
  7856. }
  7857. // Iterate all lines to find our line numbers
  7858. // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
  7859. searches_remaining += is_multiline ? 1 : 0;
  7860. int line_count = 0;
  7861. for (const ImWchar* s = text_begin; *s != 0; s++)
  7862. if (*s == '\n')
  7863. {
  7864. line_count++;
  7865. if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; }
  7866. if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; }
  7867. }
  7868. line_count++;
  7869. if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count;
  7870. if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count;
  7871. // Calculate 2d position by finding the beginning of the line and measuring distance
  7872. cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
  7873. cursor_offset.y = searches_result_line_number[0] * g.FontSize;
  7874. if (searches_result_line_number[1] >= 0)
  7875. {
  7876. select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
  7877. select_start_offset.y = searches_result_line_number[1] * g.FontSize;
  7878. }
  7879. // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
  7880. if (is_multiline)
  7881. text_size = ImVec2(size.x, line_count * g.FontSize);
  7882. }
  7883. // Scroll
  7884. if (edit_state.CursorFollow)
  7885. {
  7886. // Horizontal scroll in chunks of quarter width
  7887. if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
  7888. {
  7889. const float scroll_increment_x = size.x * 0.25f;
  7890. if (cursor_offset.x < edit_state.ScrollX)
  7891. edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
  7892. else if (cursor_offset.x - size.x >= edit_state.ScrollX)
  7893. edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
  7894. }
  7895. else
  7896. {
  7897. edit_state.ScrollX = 0.0f;
  7898. }
  7899. // Vertical scroll
  7900. if (is_multiline)
  7901. {
  7902. float scroll_y = draw_window->Scroll.y;
  7903. if (cursor_offset.y - g.FontSize < scroll_y)
  7904. scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
  7905. else if (cursor_offset.y - size.y >= scroll_y)
  7906. scroll_y = cursor_offset.y - size.y;
  7907. draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag
  7908. draw_window->Scroll.y = scroll_y;
  7909. render_pos.y = draw_window->DC.CursorPos.y;
  7910. }
  7911. }
  7912. edit_state.CursorFollow = false;
  7913. const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f);
  7914. // Draw selection
  7915. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  7916. {
  7917. const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  7918. const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end);
  7919. 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.
  7920. float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
  7921. ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg);
  7922. ImVec2 rect_pos = render_pos + select_start_offset - render_scroll;
  7923. for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
  7924. {
  7925. if (rect_pos.y > clip_rect.w + g.FontSize)
  7926. break;
  7927. if (rect_pos.y < clip_rect.y)
  7928. {
  7929. while (p < text_selected_end)
  7930. if (*p++ == '\n')
  7931. break;
  7932. }
  7933. else
  7934. {
  7935. ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
  7936. 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
  7937. ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
  7938. rect.ClipWith(clip_rect);
  7939. if (rect.Overlaps(clip_rect))
  7940. draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
  7941. }
  7942. rect_pos.x = render_pos.x - render_scroll.x;
  7943. rect_pos.y += g.FontSize;
  7944. }
  7945. }
  7946. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
  7947. // Draw blinking cursor
  7948. bool cursor_is_visible = (!g.IO.OptCursorBlink) || (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
  7949. ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll;
  7950. ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f);
  7951. if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
  7952. draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
  7953. // 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.)
  7954. if (is_editable)
  7955. g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize);
  7956. }
  7957. else
  7958. {
  7959. // Render text only
  7960. const char* buf_end = NULL;
  7961. if (is_multiline)
  7962. text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width
  7963. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect);
  7964. }
  7965. if (is_multiline)
  7966. {
  7967. Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
  7968. EndChildFrame();
  7969. EndGroup();
  7970. }
  7971. if (is_password)
  7972. PopFont();
  7973. // Log as text
  7974. if (g.LogEnabled && !is_password)
  7975. LogRenderedText(&render_pos, buf_display, NULL);
  7976. if (label_size.x > 0)
  7977. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  7978. if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
  7979. return enter_pressed;
  7980. else
  7981. return value_changed;
  7982. }
  7983. bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7984. {
  7985. IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
  7986. return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
  7987. }
  7988. bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7989. {
  7990. return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
  7991. }
  7992. // NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
  7993. 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)
  7994. {
  7995. ImGuiWindow* window = GetCurrentWindow();
  7996. if (window->SkipItems)
  7997. return false;
  7998. ImGuiContext& g = *GImGui;
  7999. const ImGuiStyle& style = g.Style;
  8000. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8001. BeginGroup();
  8002. PushID(label);
  8003. const ImVec2 button_sz = ImVec2(GetFrameHeight(), GetFrameHeight());
  8004. if (step_ptr)
  8005. PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
  8006. char buf[64];
  8007. DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
  8008. bool value_changed = false;
  8009. if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
  8010. extra_flags |= ImGuiInputTextFlags_CharsDecimal;
  8011. extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
  8012. if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view
  8013. value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
  8014. // Step buttons
  8015. if (step_ptr)
  8016. {
  8017. PopItemWidth();
  8018. SameLine(0, style.ItemInnerSpacing.x);
  8019. if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  8020. {
  8021. DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  8022. value_changed = true;
  8023. }
  8024. SameLine(0, style.ItemInnerSpacing.x);
  8025. if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  8026. {
  8027. DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  8028. value_changed = true;
  8029. }
  8030. }
  8031. PopID();
  8032. if (label_size.x > 0)
  8033. {
  8034. SameLine(0, style.ItemInnerSpacing.x);
  8035. RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
  8036. ItemSize(label_size, style.FramePadding.y);
  8037. }
  8038. EndGroup();
  8039. return value_changed;
  8040. }
  8041. bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
  8042. {
  8043. char display_format[16];
  8044. if (decimal_precision < 0)
  8045. 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
  8046. else
  8047. ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision);
  8048. 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);
  8049. }
  8050. bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags)
  8051. {
  8052. // 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.
  8053. const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
  8054. 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);
  8055. }
  8056. bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
  8057. {
  8058. ImGuiWindow* window = GetCurrentWindow();
  8059. if (window->SkipItems)
  8060. return false;
  8061. ImGuiContext& g = *GImGui;
  8062. bool value_changed = false;
  8063. BeginGroup();
  8064. PushID(label);
  8065. PushMultiItemsWidths(components);
  8066. for (int i = 0; i < components; i++)
  8067. {
  8068. PushID(i);
  8069. value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
  8070. SameLine(0, g.Style.ItemInnerSpacing.x);
  8071. PopID();
  8072. PopItemWidth();
  8073. }
  8074. PopID();
  8075. TextUnformatted(label, FindRenderedTextEnd(label));
  8076. EndGroup();
  8077. return value_changed;
  8078. }
  8079. bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8080. {
  8081. return InputFloatN(label, v, 2, decimal_precision, extra_flags);
  8082. }
  8083. bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8084. {
  8085. return InputFloatN(label, v, 3, decimal_precision, extra_flags);
  8086. }
  8087. bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8088. {
  8089. return InputFloatN(label, v, 4, decimal_precision, extra_flags);
  8090. }
  8091. bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
  8092. {
  8093. ImGuiWindow* window = GetCurrentWindow();
  8094. if (window->SkipItems)
  8095. return false;
  8096. ImGuiContext& g = *GImGui;
  8097. bool value_changed = false;
  8098. BeginGroup();
  8099. PushID(label);
  8100. PushMultiItemsWidths(components);
  8101. for (int i = 0; i < components; i++)
  8102. {
  8103. PushID(i);
  8104. value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags);
  8105. SameLine(0, g.Style.ItemInnerSpacing.x);
  8106. PopID();
  8107. PopItemWidth();
  8108. }
  8109. PopID();
  8110. TextUnformatted(label, FindRenderedTextEnd(label));
  8111. EndGroup();
  8112. return value_changed;
  8113. }
  8114. bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
  8115. {
  8116. return InputIntN(label, v, 2, extra_flags);
  8117. }
  8118. bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
  8119. {
  8120. return InputIntN(label, v, 3, extra_flags);
  8121. }
  8122. bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
  8123. {
  8124. return InputIntN(label, v, 4, extra_flags);
  8125. }
  8126. static float CalcMaxPopupHeightFromItemCount(int items_count)
  8127. {
  8128. ImGuiContext& g = *GImGui;
  8129. if (items_count <= 0)
  8130. return FLT_MAX;
  8131. return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
  8132. }
  8133. bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
  8134. {
  8135. // Always consume the SetNextWindowSizeConstraint() call in our early return paths
  8136. ImGuiContext& g = *GImGui;
  8137. ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond;
  8138. g.NextWindowData.SizeConstraintCond = 0;
  8139. ImGuiWindow* window = GetCurrentWindow();
  8140. if (window->SkipItems)
  8141. return false;
  8142. const ImGuiStyle& style = g.Style;
  8143. const ImGuiID id = window->GetID(label);
  8144. const float w = CalcItemWidth();
  8145. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8146. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  8147. 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));
  8148. ItemSize(total_bb, style.FramePadding.y);
  8149. if (!ItemAdd(total_bb, id))
  8150. return false;
  8151. bool hovered, held;
  8152. bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
  8153. bool popup_open = IsPopupOpen(id);
  8154. const float arrow_size = GetFrameHeight();
  8155. const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
  8156. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  8157. RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
  8158. RenderTriangle(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down);
  8159. if (preview_value != NULL)
  8160. RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
  8161. if (label_size.x > 0)
  8162. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8163. if (pressed && !popup_open)
  8164. {
  8165. OpenPopupEx(id);
  8166. popup_open = true;
  8167. }
  8168. if (!popup_open)
  8169. return false;
  8170. if (backup_next_window_size_constraint)
  8171. {
  8172. g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint;
  8173. g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
  8174. }
  8175. else
  8176. {
  8177. if ((flags & ImGuiComboFlags_HeightMask_) == 0)
  8178. flags |= ImGuiComboFlags_HeightRegular;
  8179. IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
  8180. int popup_max_height_in_items = -1;
  8181. if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
  8182. else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
  8183. else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
  8184. SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
  8185. }
  8186. char name[16];
  8187. ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
  8188. // Peak into expected window size so we can position it
  8189. if (ImGuiWindow* popup_window = FindWindowByName(name))
  8190. if (popup_window->WasActive)
  8191. {
  8192. ImVec2 size_contents = CalcSizeContents(popup_window);
  8193. ImVec2 size_expected = CalcSizeAfterConstraint(popup_window, CalcSizeAutoFit(popup_window, size_contents));
  8194. if (flags & ImGuiComboFlags_PopupAlignLeft)
  8195. popup_window->AutoPosLastDirection = ImGuiDir_Left;
  8196. ImVec2 pos = FindBestWindowPosForPopup(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
  8197. SetNextWindowPos(pos);
  8198. }
  8199. ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
  8200. if (!Begin(name, NULL, window_flags))
  8201. {
  8202. EndPopup();
  8203. IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
  8204. return false;
  8205. }
  8206. // Horizontally align ourselves with the framed text
  8207. if (style.FramePadding.x != style.WindowPadding.x)
  8208. Indent(style.FramePadding.x - style.WindowPadding.x);
  8209. return true;
  8210. }
  8211. void ImGui::EndCombo()
  8212. {
  8213. const ImGuiStyle& style = GImGui->Style;
  8214. if (style.FramePadding.x != style.WindowPadding.x)
  8215. Unindent(style.FramePadding.x - style.WindowPadding.x);
  8216. EndPopup();
  8217. }
  8218. // Old API, prefer using BeginCombo() nowadays if you can.
  8219. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)
  8220. {
  8221. ImGuiContext& g = *GImGui;
  8222. const char* preview_text = NULL;
  8223. if (*current_item >= 0 && *current_item < items_count)
  8224. items_getter(data, *current_item, &preview_text);
  8225. // The old Combo() API exposed "popup_max_height_in_items", however the new more general BeginCombo() API doesn't, so we emulate it here.
  8226. if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond)
  8227. {
  8228. float popup_max_height = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
  8229. SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, popup_max_height));
  8230. }
  8231. if (!BeginCombo(label, preview_text, 0))
  8232. return false;
  8233. // Display items
  8234. // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)
  8235. bool value_changed = false;
  8236. for (int i = 0; i < items_count; i++)
  8237. {
  8238. PushID((void*)(intptr_t)i);
  8239. const bool item_selected = (i == *current_item);
  8240. const char* item_text;
  8241. if (!items_getter(data, i, &item_text))
  8242. item_text = "*Unknown item*";
  8243. if (Selectable(item_text, item_selected))
  8244. {
  8245. value_changed = true;
  8246. *current_item = i;
  8247. }
  8248. if (item_selected)
  8249. SetItemDefaultFocus();
  8250. PopID();
  8251. }
  8252. EndCombo();
  8253. return value_changed;
  8254. }
  8255. static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
  8256. {
  8257. const char* const* items = (const char* const*)data;
  8258. if (out_text)
  8259. *out_text = items[idx];
  8260. return true;
  8261. }
  8262. static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
  8263. {
  8264. // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
  8265. const char* items_separated_by_zeros = (const char*)data;
  8266. int items_count = 0;
  8267. const char* p = items_separated_by_zeros;
  8268. while (*p)
  8269. {
  8270. if (idx == items_count)
  8271. break;
  8272. p += strlen(p) + 1;
  8273. items_count++;
  8274. }
  8275. if (!*p)
  8276. return false;
  8277. if (out_text)
  8278. *out_text = p;
  8279. return true;
  8280. }
  8281. // Combo box helper allowing to pass an array of strings.
  8282. bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
  8283. {
  8284. const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
  8285. return value_changed;
  8286. }
  8287. // Combo box helper allowing to pass all items in a single string.
  8288. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
  8289. {
  8290. int items_count = 0;
  8291. const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
  8292. while (*p)
  8293. {
  8294. p += strlen(p) + 1;
  8295. items_count++;
  8296. }
  8297. bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
  8298. return value_changed;
  8299. }
  8300. // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image.
  8301. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID.
  8302. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  8303. {
  8304. ImGuiWindow* window = GetCurrentWindow();
  8305. if (window->SkipItems)
  8306. return false;
  8307. ImGuiContext& g = *GImGui;
  8308. const ImGuiStyle& style = g.Style;
  8309. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped.
  8310. PopClipRect();
  8311. ImGuiID id = window->GetID(label);
  8312. ImVec2 label_size = CalcTextSize(label, NULL, true);
  8313. ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
  8314. ImVec2 pos = window->DC.CursorPos;
  8315. pos.y += window->DC.CurrentLineTextBaseOffset;
  8316. ImRect bb(pos, pos + size);
  8317. ItemSize(bb);
  8318. // Fill horizontal space.
  8319. ImVec2 window_padding = window->WindowPadding;
  8320. float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
  8321. float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x);
  8322. 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);
  8323. ImRect bb_with_spacing(pos, pos + size_draw);
  8324. if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
  8325. bb_with_spacing.Max.x += window_padding.x;
  8326. // Selectables are tightly packed together, we extend the box to cover spacing between selectable.
  8327. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
  8328. float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
  8329. float spacing_R = style.ItemSpacing.x - spacing_L;
  8330. float spacing_D = style.ItemSpacing.y - spacing_U;
  8331. bb_with_spacing.Min.x -= spacing_L;
  8332. bb_with_spacing.Min.y -= spacing_U;
  8333. bb_with_spacing.Max.x += spacing_R;
  8334. bb_with_spacing.Max.y += spacing_D;
  8335. if (!ItemAdd(bb_with_spacing, id))
  8336. {
  8337. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
  8338. PushColumnClipRect();
  8339. return false;
  8340. }
  8341. ImGuiButtonFlags button_flags = 0;
  8342. if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_NoHoldingActiveID;
  8343. if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnRelease;
  8344. if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
  8345. if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
  8346. bool hovered, held;
  8347. bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
  8348. if (flags & ImGuiSelectableFlags_Disabled)
  8349. selected = false;
  8350. // Render
  8351. if (hovered || selected)
  8352. {
  8353. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  8354. RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
  8355. }
  8356. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
  8357. {
  8358. PushColumnClipRect();
  8359. bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
  8360. }
  8361. if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  8362. RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f));
  8363. if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
  8364. // Automatically close popups
  8365. if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
  8366. CloseCurrentPopup();
  8367. return pressed;
  8368. }
  8369. bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  8370. {
  8371. if (Selectable(label, *p_selected, flags, size_arg))
  8372. {
  8373. *p_selected = !*p_selected;
  8374. return true;
  8375. }
  8376. return false;
  8377. }
  8378. // Helper to calculate the size of a listbox and display a label on the right.
  8379. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty"
  8380. bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
  8381. {
  8382. ImGuiWindow* window = GetCurrentWindow();
  8383. if (window->SkipItems)
  8384. return false;
  8385. const ImGuiStyle& style = GetStyle();
  8386. const ImGuiID id = GetID(label);
  8387. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8388. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  8389. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
  8390. ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
  8391. ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
  8392. ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  8393. window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy.
  8394. BeginGroup();
  8395. if (label_size.x > 0)
  8396. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8397. BeginChildFrame(id, frame_bb.GetSize());
  8398. return true;
  8399. }
  8400. bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
  8401. {
  8402. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  8403. // 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.
  8404. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
  8405. if (height_in_items < 0)
  8406. height_in_items = ImMin(items_count, 7);
  8407. float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f);
  8408. // 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().
  8409. ImVec2 size;
  8410. size.x = 0.0f;
  8411. size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y;
  8412. return ListBoxHeader(label, size);
  8413. }
  8414. void ImGui::ListBoxFooter()
  8415. {
  8416. ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow;
  8417. const ImRect bb = parent_window->DC.LastItemRect;
  8418. const ImGuiStyle& style = GetStyle();
  8419. EndChildFrame();
  8420. // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
  8421. // We call SameLine() to restore DC.CurrentLine* data
  8422. SameLine();
  8423. parent_window->DC.CursorPos = bb.Min;
  8424. ItemSize(bb, style.FramePadding.y);
  8425. EndGroup();
  8426. }
  8427. bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
  8428. {
  8429. const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
  8430. return value_changed;
  8431. }
  8432. 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)
  8433. {
  8434. if (!ListBoxHeader(label, items_count, height_in_items))
  8435. return false;
  8436. // 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.
  8437. bool value_changed = false;
  8438. ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
  8439. while (clipper.Step())
  8440. for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
  8441. {
  8442. const bool item_selected = (i == *current_item);
  8443. const char* item_text;
  8444. if (!items_getter(data, i, &item_text))
  8445. item_text = "*Unknown item*";
  8446. PushID(i);
  8447. if (Selectable(item_text, item_selected))
  8448. {
  8449. *current_item = i;
  8450. value_changed = true;
  8451. }
  8452. PopID();
  8453. }
  8454. ListBoxFooter();
  8455. return value_changed;
  8456. }
  8457. bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
  8458. {
  8459. ImGuiWindow* window = GetCurrentWindow();
  8460. if (window->SkipItems)
  8461. return false;
  8462. ImGuiContext& g = *GImGui;
  8463. ImGuiStyle& style = g.Style;
  8464. ImVec2 pos = window->DC.CursorPos;
  8465. ImVec2 label_size = CalcTextSize(label, NULL, true);
  8466. ImGuiSelectableFlags flags = ImGuiSelectableFlags_MenuItem | (enabled ? 0 : ImGuiSelectableFlags_Disabled);
  8467. bool pressed;
  8468. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  8469. {
  8470. // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
  8471. // Note that in this situation we render neither the shortcut neither the selected tick mark
  8472. float w = label_size.x;
  8473. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  8474. PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
  8475. pressed = Selectable(label, false, flags, ImVec2(w, 0.0f));
  8476. PopStyleVar();
  8477. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
  8478. }
  8479. else
  8480. {
  8481. ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
  8482. float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
  8483. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  8484. pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f));
  8485. if (shortcut_size.x > 0.0f)
  8486. {
  8487. PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  8488. RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
  8489. PopStyleColor();
  8490. }
  8491. if (selected)
  8492. RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f);
  8493. }
  8494. return pressed;
  8495. }
  8496. bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
  8497. {
  8498. if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
  8499. {
  8500. if (p_selected)
  8501. *p_selected = !*p_selected;
  8502. return true;
  8503. }
  8504. return false;
  8505. }
  8506. bool ImGui::BeginMainMenuBar()
  8507. {
  8508. ImGuiContext& g = *GImGui;
  8509. SetNextWindowPos(ImVec2(0.0f, 0.0f));
  8510. SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
  8511. PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  8512. PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
  8513. if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar)
  8514. || !BeginMenuBar())
  8515. {
  8516. End();
  8517. PopStyleVar(2);
  8518. return false;
  8519. }
  8520. g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
  8521. return true;
  8522. }
  8523. void ImGui::EndMainMenuBar()
  8524. {
  8525. EndMenuBar();
  8526. End();
  8527. PopStyleVar(2);
  8528. }
  8529. bool ImGui::BeginMenuBar()
  8530. {
  8531. ImGuiWindow* window = GetCurrentWindow();
  8532. if (window->SkipItems)
  8533. return false;
  8534. if (!(window->Flags & ImGuiWindowFlags_MenuBar))
  8535. return false;
  8536. IM_ASSERT(!window->DC.MenuBarAppending);
  8537. BeginGroup(); // Save position
  8538. PushID("##menubar");
  8539. // We don't clip with regular window clipping rectangle as it is already set to the area below. However we clip with window full rect.
  8540. // We remove 1 worth of rounding to Max.x to that text in long menus don't tend to display over the lower-right rounded area, which looks particularly glitchy.
  8541. ImRect bar_rect = window->MenuBarRect();
  8542. ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f));
  8543. clip_rect.ClipWith(window->WindowRectClipped);
  8544. PushClipRect(clip_rect.Min, clip_rect.Max, false);
  8545. window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffsetX, bar_rect.Min.y);// + g.Style.FramePadding.y);
  8546. window->DC.LayoutType = ImGuiLayoutType_Horizontal;
  8547. window->DC.MenuBarAppending = true;
  8548. AlignTextToFramePadding();
  8549. return true;
  8550. }
  8551. void ImGui::EndMenuBar()
  8552. {
  8553. ImGuiWindow* window = GetCurrentWindow();
  8554. if (window->SkipItems)
  8555. return;
  8556. IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
  8557. IM_ASSERT(window->DC.MenuBarAppending);
  8558. PopClipRect();
  8559. PopID();
  8560. window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
  8561. window->DC.GroupStack.back().AdvanceCursor = false;
  8562. EndGroup();
  8563. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  8564. window->DC.MenuBarAppending = false;
  8565. }
  8566. bool ImGui::BeginMenu(const char* label, bool enabled)
  8567. {
  8568. ImGuiWindow* window = GetCurrentWindow();
  8569. if (window->SkipItems)
  8570. return false;
  8571. ImGuiContext& g = *GImGui;
  8572. const ImGuiStyle& style = g.Style;
  8573. const ImGuiID id = window->GetID(label);
  8574. ImVec2 label_size = CalcTextSize(label, NULL, true);
  8575. bool pressed;
  8576. bool menu_is_open = IsPopupOpen(id);
  8577. bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].OpenParentId == window->IDStack.back());
  8578. ImGuiWindow* backed_nav_window = g.NavWindow;
  8579. if (menuset_is_open)
  8580. g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
  8581. // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos).
  8582. ImVec2 popup_pos, pos = window->DC.CursorPos;
  8583. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  8584. {
  8585. // Menu inside an horizontal menu bar
  8586. // Selectable extend their highlight by half ItemSpacing in each direction.
  8587. // For ChildMenu, the popup position will be overwritten by the call to FindBestPopupWindowPos() in Begin()
  8588. popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
  8589. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  8590. PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
  8591. float w = label_size.x;
  8592. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  8593. PopStyleVar();
  8594. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
  8595. }
  8596. else
  8597. {
  8598. // Menu inside a menu
  8599. popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
  8600. float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
  8601. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  8602. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  8603. if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  8604. RenderTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right);
  8605. if (!enabled) PopStyleColor();
  8606. }
  8607. const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id);
  8608. if (menuset_is_open)
  8609. g.NavWindow = backed_nav_window;
  8610. bool want_open = false, want_close = false;
  8611. if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
  8612. {
  8613. // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
  8614. bool moving_within_opened_triangle = false;
  8615. if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window)
  8616. {
  8617. if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window)
  8618. {
  8619. ImRect next_window_rect = next_window->Rect();
  8620. ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
  8621. ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
  8622. ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
  8623. float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
  8624. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
  8625. 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 // FIXME: Multiply by fb_scale?
  8626. tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
  8627. moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
  8628. //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug
  8629. }
  8630. }
  8631. want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
  8632. want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
  8633. }
  8634. else
  8635. {
  8636. // Menu bar
  8637. if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
  8638. {
  8639. want_close = true;
  8640. want_open = menu_is_open = false;
  8641. }
  8642. else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
  8643. {
  8644. want_open = true;
  8645. }
  8646. }
  8647. if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
  8648. want_close = true;
  8649. if (want_close && IsPopupOpen(id))
  8650. ClosePopupToLevel(GImGui->CurrentPopupStack.Size);
  8651. if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size)
  8652. {
  8653. // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
  8654. OpenPopup(label);
  8655. return false;
  8656. }
  8657. menu_is_open |= want_open;
  8658. if (want_open)
  8659. OpenPopup(label);
  8660. if (menu_is_open)
  8661. {
  8662. SetNextWindowPos(popup_pos, ImGuiCond_Always);
  8663. ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
  8664. menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  8665. }
  8666. return menu_is_open;
  8667. }
  8668. void ImGui::EndMenu()
  8669. {
  8670. EndPopup();
  8671. }
  8672. // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  8673. void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
  8674. {
  8675. ImGuiContext& g = *GImGui;
  8676. int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
  8677. BeginTooltipEx(0, true);
  8678. const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
  8679. if (text_end > text)
  8680. {
  8681. TextUnformatted(text, text_end);
  8682. Separator();
  8683. }
  8684. ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
  8685. ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
  8686. SameLine();
  8687. if (flags & ImGuiColorEditFlags_NoAlpha)
  8688. Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
  8689. else
  8690. Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
  8691. EndTooltip();
  8692. }
  8693. static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b)
  8694. {
  8695. float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
  8696. int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
  8697. int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
  8698. int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
  8699. return IM_COL32(r, g, b, 0xFF);
  8700. }
  8701. // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
  8702. // I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether.
  8703. void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
  8704. {
  8705. ImGuiWindow* window = GetCurrentWindow();
  8706. if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
  8707. {
  8708. ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col));
  8709. ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col));
  8710. window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags);
  8711. int yi = 0;
  8712. for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
  8713. {
  8714. float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
  8715. if (y2 <= y1)
  8716. continue;
  8717. for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
  8718. {
  8719. float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
  8720. if (x2 <= x1)
  8721. continue;
  8722. int rounding_corners_flags_cell = 0;
  8723. if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; }
  8724. if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; }
  8725. rounding_corners_flags_cell &= rounding_corners_flags;
  8726. window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
  8727. }
  8728. }
  8729. }
  8730. else
  8731. {
  8732. window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
  8733. }
  8734. }
  8735. void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
  8736. {
  8737. ImGuiContext& g = *GImGui;
  8738. if ((flags & ImGuiColorEditFlags__InputsMask) == 0)
  8739. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask;
  8740. if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
  8741. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
  8742. if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
  8743. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
  8744. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected
  8745. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected
  8746. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected
  8747. g.ColorEditOptions = flags;
  8748. }
  8749. // A little colored square. Return true when clicked.
  8750. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
  8751. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
  8752. bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
  8753. {
  8754. ImGuiWindow* window = GetCurrentWindow();
  8755. if (window->SkipItems)
  8756. return false;
  8757. ImGuiContext& g = *GImGui;
  8758. const ImGuiID id = window->GetID(desc_id);
  8759. float default_size = GetFrameHeight();
  8760. if (size.x == 0.0f)
  8761. size.x = default_size;
  8762. if (size.y == 0.0f)
  8763. size.y = default_size;
  8764. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  8765. ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
  8766. if (!ItemAdd(bb, id))
  8767. return false;
  8768. bool hovered, held;
  8769. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  8770. if (flags & ImGuiColorEditFlags_NoAlpha)
  8771. flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
  8772. ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f);
  8773. float grid_step = ImMin(size.x, size.y) / 2.99f;
  8774. float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
  8775. ImRect bb_inner = bb;
  8776. float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
  8777. bb_inner.Expand(off);
  8778. if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f)
  8779. {
  8780. float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f);
  8781. RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight);
  8782. window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft);
  8783. }
  8784. else
  8785. {
  8786. // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
  8787. ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha;
  8788. if (col_source.w < 1.0f)
  8789. RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
  8790. else
  8791. window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
  8792. }
  8793. if (g.Style.FrameBorderSize > 0.0f)
  8794. RenderFrameBorder(bb.Min, bb.Max, rounding);
  8795. else
  8796. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
  8797. // Drag and Drop Source
  8798. if (g.ActiveId == id && BeginDragDropSource()) // NB: The ActiveId test is merely an optional micro-optimization
  8799. {
  8800. if (flags & ImGuiColorEditFlags_NoAlpha)
  8801. SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col, sizeof(float) * 3, ImGuiCond_Once);
  8802. else
  8803. SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once);
  8804. ColorButton(desc_id, col, flags);
  8805. SameLine();
  8806. TextUnformatted("Color");
  8807. EndDragDropSource();
  8808. hovered = false;
  8809. }
  8810. // Tooltip
  8811. if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)
  8812. ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
  8813. return pressed;
  8814. }
  8815. bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
  8816. {
  8817. return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
  8818. }
  8819. void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
  8820. {
  8821. bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask);
  8822. bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
  8823. if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
  8824. return;
  8825. ImGuiContext& g = *GImGui;
  8826. ImGuiColorEditFlags opts = g.ColorEditOptions;
  8827. if (allow_opt_inputs)
  8828. {
  8829. if (RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB;
  8830. if (RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV;
  8831. if (RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX;
  8832. }
  8833. if (allow_opt_datatype)
  8834. {
  8835. if (allow_opt_inputs) Separator();
  8836. if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
  8837. if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
  8838. }
  8839. if (allow_opt_inputs || allow_opt_datatype)
  8840. Separator();
  8841. if (Button("Copy as..", ImVec2(-1,0)))
  8842. OpenPopup("Copy");
  8843. if (BeginPopup("Copy"))
  8844. {
  8845. int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
  8846. char buf[64];
  8847. ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
  8848. if (Selectable(buf))
  8849. SetClipboardText(buf);
  8850. ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
  8851. if (Selectable(buf))
  8852. SetClipboardText(buf);
  8853. if (flags & ImGuiColorEditFlags_NoAlpha)
  8854. ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb);
  8855. else
  8856. ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca);
  8857. if (Selectable(buf))
  8858. SetClipboardText(buf);
  8859. EndPopup();
  8860. }
  8861. g.ColorEditOptions = opts;
  8862. EndPopup();
  8863. }
  8864. static void ColorPickerOptionsPopup(ImGuiColorEditFlags flags, const float* ref_col)
  8865. {
  8866. bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
  8867. bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
  8868. if ((!allow_opt_picker && !allow_opt_alpha_bar) || !ImGui::BeginPopup("context"))
  8869. return;
  8870. ImGuiContext& g = *GImGui;
  8871. if (allow_opt_picker)
  8872. {
  8873. ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
  8874. ImGui::PushItemWidth(picker_size.x);
  8875. for (int picker_type = 0; picker_type < 2; picker_type++)
  8876. {
  8877. // Draw small/thumbnail version of each picker type (over an invisible button for selection)
  8878. if (picker_type > 0) ImGui::Separator();
  8879. ImGui::PushID(picker_type);
  8880. ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha);
  8881. if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
  8882. if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
  8883. ImVec2 backup_pos = ImGui::GetCursorScreenPos();
  8884. if (ImGui::Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
  8885. g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
  8886. ImGui::SetCursorScreenPos(backup_pos);
  8887. ImVec4 dummy_ref_col;
  8888. memcpy(&dummy_ref_col.x, ref_col, sizeof(float) * (picker_flags & ImGuiColorEditFlags_NoAlpha ? 3 : 4));
  8889. ImGui::ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
  8890. ImGui::PopID();
  8891. }
  8892. ImGui::PopItemWidth();
  8893. }
  8894. if (allow_opt_alpha_bar)
  8895. {
  8896. if (allow_opt_picker) ImGui::Separator();
  8897. ImGui::CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
  8898. }
  8899. ImGui::EndPopup();
  8900. }
  8901. // Edit colors components (each component in 0.0f..1.0f range).
  8902. // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  8903. // With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
  8904. bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
  8905. {
  8906. ImGuiWindow* window = GetCurrentWindow();
  8907. if (window->SkipItems)
  8908. return false;
  8909. ImGuiContext& g = *GImGui;
  8910. const ImGuiStyle& style = g.Style;
  8911. const float square_sz = GetFrameHeight();
  8912. const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
  8913. const float w_items_all = CalcItemWidth() - w_extra;
  8914. const char* label_display_end = FindRenderedTextEnd(label);
  8915. const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
  8916. const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
  8917. const int components = alpha ? 4 : 3;
  8918. const ImGuiColorEditFlags flags_untouched = flags;
  8919. BeginGroup();
  8920. PushID(label);
  8921. // If we're not showing any slider there's no point in doing any HSV conversions
  8922. if (flags & ImGuiColorEditFlags_NoInputs)
  8923. flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions;
  8924. // Context menu: display and modify options (before defaults are applied)
  8925. if (!(flags & ImGuiColorEditFlags_NoOptions))
  8926. ColorEditOptionsPopup(col, flags);
  8927. // Read stored options
  8928. if (!(flags & ImGuiColorEditFlags__InputsMask))
  8929. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask);
  8930. if (!(flags & ImGuiColorEditFlags__DataTypeMask))
  8931. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
  8932. if (!(flags & ImGuiColorEditFlags__PickerMask))
  8933. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
  8934. flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask));
  8935. // Convert to the formats we need
  8936. float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
  8937. if (flags & ImGuiColorEditFlags_HSV)
  8938. ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
  8939. int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
  8940. bool value_changed = false;
  8941. bool value_changed_as_float = false;
  8942. if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
  8943. {
  8944. // RGB/HSV 0..255 Sliders
  8945. const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  8946. const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  8947. const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
  8948. const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
  8949. const char* fmt_table_int[3][4] =
  8950. {
  8951. { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, // Short display
  8952. { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, // Long display for RGBA
  8953. { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } // Long display for HSVA
  8954. };
  8955. const char* fmt_table_float[3][4] =
  8956. {
  8957. { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
  8958. { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
  8959. { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
  8960. };
  8961. const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1;
  8962. PushItemWidth(w_item_one);
  8963. for (int n = 0; n < components; n++)
  8964. {
  8965. if (n > 0)
  8966. SameLine(0, style.ItemInnerSpacing.x);
  8967. if (n + 1 == components)
  8968. PushItemWidth(w_item_last);
  8969. if (flags & ImGuiColorEditFlags_Float)
  8970. value_changed = value_changed_as_float = value_changed | DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
  8971. else
  8972. value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
  8973. if (!(flags & ImGuiColorEditFlags_NoOptions))
  8974. OpenPopupOnItemClick("context");
  8975. }
  8976. PopItemWidth();
  8977. PopItemWidth();
  8978. }
  8979. else if ((flags & ImGuiColorEditFlags_HEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
  8980. {
  8981. // RGB Hexadecimal Input
  8982. char buf[64];
  8983. if (alpha)
  8984. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255));
  8985. else
  8986. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255));
  8987. PushItemWidth(w_items_all);
  8988. if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
  8989. {
  8990. value_changed = true;
  8991. char* p = buf;
  8992. while (*p == '#' || ImCharIsSpace(*p))
  8993. p++;
  8994. i[0] = i[1] = i[2] = i[3] = 0;
  8995. if (alpha)
  8996. 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)
  8997. else
  8998. sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
  8999. }
  9000. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9001. OpenPopupOnItemClick("context");
  9002. PopItemWidth();
  9003. }
  9004. ImGuiWindow* picker_active_window = NULL;
  9005. if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
  9006. {
  9007. if (!(flags & ImGuiColorEditFlags_NoInputs))
  9008. SameLine(0, style.ItemInnerSpacing.x);
  9009. const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
  9010. if (ColorButton("##ColorButton", col_v4, flags))
  9011. {
  9012. if (!(flags & ImGuiColorEditFlags_NoPicker))
  9013. {
  9014. // Store current color and open a picker
  9015. g.ColorPickerRef = col_v4;
  9016. OpenPopup("picker");
  9017. SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y));
  9018. }
  9019. }
  9020. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9021. OpenPopupOnItemClick("context");
  9022. if (BeginPopup("picker"))
  9023. {
  9024. picker_active_window = g.CurrentWindow;
  9025. if (label != label_display_end)
  9026. {
  9027. TextUnformatted(label, label_display_end);
  9028. Separator();
  9029. }
  9030. ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
  9031. ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
  9032. PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
  9033. value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
  9034. PopItemWidth();
  9035. EndPopup();
  9036. }
  9037. }
  9038. if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
  9039. {
  9040. SameLine(0, style.ItemInnerSpacing.x);
  9041. TextUnformatted(label, label_display_end);
  9042. }
  9043. // Convert back
  9044. if (picker_active_window == NULL)
  9045. {
  9046. if (!value_changed_as_float)
  9047. for (int n = 0; n < 4; n++)
  9048. f[n] = i[n] / 255.0f;
  9049. if (flags & ImGuiColorEditFlags_HSV)
  9050. ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
  9051. if (value_changed)
  9052. {
  9053. col[0] = f[0];
  9054. col[1] = f[1];
  9055. col[2] = f[2];
  9056. if (alpha)
  9057. col[3] = f[3];
  9058. }
  9059. }
  9060. PopID();
  9061. EndGroup();
  9062. // Drag and Drop Target
  9063. if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && BeginDragDropTarget()) // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
  9064. {
  9065. if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
  9066. {
  9067. memcpy((float*)col, payload->Data, sizeof(float) * 3);
  9068. value_changed = true;
  9069. }
  9070. if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
  9071. {
  9072. memcpy((float*)col, payload->Data, sizeof(float) * components);
  9073. value_changed = true;
  9074. }
  9075. EndDragDropTarget();
  9076. }
  9077. // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
  9078. if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
  9079. window->DC.LastItemId = g.ActiveId;
  9080. return value_changed;
  9081. }
  9082. bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
  9083. {
  9084. float col4[4] = { col[0], col[1], col[2], 1.0f };
  9085. if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
  9086. return false;
  9087. col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
  9088. return true;
  9089. }
  9090. // 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side.
  9091. static void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col)
  9092. {
  9093. switch (direction)
  9094. {
  9095. case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return;
  9096. case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return;
  9097. case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return;
  9098. case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return;
  9099. case ImGuiDir_None: case ImGuiDir_Count_: break; // Fix warnings
  9100. }
  9101. }
  9102. static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w)
  9103. {
  9104. RenderArrow(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK);
  9105. RenderArrow(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE);
  9106. RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK);
  9107. RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE);
  9108. }
  9109. // ColorPicker
  9110. // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  9111. // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
  9112. bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
  9113. {
  9114. ImGuiContext& g = *GImGui;
  9115. ImGuiWindow* window = GetCurrentWindow();
  9116. ImDrawList* draw_list = window->DrawList;
  9117. ImGuiStyle& style = g.Style;
  9118. ImGuiIO& io = g.IO;
  9119. PushID(label);
  9120. BeginGroup();
  9121. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  9122. flags |= ImGuiColorEditFlags_NoSmallPreview;
  9123. // Context menu: display and store options.
  9124. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9125. ColorPickerOptionsPopup(flags, col);
  9126. // Read stored options
  9127. if (!(flags & ImGuiColorEditFlags__PickerMask))
  9128. flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
  9129. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected
  9130. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9131. flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
  9132. // Setup
  9133. int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
  9134. bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
  9135. ImVec2 picker_pos = window->DC.CursorPos;
  9136. float square_sz = GetFrameHeight();
  9137. float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
  9138. float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
  9139. float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
  9140. float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
  9141. float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f);
  9142. float backup_initial_col[4];
  9143. memcpy(backup_initial_col, col, components * sizeof(float));
  9144. float wheel_thickness = sv_picker_size * 0.08f;
  9145. float wheel_r_outer = sv_picker_size * 0.50f;
  9146. float wheel_r_inner = wheel_r_outer - wheel_thickness;
  9147. ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f);
  9148. // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
  9149. float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
  9150. ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
  9151. ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
  9152. ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
  9153. float H,S,V;
  9154. ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V);
  9155. bool value_changed = false, value_changed_h = false, value_changed_sv = false;
  9156. if (flags & ImGuiColorEditFlags_PickerHueWheel)
  9157. {
  9158. // Hue wheel + SV triangle logic
  9159. InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
  9160. if (IsItemActive())
  9161. {
  9162. ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
  9163. ImVec2 current_off = g.IO.MousePos - wheel_center;
  9164. float initial_dist2 = ImLengthSqr(initial_off);
  9165. if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1))
  9166. {
  9167. // Interactive with Hue wheel
  9168. H = atan2f(current_off.y, current_off.x) / IM_PI*0.5f;
  9169. if (H < 0.0f)
  9170. H += 1.0f;
  9171. value_changed = value_changed_h = true;
  9172. }
  9173. float cos_hue_angle = cosf(-H * 2.0f * IM_PI);
  9174. float sin_hue_angle = sinf(-H * 2.0f * IM_PI);
  9175. if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
  9176. {
  9177. // Interacting with SV triangle
  9178. ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
  9179. if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
  9180. current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
  9181. float uu, vv, ww;
  9182. ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
  9183. V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
  9184. S = ImClamp(uu / V, 0.0001f, 1.0f);
  9185. value_changed = value_changed_sv = true;
  9186. }
  9187. }
  9188. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9189. OpenPopupOnItemClick("context");
  9190. }
  9191. else if (flags & ImGuiColorEditFlags_PickerHueBar)
  9192. {
  9193. // SV rectangle logic
  9194. InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
  9195. if (IsItemActive())
  9196. {
  9197. S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1));
  9198. V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
  9199. value_changed = value_changed_sv = true;
  9200. }
  9201. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9202. OpenPopupOnItemClick("context");
  9203. // Hue bar logic
  9204. SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
  9205. InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
  9206. if (IsItemActive())
  9207. {
  9208. H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
  9209. value_changed = value_changed_h = true;
  9210. }
  9211. }
  9212. // Alpha bar logic
  9213. if (alpha_bar)
  9214. {
  9215. SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
  9216. InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
  9217. if (IsItemActive())
  9218. {
  9219. col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
  9220. value_changed = true;
  9221. }
  9222. }
  9223. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  9224. {
  9225. SameLine(0, style.ItemInnerSpacing.x);
  9226. BeginGroup();
  9227. }
  9228. if (!(flags & ImGuiColorEditFlags_NoLabel))
  9229. {
  9230. const char* label_display_end = FindRenderedTextEnd(label);
  9231. if (label != label_display_end)
  9232. {
  9233. if ((flags & ImGuiColorEditFlags_NoSidePreview))
  9234. SameLine(0, style.ItemInnerSpacing.x);
  9235. TextUnformatted(label, label_display_end);
  9236. }
  9237. }
  9238. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  9239. {
  9240. ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
  9241. if ((flags & ImGuiColorEditFlags_NoLabel))
  9242. Text("Current");
  9243. ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2));
  9244. if (ref_col != NULL)
  9245. {
  9246. Text("Original");
  9247. ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
  9248. if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)))
  9249. {
  9250. memcpy(col, ref_col, components * sizeof(float));
  9251. value_changed = true;
  9252. }
  9253. }
  9254. EndGroup();
  9255. }
  9256. // Convert back color to RGB
  9257. if (value_changed_h || value_changed_sv)
  9258. ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]);
  9259. // R,G,B and H,S,V slider color editor
  9260. if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
  9261. {
  9262. PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
  9263. ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
  9264. ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
  9265. if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  9266. value_changed |= ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB);
  9267. if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  9268. value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV);
  9269. if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  9270. value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX);
  9271. PopItemWidth();
  9272. }
  9273. // Try to cancel hue wrap (after ColorEdit), if any
  9274. if (value_changed)
  9275. {
  9276. float new_H, new_S, new_V;
  9277. ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
  9278. if (new_H <= 0 && H > 0)
  9279. {
  9280. if (new_V <= 0 && V != new_V)
  9281. ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
  9282. else if (new_S <= 0)
  9283. ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
  9284. }
  9285. }
  9286. ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
  9287. ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
  9288. ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f));
  9289. const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) };
  9290. ImVec2 sv_cursor_pos;
  9291. if (flags & ImGuiColorEditFlags_PickerHueWheel)
  9292. {
  9293. // Render Hue Wheel
  9294. const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
  9295. const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
  9296. for (int n = 0; n < 6; n++)
  9297. {
  9298. const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
  9299. const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
  9300. const int vert_start_idx = draw_list->VtxBuffer.Size;
  9301. draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
  9302. draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness);
  9303. const int vert_end_idx = draw_list->VtxBuffer.Size;
  9304. // Paint colors over existing vertices
  9305. ImVec2 gradient_p0(wheel_center.x + cosf(a0) * wheel_r_inner, wheel_center.y + sinf(a0) * wheel_r_inner);
  9306. ImVec2 gradient_p1(wheel_center.x + cosf(a1) * wheel_r_inner, wheel_center.y + sinf(a1) * wheel_r_inner);
  9307. ShadeVertsLinearColorGradientKeepAlpha(draw_list->VtxBuffer.Data + vert_start_idx, draw_list->VtxBuffer.Data + vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]);
  9308. }
  9309. // Render Cursor + preview on Hue Wheel
  9310. float cos_hue_angle = cosf(H * 2.0f * IM_PI);
  9311. float sin_hue_angle = sinf(H * 2.0f * IM_PI);
  9312. ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f);
  9313. float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
  9314. int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);
  9315. draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
  9316. draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments);
  9317. draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments);
  9318. // Render SV triangle (rotated according to hue)
  9319. ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
  9320. ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
  9321. ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
  9322. ImVec2 uv_white = GetFontTexUvWhitePixel();
  9323. draw_list->PrimReserve(6, 6);
  9324. draw_list->PrimVtx(tra, uv_white, hue_color32);
  9325. draw_list->PrimVtx(trb, uv_white, hue_color32);
  9326. draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE);
  9327. draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS);
  9328. draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK);
  9329. draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS);
  9330. draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f);
  9331. sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
  9332. }
  9333. else if (flags & ImGuiColorEditFlags_PickerHueBar)
  9334. {
  9335. // Render SV Square
  9336. draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE);
  9337. draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK);
  9338. RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f);
  9339. sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
  9340. sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
  9341. // Render Hue Bar
  9342. for (int i = 0; i < 6; ++i)
  9343. draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]);
  9344. float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f);
  9345. RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
  9346. RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
  9347. }
  9348. // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
  9349. float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;
  9350. draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12);
  9351. draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12);
  9352. draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12);
  9353. // Render alpha bar
  9354. if (alpha_bar)
  9355. {
  9356. float alpha = ImSaturate(col[3]);
  9357. ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
  9358. RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
  9359. draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK);
  9360. float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f);
  9361. RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
  9362. RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
  9363. }
  9364. EndGroup();
  9365. PopID();
  9366. return value_changed && memcmp(backup_initial_col, col, components * sizeof(float));
  9367. }
  9368. // Horizontal separating line.
  9369. void ImGui::Separator()
  9370. {
  9371. ImGuiWindow* window = GetCurrentWindow();
  9372. if (window->SkipItems)
  9373. return;
  9374. ImGuiContext& g = *GImGui;
  9375. ImGuiWindowFlags flags = 0;
  9376. if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0)
  9377. flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
  9378. IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected
  9379. if (flags & ImGuiSeparatorFlags_Vertical)
  9380. {
  9381. VerticalSeparator();
  9382. return;
  9383. }
  9384. // Horizontal Separator
  9385. if (window->DC.ColumnsSet)
  9386. PopClipRect();
  9387. float x1 = window->Pos.x;
  9388. float x2 = window->Pos.x + window->Size.x;
  9389. if (!window->DC.GroupStack.empty())
  9390. x1 += window->DC.IndentX;
  9391. const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f));
  9392. ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
  9393. if (!ItemAdd(bb, 0))
  9394. {
  9395. if (window->DC.ColumnsSet)
  9396. PushColumnClipRect();
  9397. return;
  9398. }
  9399. window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator));
  9400. if (g.LogEnabled)
  9401. LogRenderedText(NULL, IM_NEWLINE "--------------------------------");
  9402. if (window->DC.ColumnsSet)
  9403. {
  9404. PushColumnClipRect();
  9405. window->DC.ColumnsSet->CellMinY = window->DC.CursorPos.y;
  9406. }
  9407. }
  9408. void ImGui::VerticalSeparator()
  9409. {
  9410. ImGuiWindow* window = GetCurrentWindow();
  9411. if (window->SkipItems)
  9412. return;
  9413. ImGuiContext& g = *GImGui;
  9414. float y1 = window->DC.CursorPos.y;
  9415. float y2 = window->DC.CursorPos.y + window->DC.CurrentLineHeight;
  9416. const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2));
  9417. ItemSize(ImVec2(bb.GetWidth(), 0.0f));
  9418. if (!ItemAdd(bb, 0))
  9419. return;
  9420. window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));
  9421. if (g.LogEnabled)
  9422. LogText(" |");
  9423. }
  9424. bool ImGui::SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend)
  9425. {
  9426. ImGuiContext& g = *GImGui;
  9427. ImGuiWindow* window = g.CurrentWindow;
  9428. const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
  9429. #ifdef IMGUI_HAS_NAV
  9430. window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
  9431. #endif
  9432. bool item_add = ItemAdd(bb, id);
  9433. window->DC.ItemFlags = item_flags_backup;
  9434. if (!item_add)
  9435. return false;
  9436. bool hovered, held;
  9437. ImRect bb_interact = bb;
  9438. bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
  9439. ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);
  9440. if (g.ActiveId != id)
  9441. SetItemAllowOverlap();
  9442. if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id))
  9443. SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
  9444. ImRect bb_render = bb;
  9445. if (held)
  9446. {
  9447. ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;
  9448. float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;
  9449. // Minimum pane size
  9450. if (mouse_delta < min_size1 - *size1)
  9451. mouse_delta = min_size1 - *size1;
  9452. if (mouse_delta > *size2 - min_size2)
  9453. mouse_delta = *size2 - min_size2;
  9454. // Apply resize
  9455. *size1 += mouse_delta;
  9456. *size2 -= mouse_delta;
  9457. bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
  9458. }
  9459. // Render
  9460. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  9461. window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding);
  9462. return held;
  9463. }
  9464. void ImGui::Spacing()
  9465. {
  9466. ImGuiWindow* window = GetCurrentWindow();
  9467. if (window->SkipItems)
  9468. return;
  9469. ItemSize(ImVec2(0,0));
  9470. }
  9471. void ImGui::Dummy(const ImVec2& size)
  9472. {
  9473. ImGuiWindow* window = GetCurrentWindow();
  9474. if (window->SkipItems)
  9475. return;
  9476. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  9477. ItemSize(bb);
  9478. ItemAdd(bb, 0);
  9479. }
  9480. bool ImGui::IsRectVisible(const ImVec2& size)
  9481. {
  9482. ImGuiWindow* window = GetCurrentWindowRead();
  9483. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  9484. }
  9485. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  9486. {
  9487. ImGuiWindow* window = GetCurrentWindowRead();
  9488. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  9489. }
  9490. // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
  9491. void ImGui::BeginGroup()
  9492. {
  9493. ImGuiWindow* window = GetCurrentWindow();
  9494. window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
  9495. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  9496. group_data.BackupCursorPos = window->DC.CursorPos;
  9497. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  9498. group_data.BackupIndentX = window->DC.IndentX;
  9499. group_data.BackupGroupOffsetX = window->DC.GroupOffsetX;
  9500. group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
  9501. group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
  9502. group_data.BackupLogLinePosY = window->DC.LogLinePosY;
  9503. group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive;
  9504. group_data.AdvanceCursor = true;
  9505. window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX;
  9506. window->DC.IndentX = window->DC.GroupOffsetX;
  9507. window->DC.CursorMaxPos = window->DC.CursorPos;
  9508. window->DC.CurrentLineHeight = 0.0f;
  9509. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  9510. }
  9511. void ImGui::EndGroup()
  9512. {
  9513. ImGuiContext& g = *GImGui;
  9514. ImGuiWindow* window = GetCurrentWindow();
  9515. IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
  9516. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  9517. ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
  9518. group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
  9519. window->DC.CursorPos = group_data.BackupCursorPos;
  9520. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  9521. window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight;
  9522. window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
  9523. window->DC.IndentX = group_data.BackupIndentX;
  9524. window->DC.GroupOffsetX = group_data.BackupGroupOffsetX;
  9525. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  9526. if (group_data.AdvanceCursor)
  9527. {
  9528. 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.
  9529. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
  9530. ItemAdd(group_bb, 0);
  9531. }
  9532. // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will be functional on the entire group.
  9533. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context.
  9534. const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow);
  9535. if (active_id_within_group)
  9536. window->DC.LastItemId = g.ActiveId;
  9537. window->DC.LastItemRect = group_bb;
  9538. window->DC.GroupStack.pop_back();
  9539. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  9540. }
  9541. // Gets back to previous line and continue with horizontal layout
  9542. // pos_x == 0 : follow right after previous item
  9543. // pos_x != 0 : align to specified x position (relative to window/group left)
  9544. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  9545. // spacing_w >= 0 : enforce spacing amount
  9546. void ImGui::SameLine(float pos_x, float spacing_w)
  9547. {
  9548. ImGuiWindow* window = GetCurrentWindow();
  9549. if (window->SkipItems)
  9550. return;
  9551. ImGuiContext& g = *GImGui;
  9552. if (pos_x != 0.0f)
  9553. {
  9554. if (spacing_w < 0.0f) spacing_w = 0.0f;
  9555. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX;
  9556. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  9557. }
  9558. else
  9559. {
  9560. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  9561. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  9562. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  9563. }
  9564. window->DC.CurrentLineHeight = window->DC.PrevLineHeight;
  9565. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  9566. }
  9567. void ImGui::NewLine()
  9568. {
  9569. ImGuiWindow* window = GetCurrentWindow();
  9570. if (window->SkipItems)
  9571. return;
  9572. ImGuiContext& g = *GImGui;
  9573. const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
  9574. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  9575. if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
  9576. ItemSize(ImVec2(0,0));
  9577. else
  9578. ItemSize(ImVec2(0.0f, g.FontSize));
  9579. window->DC.LayoutType = backup_layout_type;
  9580. }
  9581. void ImGui::NextColumn()
  9582. {
  9583. ImGuiWindow* window = GetCurrentWindow();
  9584. if (window->SkipItems || window->DC.ColumnsSet == NULL)
  9585. return;
  9586. ImGuiContext& g = *GImGui;
  9587. PopItemWidth();
  9588. PopClipRect();
  9589. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  9590. columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y);
  9591. if (++columns->Current < columns->Count)
  9592. {
  9593. // Columns 1+ cancel out IndentX
  9594. window->DC.ColumnsOffsetX = GetColumnOffset(columns->Current) - window->DC.IndentX + g.Style.ItemSpacing.x;
  9595. window->DrawList->ChannelsSetCurrent(columns->Current);
  9596. }
  9597. else
  9598. {
  9599. window->DC.ColumnsOffsetX = 0.0f;
  9600. window->DrawList->ChannelsSetCurrent(0);
  9601. columns->Current = 0;
  9602. columns->CellMinY = columns->CellMaxY;
  9603. }
  9604. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  9605. window->DC.CursorPos.y = columns->CellMinY;
  9606. window->DC.CurrentLineHeight = 0.0f;
  9607. window->DC.CurrentLineTextBaseOffset = 0.0f;
  9608. PushColumnClipRect();
  9609. PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
  9610. }
  9611. int ImGui::GetColumnIndex()
  9612. {
  9613. ImGuiWindow* window = GetCurrentWindowRead();
  9614. return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0;
  9615. }
  9616. int ImGui::GetColumnsCount()
  9617. {
  9618. ImGuiWindow* window = GetCurrentWindowRead();
  9619. return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1;
  9620. }
  9621. static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm)
  9622. {
  9623. return offset_norm * (columns->MaxX - columns->MinX);
  9624. }
  9625. static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset)
  9626. {
  9627. return offset / (columns->MaxX - columns->MinX);
  9628. }
  9629. static inline float GetColumnsRectHalfWidth() { return 4.0f; }
  9630. static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
  9631. {
  9632. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  9633. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  9634. ImGuiContext& g = *GImGui;
  9635. ImGuiWindow* window = g.CurrentWindow;
  9636. 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.
  9637. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
  9638. float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
  9639. x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
  9640. if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
  9641. x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
  9642. return x;
  9643. }
  9644. float ImGui::GetColumnOffset(int column_index)
  9645. {
  9646. ImGuiWindow* window = GetCurrentWindowRead();
  9647. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  9648. IM_ASSERT(columns != NULL);
  9649. if (column_index < 0)
  9650. column_index = columns->Current;
  9651. IM_ASSERT(column_index < columns->Columns.Size);
  9652. /*
  9653. if (g.ActiveId)
  9654. {
  9655. ImGuiContext& g = *GImGui;
  9656. const ImGuiID column_id = columns->ColumnsSetId + ImGuiID(column_index);
  9657. if (g.ActiveId == column_id)
  9658. return GetDraggedColumnOffset(columns, column_index);
  9659. }
  9660. */
  9661. const float t = columns->Columns[column_index].OffsetNorm;
  9662. const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
  9663. return x_offset;
  9664. }
  9665. static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false)
  9666. {
  9667. if (column_index < 0)
  9668. column_index = columns->Current;
  9669. float offset_norm;
  9670. if (before_resize)
  9671. offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
  9672. else
  9673. offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
  9674. return OffsetNormToPixels(columns, offset_norm);
  9675. }
  9676. float ImGui::GetColumnWidth(int column_index)
  9677. {
  9678. ImGuiWindow* window = GetCurrentWindowRead();
  9679. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  9680. IM_ASSERT(columns != NULL);
  9681. if (column_index < 0)
  9682. column_index = columns->Current;
  9683. return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
  9684. }
  9685. void ImGui::SetColumnOffset(int column_index, float offset)
  9686. {
  9687. ImGuiContext& g = *GImGui;
  9688. ImGuiWindow* window = g.CurrentWindow;
  9689. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  9690. IM_ASSERT(columns != NULL);
  9691. if (column_index < 0)
  9692. column_index = columns->Current;
  9693. IM_ASSERT(column_index < columns->Columns.Size);
  9694. const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
  9695. const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
  9696. if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
  9697. offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
  9698. columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX);
  9699. if (preserve_width)
  9700. SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
  9701. }
  9702. void ImGui::SetColumnWidth(int column_index, float width)
  9703. {
  9704. ImGuiWindow* window = GetCurrentWindowRead();
  9705. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  9706. IM_ASSERT(columns != NULL);
  9707. if (column_index < 0)
  9708. column_index = columns->Current;
  9709. SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
  9710. }
  9711. void ImGui::PushColumnClipRect(int column_index)
  9712. {
  9713. ImGuiWindow* window = GetCurrentWindowRead();
  9714. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  9715. if (column_index < 0)
  9716. column_index = columns->Current;
  9717. PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false);
  9718. }
  9719. static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id)
  9720. {
  9721. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  9722. if (window->ColumnsStorage[n].ID == id)
  9723. return &window->ColumnsStorage[n];
  9724. window->ColumnsStorage.push_back(ImGuiColumnsSet());
  9725. ImGuiColumnsSet* columns = &window->ColumnsStorage.back();
  9726. columns->ID = id;
  9727. return columns;
  9728. }
  9729. void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
  9730. {
  9731. ImGuiContext& g = *GImGui;
  9732. ImGuiWindow* window = GetCurrentWindow();
  9733. IM_ASSERT(columns_count > 1);
  9734. IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported
  9735. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  9736. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  9737. PushID(0x11223347 + (str_id ? 0 : columns_count));
  9738. ImGuiID id = window->GetID(str_id ? str_id : "columns");
  9739. PopID();
  9740. // Acquire storage for the columns set
  9741. ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id);
  9742. IM_ASSERT(columns->ID == id);
  9743. columns->Current = 0;
  9744. columns->Count = columns_count;
  9745. columns->Flags = flags;
  9746. window->DC.ColumnsSet = columns;
  9747. // Set state for first column
  9748. const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->Size.x -window->ScrollbarSizes.x);
  9749. columns->MinX = window->DC.IndentX - g.Style.ItemSpacing.x; // Lock our horizontal range
  9750. //column->MaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
  9751. columns->MaxX = content_region_width - window->Scroll.x;
  9752. columns->StartPosY = window->DC.CursorPos.y;
  9753. columns->StartMaxPosX = window->DC.CursorMaxPos.x;
  9754. columns->CellMinY = columns->CellMaxY = window->DC.CursorPos.y;
  9755. window->DC.ColumnsOffsetX = 0.0f;
  9756. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  9757. // Clear data if columns count changed
  9758. if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
  9759. columns->Columns.resize(0);
  9760. // Initialize defaults
  9761. columns->IsFirstFrame = (columns->Columns.Size == 0);
  9762. if (columns->Columns.Size == 0)
  9763. {
  9764. columns->Columns.reserve(columns_count + 1);
  9765. for (int n = 0; n < columns_count + 1; n++)
  9766. {
  9767. ImGuiColumnData column;
  9768. column.OffsetNorm = n / (float)columns_count;
  9769. columns->Columns.push_back(column);
  9770. }
  9771. }
  9772. for (int n = 0; n < columns_count + 1; n++)
  9773. {
  9774. // Clamp position
  9775. ImGuiColumnData* column = &columns->Columns[n];
  9776. float t = column->OffsetNorm;
  9777. if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
  9778. t = ImMin(t, PixelsToOffsetNorm(columns, (columns->MaxX - columns->MinX) - g.Style.ColumnsMinSpacing * (columns->Count - n)));
  9779. column->OffsetNorm = t;
  9780. if (n == columns_count)
  9781. continue;
  9782. // Compute clipping rectangle
  9783. float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
  9784. float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
  9785. column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
  9786. column->ClipRect.ClipWith(window->ClipRect);
  9787. }
  9788. window->DrawList->ChannelsSplit(columns->Count);
  9789. PushColumnClipRect();
  9790. PushItemWidth(GetColumnWidth() * 0.65f);
  9791. }
  9792. void ImGui::EndColumns()
  9793. {
  9794. ImGuiContext& g = *GImGui;
  9795. ImGuiWindow* window = GetCurrentWindow();
  9796. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  9797. IM_ASSERT(columns != NULL);
  9798. PopItemWidth();
  9799. PopClipRect();
  9800. window->DrawList->ChannelsMerge();
  9801. columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y);
  9802. window->DC.CursorPos.y = columns->CellMaxY;
  9803. if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
  9804. window->DC.CursorMaxPos.x = ImMax(columns->StartMaxPosX, columns->MaxX); // Restore cursor max pos, as columns don't grow parent
  9805. // Draw columns borders and handle resize
  9806. bool is_being_resized = false;
  9807. if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
  9808. {
  9809. const float y1 = columns->StartPosY;
  9810. const float y2 = window->DC.CursorPos.y;
  9811. int dragging_column = -1;
  9812. for (int n = 1; n < columns->Count; n++)
  9813. {
  9814. float x = window->Pos.x + GetColumnOffset(n);
  9815. const ImGuiID column_id = columns->ID + ImGuiID(n);
  9816. const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction
  9817. const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2));
  9818. KeepAliveID(column_id);
  9819. if (IsClippedEx(column_rect, column_id, false))
  9820. continue;
  9821. bool hovered = false, held = false;
  9822. if (!(columns->Flags & ImGuiColumnsFlags_NoResize))
  9823. {
  9824. ButtonBehavior(column_rect, column_id, &hovered, &held);
  9825. if (hovered || held)
  9826. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  9827. if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize))
  9828. dragging_column = n;
  9829. }
  9830. // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.)
  9831. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  9832. const float xi = (float)(int)x;
  9833. window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col);
  9834. }
  9835. // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
  9836. if (dragging_column != -1)
  9837. {
  9838. if (!columns->IsBeingResized)
  9839. for (int n = 0; n < columns->Count + 1; n++)
  9840. columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
  9841. columns->IsBeingResized = is_being_resized = true;
  9842. float x = GetDraggedColumnOffset(columns, dragging_column);
  9843. SetColumnOffset(dragging_column, x);
  9844. }
  9845. }
  9846. columns->IsBeingResized = is_being_resized;
  9847. window->DC.ColumnsSet = NULL;
  9848. window->DC.ColumnsOffsetX = 0.0f;
  9849. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  9850. }
  9851. // [2017/12: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
  9852. void ImGui::Columns(int columns_count, const char* id, bool border)
  9853. {
  9854. ImGuiWindow* window = GetCurrentWindow();
  9855. IM_ASSERT(columns_count >= 1);
  9856. if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count != columns_count)
  9857. EndColumns();
  9858. ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
  9859. //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
  9860. if (columns_count != 1)
  9861. BeginColumns(id, columns_count, flags);
  9862. }
  9863. void ImGui::Indent(float indent_w)
  9864. {
  9865. ImGuiContext& g = *GImGui;
  9866. ImGuiWindow* window = GetCurrentWindow();
  9867. window->DC.IndentX += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  9868. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  9869. }
  9870. void ImGui::Unindent(float indent_w)
  9871. {
  9872. ImGuiContext& g = *GImGui;
  9873. ImGuiWindow* window = GetCurrentWindow();
  9874. window->DC.IndentX -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  9875. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  9876. }
  9877. void ImGui::TreePush(const char* str_id)
  9878. {
  9879. ImGuiWindow* window = GetCurrentWindow();
  9880. Indent();
  9881. window->DC.TreeDepth++;
  9882. PushID(str_id ? str_id : "#TreePush");
  9883. }
  9884. void ImGui::TreePush(const void* ptr_id)
  9885. {
  9886. ImGuiWindow* window = GetCurrentWindow();
  9887. Indent();
  9888. window->DC.TreeDepth++;
  9889. PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
  9890. }
  9891. void ImGui::TreePushRawID(ImGuiID id)
  9892. {
  9893. ImGuiWindow* window = GetCurrentWindow();
  9894. Indent();
  9895. window->DC.TreeDepth++;
  9896. window->IDStack.push_back(id);
  9897. }
  9898. void ImGui::TreePop()
  9899. {
  9900. ImGuiWindow* window = GetCurrentWindow();
  9901. Unindent();
  9902. window->DC.TreeDepth--;
  9903. PopID();
  9904. }
  9905. void ImGui::Value(const char* prefix, bool b)
  9906. {
  9907. Text("%s: %s", prefix, (b ? "true" : "false"));
  9908. }
  9909. void ImGui::Value(const char* prefix, int v)
  9910. {
  9911. Text("%s: %d", prefix, v);
  9912. }
  9913. void ImGui::Value(const char* prefix, unsigned int v)
  9914. {
  9915. Text("%s: %d", prefix, v);
  9916. }
  9917. void ImGui::Value(const char* prefix, float v, const char* float_format)
  9918. {
  9919. if (float_format)
  9920. {
  9921. char fmt[64];
  9922. ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
  9923. Text(fmt, prefix, v);
  9924. }
  9925. else
  9926. {
  9927. Text("%s: %.3f", prefix, v);
  9928. }
  9929. }
  9930. //-----------------------------------------------------------------------------
  9931. // DRAG AND DROP
  9932. //-----------------------------------------------------------------------------
  9933. void ImGui::ClearDragDrop()
  9934. {
  9935. ImGuiContext& g = *GImGui;
  9936. g.DragDropActive = false;
  9937. g.DragDropPayload.Clear();
  9938. g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
  9939. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  9940. g.DragDropAcceptFrameCount = -1;
  9941. }
  9942. // Call when current ID is active.
  9943. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
  9944. bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags, int mouse_button)
  9945. {
  9946. ImGuiContext& g = *GImGui;
  9947. ImGuiWindow* window = g.CurrentWindow;
  9948. bool source_drag_active = false;
  9949. ImGuiID source_id = 0;
  9950. ImGuiID source_parent_id = 0;
  9951. if (!(flags & ImGuiDragDropFlags_SourceExtern))
  9952. {
  9953. source_id = window->DC.LastItemId;
  9954. if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
  9955. return false;
  9956. if (g.IO.MouseDown[mouse_button] == false)
  9957. return false;
  9958. if (source_id == 0)
  9959. {
  9960. // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
  9961. // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
  9962. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
  9963. {
  9964. IM_ASSERT(0);
  9965. return false;
  9966. }
  9967. // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
  9968. // We build a throwaway ID based on current ID stack + relative AABB of items in window.
  9969. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
  9970. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
  9971. bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0;
  9972. if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
  9973. return false;
  9974. source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
  9975. if (is_hovered)
  9976. SetHoveredID(source_id);
  9977. if (is_hovered && g.IO.MouseClicked[mouse_button])
  9978. {
  9979. SetActiveID(source_id, window);
  9980. FocusWindow(window);
  9981. }
  9982. if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
  9983. g.ActiveIdAllowOverlap = is_hovered;
  9984. }
  9985. if (g.ActiveId != source_id)
  9986. return false;
  9987. source_parent_id = window->IDStack.back();
  9988. source_drag_active = IsMouseDragging(mouse_button);
  9989. }
  9990. else
  9991. {
  9992. window = NULL;
  9993. source_id = ImHash("#SourceExtern", 0);
  9994. source_drag_active = true;
  9995. }
  9996. if (source_drag_active)
  9997. {
  9998. if (!g.DragDropActive)
  9999. {
  10000. IM_ASSERT(source_id != 0);
  10001. ClearDragDrop();
  10002. ImGuiPayload& payload = g.DragDropPayload;
  10003. payload.SourceId = source_id;
  10004. payload.SourceParentId = source_parent_id;
  10005. g.DragDropActive = true;
  10006. g.DragDropSourceFlags = flags;
  10007. g.DragDropMouseButton = mouse_button;
  10008. }
  10009. if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  10010. {
  10011. // FIXME-DRAG
  10012. //SetNextWindowPos(g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding);
  10013. //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This is better but e.g ColorButton with checkboard has issue with transparent colors :(
  10014. SetNextWindowPos(g.IO.MousePos);
  10015. PushStyleColor(ImGuiCol_PopupBg, GetStyleColorVec4(ImGuiCol_PopupBg) * ImVec4(1.0f, 1.0f, 1.0f, 0.6f));
  10016. BeginTooltip();
  10017. }
  10018. if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
  10019. window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
  10020. return true;
  10021. }
  10022. return false;
  10023. }
  10024. void ImGui::EndDragDropSource()
  10025. {
  10026. ImGuiContext& g = *GImGui;
  10027. IM_ASSERT(g.DragDropActive);
  10028. if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  10029. {
  10030. EndTooltip();
  10031. PopStyleColor();
  10032. //PopStyleVar();
  10033. }
  10034. // Discard the drag if have not called SetDragDropPayload()
  10035. if (g.DragDropPayload.DataFrameCount == -1)
  10036. ClearDragDrop();
  10037. }
  10038. // Use 'cond' to choose to submit payload on drag start or every frame
  10039. bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
  10040. {
  10041. ImGuiContext& g = *GImGui;
  10042. ImGuiPayload& payload = g.DragDropPayload;
  10043. if (cond == 0)
  10044. cond = ImGuiCond_Always;
  10045. IM_ASSERT(type != NULL);
  10046. IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 12 characters long");
  10047. IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
  10048. IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
  10049. IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
  10050. if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
  10051. {
  10052. // Copy payload
  10053. ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
  10054. g.DragDropPayloadBufHeap.resize(0);
  10055. if (data_size > sizeof(g.DragDropPayloadBufLocal))
  10056. {
  10057. // Store in heap
  10058. g.DragDropPayloadBufHeap.resize((int)data_size);
  10059. payload.Data = g.DragDropPayloadBufHeap.Data;
  10060. memcpy((void*)payload.Data, data, data_size);
  10061. }
  10062. else if (data_size > 0)
  10063. {
  10064. // Store locally
  10065. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  10066. payload.Data = g.DragDropPayloadBufLocal;
  10067. memcpy((void*)payload.Data, data, data_size);
  10068. }
  10069. else
  10070. {
  10071. payload.Data = NULL;
  10072. }
  10073. payload.DataSize = (int)data_size;
  10074. }
  10075. payload.DataFrameCount = g.FrameCount;
  10076. return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
  10077. }
  10078. bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
  10079. {
  10080. ImGuiContext& g = *GImGui;
  10081. if (!g.DragDropActive)
  10082. return false;
  10083. ImGuiWindow* window = g.CurrentWindow;
  10084. if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
  10085. return false;
  10086. IM_ASSERT(id != 0);
  10087. if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
  10088. return false;
  10089. g.DragDropTargetRect = bb;
  10090. g.DragDropTargetId = id;
  10091. return true;
  10092. }
  10093. // We don't use BeginDragDropTargetCustom() and duplicate its code because:
  10094. // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
  10095. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
  10096. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
  10097. bool ImGui::BeginDragDropTarget()
  10098. {
  10099. ImGuiContext& g = *GImGui;
  10100. if (!g.DragDropActive)
  10101. return false;
  10102. ImGuiWindow* window = g.CurrentWindow;
  10103. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  10104. return false;
  10105. if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
  10106. return false;
  10107. const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
  10108. ImGuiID id = window->DC.LastItemId;
  10109. if (id == 0)
  10110. id = window->GetIDFromRectangle(display_rect);
  10111. if (g.DragDropPayload.SourceId == id)
  10112. return false;
  10113. g.DragDropTargetRect = display_rect;
  10114. g.DragDropTargetId = id;
  10115. return true;
  10116. }
  10117. bool ImGui::IsDragDropPayloadBeingAccepted()
  10118. {
  10119. ImGuiContext& g = *GImGui;
  10120. return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
  10121. }
  10122. const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
  10123. {
  10124. ImGuiContext& g = *GImGui;
  10125. ImGuiWindow* window = g.CurrentWindow;
  10126. ImGuiPayload& payload = g.DragDropPayload;
  10127. IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
  10128. IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
  10129. if (type != NULL && !payload.IsDataType(type))
  10130. return NULL;
  10131. // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
  10132. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
  10133. const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
  10134. ImRect r = g.DragDropTargetRect;
  10135. float r_surface = r.GetWidth() * r.GetHeight();
  10136. if (r_surface < g.DragDropAcceptIdCurrRectSurface)
  10137. {
  10138. g.DragDropAcceptIdCurr = g.DragDropTargetId;
  10139. g.DragDropAcceptIdCurrRectSurface = r_surface;
  10140. }
  10141. // Render default drop visuals
  10142. payload.Preview = was_accepted_previously;
  10143. flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
  10144. if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
  10145. {
  10146. // FIXME-DRAG: Settle on a proper default visuals for drop target.
  10147. r.Expand(3.5f);
  10148. bool push_clip_rect = !window->ClipRect.Contains(r);
  10149. if (push_clip_rect) window->DrawList->PushClipRectFullScreen();
  10150. window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
  10151. if (push_clip_rect) window->DrawList->PopClipRect();
  10152. }
  10153. g.DragDropAcceptFrameCount = g.FrameCount;
  10154. payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
  10155. if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
  10156. return NULL;
  10157. return &payload;
  10158. }
  10159. // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
  10160. void ImGui::EndDragDropTarget()
  10161. {
  10162. ImGuiContext& g = *GImGui; (void)g;
  10163. IM_ASSERT(g.DragDropActive);
  10164. }
  10165. //-----------------------------------------------------------------------------
  10166. // PLATFORM DEPENDENT HELPERS
  10167. //-----------------------------------------------------------------------------
  10168. #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
  10169. #undef WIN32_LEAN_AND_MEAN
  10170. #define WIN32_LEAN_AND_MEAN
  10171. #ifndef __MINGW32__
  10172. #include <Windows.h>
  10173. #else
  10174. #include <windows.h>
  10175. #endif
  10176. #endif
  10177. // Win32 API clipboard implementation
  10178. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
  10179. #ifdef _MSC_VER
  10180. #pragma comment(lib, "user32")
  10181. #endif
  10182. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10183. {
  10184. static ImVector<char> buf_local;
  10185. buf_local.clear();
  10186. if (!OpenClipboard(NULL))
  10187. return NULL;
  10188. HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
  10189. if (wbuf_handle == NULL)
  10190. {
  10191. CloseClipboard();
  10192. return NULL;
  10193. }
  10194. if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
  10195. {
  10196. int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
  10197. buf_local.resize(buf_len);
  10198. ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
  10199. }
  10200. GlobalUnlock(wbuf_handle);
  10201. CloseClipboard();
  10202. return buf_local.Data;
  10203. }
  10204. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10205. {
  10206. if (!OpenClipboard(NULL))
  10207. return;
  10208. const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
  10209. HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
  10210. if (wbuf_handle == NULL)
  10211. {
  10212. CloseClipboard();
  10213. return;
  10214. }
  10215. ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
  10216. ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
  10217. GlobalUnlock(wbuf_handle);
  10218. EmptyClipboard();
  10219. SetClipboardData(CF_UNICODETEXT, wbuf_handle);
  10220. CloseClipboard();
  10221. }
  10222. #else
  10223. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  10224. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10225. {
  10226. ImGuiContext& g = *GImGui;
  10227. return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
  10228. }
  10229. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  10230. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10231. {
  10232. ImGuiContext& g = *GImGui;
  10233. g.PrivateClipboard.clear();
  10234. const char* text_end = text + strlen(text);
  10235. g.PrivateClipboard.resize((int)(text_end - text) + 1);
  10236. memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
  10237. g.PrivateClipboard[(int)(text_end - text)] = 0;
  10238. }
  10239. #endif
  10240. // Win32 API IME support (for Asian languages, etc.)
  10241. #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  10242. #include <imm.h>
  10243. #ifdef _MSC_VER
  10244. #pragma comment(lib, "imm32")
  10245. #endif
  10246. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
  10247. {
  10248. // Notify OS Input Method Editor of text input position
  10249. if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
  10250. if (HIMC himc = ImmGetContext(hwnd))
  10251. {
  10252. COMPOSITIONFORM cf;
  10253. cf.ptCurrentPos.x = x;
  10254. cf.ptCurrentPos.y = y;
  10255. cf.dwStyle = CFS_FORCE_POSITION;
  10256. ImmSetCompositionWindow(himc, &cf);
  10257. }
  10258. }
  10259. #else
  10260. static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
  10261. #endif
  10262. //-----------------------------------------------------------------------------
  10263. // HELP
  10264. //-----------------------------------------------------------------------------
  10265. void ImGui::ShowMetricsWindow(bool* p_open)
  10266. {
  10267. if (ImGui::Begin("ImGui Metrics", p_open))
  10268. {
  10269. ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
  10270. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  10271. ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
  10272. ImGui::Text("%d allocations", GImAllocatorActiveAllocationsCount);
  10273. static bool show_clip_rects = true;
  10274. ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_clip_rects);
  10275. ImGui::Separator();
  10276. struct Funcs
  10277. {
  10278. static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
  10279. {
  10280. bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
  10281. if (draw_list == ImGui::GetWindowDrawList())
  10282. {
  10283. ImGui::SameLine();
  10284. ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  10285. if (node_open) ImGui::TreePop();
  10286. return;
  10287. }
  10288. ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
  10289. if (window && ImGui::IsItemHovered())
  10290. overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  10291. if (!node_open)
  10292. return;
  10293. int elem_offset = 0;
  10294. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
  10295. {
  10296. if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
  10297. continue;
  10298. if (pcmd->UserCallback)
  10299. {
  10300. ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  10301. continue;
  10302. }
  10303. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  10304. bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  10305. if (show_clip_rects && ImGui::IsItemHovered())
  10306. {
  10307. ImRect clip_rect = pcmd->ClipRect;
  10308. ImRect vtxs_rect;
  10309. for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
  10310. vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
  10311. clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
  10312. vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
  10313. }
  10314. if (!pcmd_node_open)
  10315. continue;
  10316. // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
  10317. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  10318. while (clipper.Step())
  10319. for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
  10320. {
  10321. char buf[300];
  10322. char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
  10323. ImVec2 triangles_pos[3];
  10324. for (int n = 0; n < 3; n++, vtx_i++)
  10325. {
  10326. ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
  10327. triangles_pos[n] = v.pos;
  10328. buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  10329. }
  10330. ImGui::Selectable(buf, false);
  10331. if (ImGui::IsItemHovered())
  10332. {
  10333. ImDrawListFlags backup_flags = overlay_draw_list->Flags;
  10334. overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
  10335. overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
  10336. overlay_draw_list->Flags = backup_flags;
  10337. }
  10338. }
  10339. ImGui::TreePop();
  10340. }
  10341. ImGui::TreePop();
  10342. }
  10343. static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
  10344. {
  10345. if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
  10346. return;
  10347. for (int i = 0; i < windows.Size; i++)
  10348. Funcs::NodeWindow(windows[i], "Window");
  10349. ImGui::TreePop();
  10350. }
  10351. static void NodeWindow(ImGuiWindow* window, const char* label)
  10352. {
  10353. if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
  10354. return;
  10355. ImGuiWindowFlags flags = window->Flags;
  10356. NodeDrawList(window, window->DrawList, "DrawList");
  10357. ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
  10358. ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s..)", flags,
  10359. (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
  10360. (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "");
  10361. ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetScrollMaxX(window), window->Scroll.y, GetScrollMaxY(window));
  10362. ImGui::BulletText("Active: %d, WriteAccessed: %d", window->Active, window->WriteAccessed);
  10363. if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
  10364. if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
  10365. ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
  10366. ImGui::TreePop();
  10367. }
  10368. };
  10369. // Access private state, we are going to display the draw lists from last frame
  10370. ImGuiContext& g = *GImGui;
  10371. Funcs::NodeWindows(g.Windows, "Windows");
  10372. if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
  10373. {
  10374. for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
  10375. Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
  10376. ImGui::TreePop();
  10377. }
  10378. if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size))
  10379. {
  10380. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  10381. {
  10382. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  10383. ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
  10384. }
  10385. ImGui::TreePop();
  10386. }
  10387. if (ImGui::TreeNode("Internal state"))
  10388. {
  10389. ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  10390. ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
  10391. ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec)", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
  10392. ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec)", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer);
  10393. ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  10394. ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  10395. ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
  10396. ImGui::TreePop();
  10397. }
  10398. }
  10399. ImGui::End();
  10400. }
  10401. //-----------------------------------------------------------------------------
  10402. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  10403. // 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.
  10404. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  10405. #include "imgui_user.inl"
  10406. #endif
  10407. //-----------------------------------------------------------------------------