imgui.cpp 668 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724
  1. // dear imgui, v1.89 WIP
  2. // (main code and documentation)
  3. // Help:
  4. // - Read FAQ at http://dearimgui.org/faq
  5. // - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
  6. // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
  7. // Read imgui.cpp for details, links and comments.
  8. // Resources:
  9. // - FAQ http://dearimgui.org/faq
  10. // - Homepage & latest https://github.com/ocornut/imgui
  11. // - Releases & changelog https://github.com/ocornut/imgui/releases
  12. // - Gallery https://github.com/ocornut/imgui/issues/5243 (please post your screenshots/video there!)
  13. // - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there)
  14. // - Glossary https://github.com/ocornut/imgui/wiki/Glossary
  15. // - Issues & support https://github.com/ocornut/imgui/issues
  16. // Getting Started?
  17. // - For first-time users having issues compiling/linking/running or issues loading fonts:
  18. // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
  19. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  20. // See LICENSE.txt for copyright and licensing details (standard MIT License).
  21. // This library is free but needs your support to sustain development and maintenance.
  22. // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
  23. // Individuals: you can support continued development via donations. See docs/README or web page.
  24. // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
  25. // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
  26. // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
  27. // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
  28. // to a better solution or official support for them.
  29. /*
  30. Index of this file:
  31. DOCUMENTATION
  32. - MISSION STATEMENT
  33. - END-USER GUIDE
  34. - PROGRAMMER GUIDE
  35. - READ FIRST
  36. - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  37. - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  38. - HOW A SIMPLE APPLICATION MAY LOOK LIKE
  39. - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  40. - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  41. - API BREAKING CHANGES (read me when you update!)
  42. - FREQUENTLY ASKED QUESTIONS (FAQ)
  43. - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
  44. CODE
  45. (search for "[SECTION]" in the code to find them)
  46. // [SECTION] INCLUDES
  47. // [SECTION] FORWARD DECLARATIONS
  48. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  49. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  50. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  51. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  52. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  53. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  54. // [SECTION] MISC HELPERS/UTILITIES (Color functions)
  55. // [SECTION] ImGuiStorage
  56. // [SECTION] ImGuiTextFilter
  57. // [SECTION] ImGuiTextBuffer
  58. // [SECTION] ImGuiListClipper
  59. // [SECTION] STYLING
  60. // [SECTION] RENDER HELPERS
  61. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  62. // [SECTION] INPUTS
  63. // [SECTION] ERROR CHECKING
  64. // [SECTION] LAYOUT
  65. // [SECTION] SCROLLING
  66. // [SECTION] TOOLTIPS
  67. // [SECTION] POPUPS
  68. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  69. // [SECTION] DRAG AND DROP
  70. // [SECTION] LOGGING/CAPTURING
  71. // [SECTION] SETTINGS
  72. // [SECTION] VIEWPORTS
  73. // [SECTION] PLATFORM DEPENDENT HELPERS
  74. // [SECTION] METRICS/DEBUGGER WINDOW
  75. // [SECTION] DEBUG LOG WINDOW
  76. // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
  77. */
  78. //-----------------------------------------------------------------------------
  79. // DOCUMENTATION
  80. //-----------------------------------------------------------------------------
  81. /*
  82. MISSION STATEMENT
  83. =================
  84. - Easy to use to create code-driven and data-driven tools.
  85. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
  86. - Easy to hack and improve.
  87. - Minimize setup and maintenance.
  88. - Minimize state storage on user side.
  89. - Minimize state synchronization.
  90. - Portable, minimize dependencies, run on target (consoles, phones, etc.).
  91. - Efficient runtime and memory consumption.
  92. Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
  93. - Doesn't look fancy, doesn't animate.
  94. - Limited layout features, intricate layouts are typically crafted in code.
  95. END-USER GUIDE
  96. ==============
  97. - Double-click on title bar to collapse window.
  98. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
  99. - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
  100. - Click and drag on any empty space to move window.
  101. - TAB/SHIFT+TAB to cycle through keyboard editable fields.
  102. - CTRL+Click on a slider or drag box to input value as text.
  103. - Use mouse wheel to scroll.
  104. - Text editor:
  105. - Hold SHIFT or use mouse to select text.
  106. - CTRL+Left/Right to word jump.
  107. - CTRL+Shift+Left/Right to select words.
  108. - CTRL+A or Double-Click to select all.
  109. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
  110. - CTRL+Z,CTRL+Y to undo/redo.
  111. - ESCAPE to revert text to its original value.
  112. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  113. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
  114. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. Download controller mapping PNG/PSD at http://dearimgui.org/controls_sheets
  115. PROGRAMMER GUIDE
  116. ================
  117. READ FIRST
  118. ----------
  119. - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
  120. - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
  121. destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
  122. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
  123. - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
  124. - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
  125. You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
  126. - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
  127. For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
  128. where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
  129. - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
  130. - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
  131. - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
  132. If you get an assert, read the messages and comments around the assert.
  133. - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
  134. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
  135. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
  136. However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
  137. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
  138. HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  139. ----------------------------------------------
  140. - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
  141. - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
  142. - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
  143. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  144. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
  145. from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
  146. likely be a comment about it. Please report any issue to the GitHub page!
  147. - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
  148. - Try to keep your copy of Dear ImGui reasonably up to date.
  149. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  150. ---------------------------------------------------------------
  151. - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
  152. - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
  153. - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
  154. It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
  155. - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
  156. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
  157. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
  158. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
  159. phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
  160. - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
  161. - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
  162. HOW A SIMPLE APPLICATION MAY LOOK LIKE
  163. --------------------------------------
  164. EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
  165. The sub-folders in examples/ contain examples applications following this structure.
  166. // Application init: create a dear imgui context, setup some options, load fonts
  167. ImGui::CreateContext();
  168. ImGuiIO& io = ImGui::GetIO();
  169. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  170. // TODO: Fill optional fields of the io structure later.
  171. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  172. // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
  173. ImGui_ImplWin32_Init(hwnd);
  174. ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
  175. // Application main loop
  176. while (true)
  177. {
  178. // Feed inputs to dear imgui, start new frame
  179. ImGui_ImplDX11_NewFrame();
  180. ImGui_ImplWin32_NewFrame();
  181. ImGui::NewFrame();
  182. // Any application code here
  183. ImGui::Text("Hello, world!");
  184. // Render dear imgui into screen
  185. ImGui::Render();
  186. ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
  187. g_pSwapChain->Present(1, 0);
  188. }
  189. // Shutdown
  190. ImGui_ImplDX11_Shutdown();
  191. ImGui_ImplWin32_Shutdown();
  192. ImGui::DestroyContext();
  193. EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
  194. // Application init: create a dear imgui context, setup some options, load fonts
  195. ImGui::CreateContext();
  196. ImGuiIO& io = ImGui::GetIO();
  197. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  198. // TODO: Fill optional fields of the io structure later.
  199. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  200. // Build and load the texture atlas into a texture
  201. // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
  202. int width, height;
  203. unsigned char* pixels = NULL;
  204. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  205. // At this point you've got the texture data and you need to upload that to your graphic system:
  206. // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
  207. // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
  208. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
  209. io.Fonts->SetTexID((void*)texture);
  210. // Application main loop
  211. while (true)
  212. {
  213. // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
  214. // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
  215. io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
  216. io.DisplaySize.x = 1920.0f; // set the current display width
  217. io.DisplaySize.y = 1280.0f; // set the current display height here
  218. io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
  219. io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
  220. io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
  221. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  222. // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
  223. ImGui::NewFrame();
  224. // Most of your application code here
  225. ImGui::Text("Hello, world!");
  226. MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  227. MyGameRender(); // may use any Dear ImGui functions as well!
  228. // Render dear imgui, swap buffers
  229. // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
  230. ImGui::EndFrame();
  231. ImGui::Render();
  232. ImDrawData* draw_data = ImGui::GetDrawData();
  233. MyImGuiRenderFunction(draw_data);
  234. SwapBuffers();
  235. }
  236. // Shutdown
  237. ImGui::DestroyContext();
  238. To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
  239. you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
  240. Please read the FAQ and example applications for details about this!
  241. HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  242. ---------------------------------------------
  243. The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
  244. void MyImGuiRenderFunction(ImDrawData* draw_data)
  245. {
  246. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  247. // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
  248. // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  249. // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  250. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  251. ImVec2 clip_off = draw_data->DisplayPos;
  252. for (int n = 0; n < draw_data->CmdListsCount; n++)
  253. {
  254. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  255. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
  256. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
  257. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  258. {
  259. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  260. if (pcmd->UserCallback)
  261. {
  262. pcmd->UserCallback(cmd_list, pcmd);
  263. }
  264. else
  265. {
  266. // Project scissor/clipping rectangles into framebuffer space
  267. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  268. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  269. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  270. continue;
  271. // We are using scissoring to clip some objects. All low-level graphics API should support it.
  272. // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
  273. // (some elements visible outside their bounds) but you can fix that once everything else works!
  274. // - Clipping coordinates are provided in imgui coordinates space:
  275. // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
  276. // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
  277. // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
  278. // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
  279. // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
  280. MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
  281. // The texture for the draw call is specified by pcmd->GetTexID().
  282. // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
  283. MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
  284. // Render 'pcmd->ElemCount/3' indexed triangles.
  285. // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
  286. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
  287. }
  288. }
  289. }
  290. }
  291. USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  292. ------------------------------------------
  293. - The gamepad/keyboard navigation is fairly functional and keeps being improved.
  294. - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
  295. - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
  296. - Keyboard:
  297. - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
  298. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard),
  299. the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from:
  300. - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
  301. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
  302. - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
  303. Please reach out if you think the game vs navigation input sharing could be improved.
  304. - Gamepad:
  305. - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
  306. - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
  307. For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
  308. Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
  309. - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
  310. - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
  311. - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
  312. with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
  313. - Mouse:
  314. - PS4/PS5 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
  315. - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
  316. - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
  317. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
  318. When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
  319. When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
  320. (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)
  321. (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
  322. to set a boolean to ignore your other external mouse positions until the external source is moved again.)
  323. API BREAKING CHANGES
  324. ====================
  325. Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
  326. Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
  327. When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  328. You can read releases logs https://github.com/ocornut/imgui/releases for more details.
  329. - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
  330. - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
  331. - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
  332. - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
  333. - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
  334. - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
  335. the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
  336. the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
  337. exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
  338. - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
  339. - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
  340. - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
  341. - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
  342. - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
  343. - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
  344. this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
  345. - previously this would make the window content size ~200x200:
  346. Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
  347. - instead, please submit an item:
  348. Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
  349. - alternative:
  350. Begin(...) + Dummy(ImVec2(200,200)) + End();
  351. - content size is now only extended when submitting an item!
  352. - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
  353. - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
  354. - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
  355. - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
  356. - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
  357. - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
  358. - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
  359. - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
  360. - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
  361. - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
  362. - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
  363. - Official backends from 1.87+ -> no issue.
  364. - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
  365. - Custom backends not writing to io.NavInputs[] -> no issue.
  366. - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
  367. - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
  368. - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
  369. - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
  370. - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
  371. - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
  372. - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
  373. - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
  374. - 2022/01/17 (1.87) - inputs: reworked mouse IO.
  375. - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
  376. - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
  377. - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
  378. - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
  379. note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
  380. read https://github.com/ocornut/imgui/issues/4921 for details.
  381. - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
  382. - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
  383. - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
  384. - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
  385. - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
  386. - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
  387. - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
  388. - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
  389. - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
  390. - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
  391. - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
  392. - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
  393. - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
  394. - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
  395. - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
  396. - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
  397. - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
  398. - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
  399. - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
  400. - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
  401. - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
  402. - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
  403. - if you are using official backends from the source tree: you have nothing to do.
  404. - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
  405. - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
  406. - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
  407. - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
  408. - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
  409. flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
  410. breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
  411. - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
  412. - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
  413. - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
  414. - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
  415. this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
  416. the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
  417. legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
  418. - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
  419. - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
  420. - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
  421. - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
  422. - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
  423. - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
  424. - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
  425. - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
  426. - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
  427. - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
  428. - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
  429. - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
  430. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
  431. - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
  432. - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
  433. - ImGuiInputTextCallback -> use ImGuiTextEditCallback
  434. - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
  435. - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
  436. - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
  437. - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
  438. - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
  439. - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
  440. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
  441. - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
  442. - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
  443. - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
  444. - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
  445. - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
  446. - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
  447. - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
  448. - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
  449. - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
  450. - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
  451. - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
  452. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
  453. - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
  454. - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
  455. - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
  456. replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
  457. worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
  458. - if you omitted the 'power' parameter (likely!), you are not affected.
  459. - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
  460. - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
  461. see https://github.com/ocornut/imgui/issues/3361 for all details.
  462. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
  463. for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
  464. - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
  465. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
  466. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
  467. - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
  468. - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
  469. - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
  470. - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
  471. - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
  472. - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
  473. - ShowTestWindow() -> use ShowDemoWindow()
  474. - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
  475. - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
  476. - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
  477. - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
  478. - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
  479. - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
  480. - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
  481. - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
  482. - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
  483. - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
  484. - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
  485. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
  486. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
  487. - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
  488. - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
  489. - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
  490. - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
  491. - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
  492. - ImFont::Glyph -> use ImFontGlyph
  493. - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
  494. if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
  495. The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
  496. If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
  497. - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
  498. - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
  499. - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
  500. - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
  501. overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
  502. This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
  503. Please reach out if you are affected.
  504. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
  505. - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
  506. - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
  507. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
  508. - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
  509. - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
  510. - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
  511. - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
  512. - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
  513. - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
  514. - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
  515. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
  516. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
  517. - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
  518. - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
  519. If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
  520. - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
  521. - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
  522. NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
  523. Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
  524. - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
  525. - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
  526. - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
  527. - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
  528. - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
  529. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
  530. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
  531. - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
  532. old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
  533. when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
  534. in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
  535. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
  536. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
  537. - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
  538. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
  539. To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
  540. If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
  541. - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
  542. consistent with other functions. Kept redirection functions (will obsolete).
  543. - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
  544. - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
  545. - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
  546. - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
  547. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
  548. - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
  549. - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
  550. - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
  551. - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
  552. - removed Shutdown() function, as DestroyContext() serve this purpose.
  553. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
  554. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
  555. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
  556. - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
  557. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
  558. - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
  559. - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
  560. - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
  561. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
  562. - 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
  563. - 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.
  564. - 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.
  565. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
  566. - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
  567. - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
  568. - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
  569. - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
  570. - 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.
  571. - 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.
  572. 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.
  573. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
  574. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
  575. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
  576. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
  577. - 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.
  578. - 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.
  579. - 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.
  580. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
  581. IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
  582. IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
  583. IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
  584. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
  585. - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
  586. - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
  587. - 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).
  588. - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
  589. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
  590. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  591. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  592. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  593. - 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.
  594. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
  595. - 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.
  596. - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
  597. - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
  598. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  599. - 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.
  600. - 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.
  601. - 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))'
  602. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  603. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  604. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  605. - 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().
  606. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  607. - 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.
  608. - 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.
  609. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  610. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
  611. 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:
  612. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
  613. 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.
  614. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  615. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  616. - 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).
  617. - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
  618. - 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).
  619. - 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)
  620. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  621. - 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.
  622. - 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.
  623. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  624. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  625. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  626. 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.
  627. 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!
  628. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  629. - 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.
  630. - 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
  631. - 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.
  632. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  633. - 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.
  634. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  635. - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
  636. - the signature of the io.RenderDrawListsFn handler has changed!
  637. old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  638. new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  639. parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
  640. ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
  641. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
  642. - 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.
  643. - 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!
  644. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  645. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  646. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  647. - 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.
  648. - 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
  649. - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
  650. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  651. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  652. - 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.
  653. - 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.
  654. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  655. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  656. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  657. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  658. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  659. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  660. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  661. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  662. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  663. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  664. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  665. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  666. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  667. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  668. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  669. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  670. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  671. - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  672. - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
  673. - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
  674. you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
  675. - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
  676. - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  677. - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  678. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  679. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  680. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  681. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  682. - 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)
  683. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  684. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  685. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  686. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  687. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  688. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  689. FREQUENTLY ASKED QUESTIONS (FAQ)
  690. ================================
  691. Read all answers online:
  692. https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
  693. Read all answers locally (with a text editor or ideally a Markdown viewer):
  694. docs/FAQ.md
  695. Some answers are copied down here to facilitate searching in code.
  696. Q&A: Basics
  697. ===========
  698. Q: Where is the documentation?
  699. A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
  700. - Run the examples/ and explore them.
  701. - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
  702. - The demo covers most features of Dear ImGui, so you can read the code and see its output.
  703. - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
  704. - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
  705. examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
  706. - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
  707. - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
  708. - Your programming IDE is your friend, find the type or function declaration to find comments
  709. associated with it.
  710. Q: What is this library called?
  711. Q: Which version should I get?
  712. >> This library is called "Dear ImGui", please don't call it "ImGui" :)
  713. >> See https://www.dearimgui.org/faq for details.
  714. Q&A: Integration
  715. ================
  716. Q: How to get started?
  717. A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
  718. Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
  719. A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
  720. >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
  721. Q. How can I enable keyboard controls?
  722. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
  723. Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
  724. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
  725. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
  726. >> See https://www.dearimgui.org/faq
  727. Q&A: Usage
  728. ----------
  729. Q: About the ID Stack system..
  730. - Why is my widget not reacting when I click on it?
  731. - How can I have widgets with an empty label?
  732. - How can I have multiple widgets with the same label?
  733. - How can I have multiple windows with the same label?
  734. Q: How can I display an image? What is ImTextureID, how does it work?
  735. Q: How can I use my own math types instead of ImVec2/ImVec4?
  736. Q: How can I interact with standard C++ types (such as std::string and std::vector)?
  737. Q: How can I display custom shapes? (using low-level ImDrawList API)
  738. >> See https://www.dearimgui.org/faq
  739. Q&A: Fonts, Text
  740. ================
  741. Q: How should I handle DPI in my application?
  742. Q: How can I load a different font than the default?
  743. Q: How can I easily use icons in my application?
  744. Q: How can I load multiple fonts?
  745. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  746. >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
  747. Q&A: Concerns
  748. =============
  749. Q: Who uses Dear ImGui?
  750. Q: Can you create elaborate/serious tools with Dear ImGui?
  751. Q: Can you reskin the look of Dear ImGui?
  752. Q: Why using C++ (as opposed to C)?
  753. >> See https://www.dearimgui.org/faq
  754. Q&A: Community
  755. ==============
  756. Q: How can I help?
  757. A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
  758. We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
  759. This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
  760. - Individuals: you can support continued development via PayPal donations. See README.
  761. - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
  762. and see how you want to help and can help!
  763. - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
  764. You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
  765. But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
  766. - 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).
  767. */
  768. //-------------------------------------------------------------------------
  769. // [SECTION] INCLUDES
  770. //-------------------------------------------------------------------------
  771. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  772. #define _CRT_SECURE_NO_WARNINGS
  773. #endif
  774. #include "imgui.h"
  775. #ifndef IMGUI_DISABLE
  776. #ifndef IMGUI_DEFINE_MATH_OPERATORS
  777. #define IMGUI_DEFINE_MATH_OPERATORS
  778. #endif
  779. #include "imgui_internal.h"
  780. // System includes
  781. #include <stdio.h> // vsnprintf, sscanf, printf
  782. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  783. #include <stddef.h> // intptr_t
  784. #else
  785. #include <stdint.h> // intptr_t
  786. #endif
  787. // [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
  788. #if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  789. #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
  790. #endif
  791. // [Windows] OS specific includes (optional)
  792. #if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
  793. #define IMGUI_DISABLE_WIN32_FUNCTIONS
  794. #endif
  795. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
  796. #ifndef WIN32_LEAN_AND_MEAN
  797. #define WIN32_LEAN_AND_MEAN
  798. #endif
  799. #ifndef NOMINMAX
  800. #define NOMINMAX
  801. #endif
  802. #ifndef __MINGW32__
  803. #include <Windows.h> // _wfopen, OpenClipboard
  804. #else
  805. #include <windows.h>
  806. #endif
  807. #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
  808. #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
  809. #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
  810. #endif
  811. #endif
  812. // [Apple] OS specific includes
  813. #if defined(__APPLE__)
  814. #include <TargetConditionals.h>
  815. #endif
  816. // Visual Studio warnings
  817. #ifdef _MSC_VER
  818. #pragma warning (disable: 4127) // condition expression is constant
  819. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  820. #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
  821. #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
  822. #endif
  823. #pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
  824. #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
  825. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  826. #endif
  827. // Clang/GCC warnings with -Weverything
  828. #if defined(__clang__)
  829. #if __has_warning("-Wunknown-warning-option")
  830. #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
  831. #endif
  832. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
  833. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
  834. #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.
  835. #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.
  836. #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.
  837. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
  838. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  839. #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.
  840. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
  841. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
  842. #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
  843. #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
  844. #elif defined(__GNUC__)
  845. // We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
  846. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  847. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  848. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  849. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  850. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  851. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  852. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  853. #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
  854. #pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
  855. #endif
  856. // Debug options
  857. #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
  858. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
  859. #define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
  860. // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
  861. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
  862. static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
  863. // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
  864. static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
  865. static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
  866. static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.80f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
  867. //-------------------------------------------------------------------------
  868. // [SECTION] FORWARD DECLARATIONS
  869. //-------------------------------------------------------------------------
  870. static void SetCurrentWindow(ImGuiWindow* window);
  871. static void FindHoveredWindow();
  872. static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
  873. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
  874. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
  875. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
  876. // Settings
  877. static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
  878. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
  879. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
  880. static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
  881. static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
  882. // Platform Dependents default implementation for IO functions
  883. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  884. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  885. static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
  886. namespace ImGui
  887. {
  888. // Navigation
  889. static void NavUpdate();
  890. static void NavUpdateWindowing();
  891. static void NavUpdateWindowingOverlay();
  892. static void NavUpdateCancelRequest();
  893. static void NavUpdateCreateMoveRequest();
  894. static void NavUpdateCreateTabbingRequest();
  895. static float NavUpdatePageUpPageDown();
  896. static inline void NavUpdateAnyRequestFlag();
  897. static void NavUpdateCreateWrappingRequest();
  898. static void NavEndFrame();
  899. static bool NavScoreItem(ImGuiNavItemData* result);
  900. static void NavApplyItemToResult(ImGuiNavItemData* result);
  901. static void NavProcessItem();
  902. static void NavProcessItemForTabbingRequest(ImGuiID id);
  903. static ImVec2 NavCalcPreferredRefPos();
  904. static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
  905. static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
  906. static void NavRestoreLayer(ImGuiNavLayer layer);
  907. static void NavRestoreHighlightAfterMove();
  908. static int FindWindowFocusIndex(ImGuiWindow* window);
  909. // Error Checking and Debug Tools
  910. static void ErrorCheckNewFrameSanityChecks();
  911. static void ErrorCheckEndFrameSanityChecks();
  912. static void UpdateDebugToolItemPicker();
  913. static void UpdateDebugToolStackQueries();
  914. // Misc
  915. static void UpdateSettings();
  916. static void UpdateKeyboardInputs();
  917. static void UpdateMouseInputs();
  918. static void UpdateMouseWheel();
  919. static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
  920. static void RenderWindowOuterBorders(ImGuiWindow* window);
  921. static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
  922. static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
  923. static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
  924. static void RenderDimmedBackgrounds();
  925. static ImGuiWindow* FindBlockingModal(ImGuiWindow* window);
  926. // Viewports
  927. static void UpdateViewportsNewFrame();
  928. }
  929. //-----------------------------------------------------------------------------
  930. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  931. //-----------------------------------------------------------------------------
  932. // DLL users:
  933. // - Heaps and globals are not shared across DLL boundaries!
  934. // - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
  935. // - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
  936. // - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
  937. // - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
  938. // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
  939. // - ImGui::CreateContext() will automatically set this pointer if it is NULL.
  940. // Change to a different context by calling ImGui::SetCurrentContext().
  941. // - Important: Dear ImGui functions are not thread-safe because of this pointer.
  942. // If you want thread-safety to allow N threads to access N different contexts:
  943. // - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
  944. // struct ImGuiContext;
  945. // extern thread_local ImGuiContext* MyImGuiTLS;
  946. // #define GImGui MyImGuiTLS
  947. // And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
  948. // - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  949. // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
  950. // - DLL users: read comments above.
  951. #ifndef GImGui
  952. ImGuiContext* GImGui = NULL;
  953. #endif
  954. // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
  955. // - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
  956. // - DLL users: read comments above.
  957. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
  958. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
  959. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
  960. #else
  961. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
  962. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
  963. #endif
  964. static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
  965. static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
  966. static void* GImAllocatorUserData = NULL;
  967. //-----------------------------------------------------------------------------
  968. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  969. //-----------------------------------------------------------------------------
  970. ImGuiStyle::ImGuiStyle()
  971. {
  972. Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
  973. DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
  974. WindowPadding = ImVec2(8,8); // Padding within a window
  975. WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
  976. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  977. WindowMinSize = ImVec2(32,32); // Minimum window size
  978. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  979. WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
  980. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  981. ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  982. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
  983. PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  984. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  985. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  986. FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
  987. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  988. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  989. CellPadding = ImVec2(4,2); // Padding within a table cell
  990. 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!
  991. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  992. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
  993. ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  994. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  995. GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
  996. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  997. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
  998. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
  999. TabBorderSize = 0.0f; // Thickness of border around tabs.
  1000. TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
  1001. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
  1002. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  1003. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
  1004. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
  1005. DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
  1006. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
  1007. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
  1008. AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
  1009. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
  1010. 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.
  1011. CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
  1012. // Default theme
  1013. ImGui::StyleColorsDark(this);
  1014. }
  1015. // 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.
  1016. // 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.
  1017. void ImGuiStyle::ScaleAllSizes(float scale_factor)
  1018. {
  1019. WindowPadding = ImFloor(WindowPadding * scale_factor);
  1020. WindowRounding = ImFloor(WindowRounding * scale_factor);
  1021. WindowMinSize = ImFloor(WindowMinSize * scale_factor);
  1022. ChildRounding = ImFloor(ChildRounding * scale_factor);
  1023. PopupRounding = ImFloor(PopupRounding * scale_factor);
  1024. FramePadding = ImFloor(FramePadding * scale_factor);
  1025. FrameRounding = ImFloor(FrameRounding * scale_factor);
  1026. ItemSpacing = ImFloor(ItemSpacing * scale_factor);
  1027. ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
  1028. CellPadding = ImFloor(CellPadding * scale_factor);
  1029. TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
  1030. IndentSpacing = ImFloor(IndentSpacing * scale_factor);
  1031. ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
  1032. ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
  1033. ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
  1034. GrabMinSize = ImFloor(GrabMinSize * scale_factor);
  1035. GrabRounding = ImFloor(GrabRounding * scale_factor);
  1036. LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
  1037. TabRounding = ImFloor(TabRounding * scale_factor);
  1038. TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
  1039. DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
  1040. DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
  1041. MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
  1042. }
  1043. ImGuiIO::ImGuiIO()
  1044. {
  1045. // Most fields are initialized with zero
  1046. memset(this, 0, sizeof(*this));
  1047. IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
  1048. // Settings
  1049. ConfigFlags = ImGuiConfigFlags_None;
  1050. BackendFlags = ImGuiBackendFlags_None;
  1051. DisplaySize = ImVec2(-1.0f, -1.0f);
  1052. DeltaTime = 1.0f / 60.0f;
  1053. IniSavingRate = 5.0f;
  1054. IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
  1055. LogFilename = "imgui_log.txt";
  1056. MouseDoubleClickTime = 0.30f;
  1057. MouseDoubleClickMaxDist = 6.0f;
  1058. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1059. for (int i = 0; i < ImGuiKey_COUNT; i++)
  1060. KeyMap[i] = -1;
  1061. #endif
  1062. KeyRepeatDelay = 0.275f;
  1063. KeyRepeatRate = 0.050f;
  1064. HoverDelayNormal = 0.30f;
  1065. HoverDelayShort = 0.10f;
  1066. UserData = NULL;
  1067. Fonts = NULL;
  1068. FontGlobalScale = 1.0f;
  1069. FontDefault = NULL;
  1070. FontAllowUserScaling = false;
  1071. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  1072. // Miscellaneous options
  1073. MouseDrawCursor = false;
  1074. #ifdef __APPLE__
  1075. ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
  1076. #else
  1077. ConfigMacOSXBehaviors = false;
  1078. #endif
  1079. ConfigInputTrickleEventQueue = true;
  1080. ConfigInputTextCursorBlink = true;
  1081. ConfigInputTextEnterKeepActive = false;
  1082. ConfigDragClickToInputText = false;
  1083. ConfigWindowsResizeFromEdges = true;
  1084. ConfigWindowsMoveFromTitleBarOnly = false;
  1085. ConfigMemoryCompactTimer = 60.0f;
  1086. // Platform Functions
  1087. BackendPlatformName = BackendRendererName = NULL;
  1088. BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
  1089. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  1090. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  1091. ClipboardUserData = NULL;
  1092. SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
  1093. // Input (NB: we already have memset zero the entire structure!)
  1094. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  1095. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  1096. MouseDragThreshold = 6.0f;
  1097. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  1098. for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
  1099. AppAcceptingEvents = true;
  1100. BackendUsingLegacyKeyArrays = (ImS8)-1;
  1101. BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
  1102. }
  1103. // Pass in translated ASCII characters for text input.
  1104. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  1105. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  1106. // FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
  1107. void ImGuiIO::AddInputCharacter(unsigned int c)
  1108. {
  1109. ImGuiContext& g = *GImGui;
  1110. IM_ASSERT(&g.IO == this && "Can only add events to current context.");
  1111. if (c == 0 || !AppAcceptingEvents)
  1112. return;
  1113. ImGuiInputEvent e;
  1114. e.Type = ImGuiInputEventType_Text;
  1115. e.Source = ImGuiInputSource_Keyboard;
  1116. e.Text.Char = c;
  1117. g.InputEventsQueue.push_back(e);
  1118. }
  1119. // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
  1120. // we should save the high surrogate.
  1121. void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
  1122. {
  1123. if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
  1124. return;
  1125. if ((c & 0xFC00) == 0xD800) // High surrogate, must save
  1126. {
  1127. if (InputQueueSurrogate != 0)
  1128. AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
  1129. InputQueueSurrogate = c;
  1130. return;
  1131. }
  1132. ImWchar cp = c;
  1133. if (InputQueueSurrogate != 0)
  1134. {
  1135. if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
  1136. {
  1137. AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
  1138. }
  1139. else
  1140. {
  1141. #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
  1142. cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
  1143. #else
  1144. cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
  1145. #endif
  1146. }
  1147. InputQueueSurrogate = 0;
  1148. }
  1149. AddInputCharacter((unsigned)cp);
  1150. }
  1151. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  1152. {
  1153. if (!AppAcceptingEvents)
  1154. return;
  1155. while (*utf8_chars != 0)
  1156. {
  1157. unsigned int c = 0;
  1158. utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
  1159. if (c != 0)
  1160. AddInputCharacter(c);
  1161. }
  1162. }
  1163. // FIXME: Perhaps we could clear queued events as well?
  1164. void ImGuiIO::ClearInputCharacters()
  1165. {
  1166. InputQueueCharacters.resize(0);
  1167. }
  1168. // FIXME: Perhaps we could clear queued events as well?
  1169. void ImGuiIO::ClearInputKeys()
  1170. {
  1171. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1172. memset(KeysDown, 0, sizeof(KeysDown));
  1173. #endif
  1174. for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
  1175. {
  1176. KeysData[n].Down = false;
  1177. KeysData[n].DownDuration = -1.0f;
  1178. KeysData[n].DownDurationPrev = -1.0f;
  1179. }
  1180. KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
  1181. KeyMods = ImGuiMod_None;
  1182. }
  1183. static ImGuiInputEvent* FindLatestInputEvent(ImGuiInputEventType type, int arg = -1)
  1184. {
  1185. ImGuiContext& g = *GImGui;
  1186. for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
  1187. {
  1188. ImGuiInputEvent* e = &g.InputEventsQueue[n];
  1189. if (e->Type != type)
  1190. continue;
  1191. if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
  1192. continue;
  1193. if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
  1194. continue;
  1195. return e;
  1196. }
  1197. return NULL;
  1198. }
  1199. // Queue a new key down/up event.
  1200. // - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
  1201. // - bool down: Is the key down? use false to signify a key release.
  1202. // - float analog_value: 0.0f..1.0f
  1203. void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
  1204. {
  1205. //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
  1206. if (key == ImGuiKey_None || !AppAcceptingEvents)
  1207. return;
  1208. ImGuiContext& g = *GImGui;
  1209. IM_ASSERT(&g.IO == this && "Can only add events to current context.");
  1210. IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
  1211. IM_ASSERT(!ImGui::IsAliasKey(key)); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
  1212. // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
  1213. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1214. IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
  1215. if (BackendUsingLegacyKeyArrays == -1)
  1216. for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
  1217. IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
  1218. BackendUsingLegacyKeyArrays = 0;
  1219. #endif
  1220. if (ImGui::IsGamepadKey(key))
  1221. BackendUsingLegacyNavInputArray = false;
  1222. // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
  1223. const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Key, (int)key);
  1224. const ImGuiKeyData* key_data = ImGui::GetKeyData(key);
  1225. const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
  1226. const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
  1227. if (latest_key_down == down && latest_key_analog == analog_value)
  1228. return;
  1229. // Add event
  1230. ImGuiInputEvent e;
  1231. e.Type = ImGuiInputEventType_Key;
  1232. e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
  1233. e.Key.Key = key;
  1234. e.Key.Down = down;
  1235. e.Key.AnalogValue = analog_value;
  1236. g.InputEventsQueue.push_back(e);
  1237. }
  1238. void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
  1239. {
  1240. if (!AppAcceptingEvents)
  1241. return;
  1242. AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
  1243. }
  1244. // [Optional] Call after AddKeyEvent().
  1245. // Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
  1246. // If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
  1247. void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
  1248. {
  1249. if (key == ImGuiKey_None)
  1250. return;
  1251. IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
  1252. IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
  1253. IM_UNUSED(native_keycode); // Yet unused
  1254. IM_UNUSED(native_scancode); // Yet unused
  1255. // Build native->imgui map so old user code can still call key functions with native 0..511 values.
  1256. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  1257. const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
  1258. if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
  1259. return;
  1260. KeyMap[legacy_key] = key;
  1261. KeyMap[key] = legacy_key;
  1262. #else
  1263. IM_UNUSED(key);
  1264. IM_UNUSED(native_legacy_index);
  1265. #endif
  1266. }
  1267. // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
  1268. void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
  1269. {
  1270. AppAcceptingEvents = accepting_events;
  1271. }
  1272. // Queue a mouse move event
  1273. void ImGuiIO::AddMousePosEvent(float x, float y)
  1274. {
  1275. ImGuiContext& g = *GImGui;
  1276. IM_ASSERT(&g.IO == this && "Can only add events to current context.");
  1277. if (!AppAcceptingEvents)
  1278. return;
  1279. // Apply same flooring as UpdateMouseInputs()
  1280. ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
  1281. // Filter duplicate
  1282. const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MousePos);
  1283. const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
  1284. if (latest_pos.x == pos.x && latest_pos.y == pos.y)
  1285. return;
  1286. ImGuiInputEvent e;
  1287. e.Type = ImGuiInputEventType_MousePos;
  1288. e.Source = ImGuiInputSource_Mouse;
  1289. e.MousePos.PosX = pos.x;
  1290. e.MousePos.PosY = pos.y;
  1291. g.InputEventsQueue.push_back(e);
  1292. }
  1293. void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
  1294. {
  1295. ImGuiContext& g = *GImGui;
  1296. IM_ASSERT(&g.IO == this && "Can only add events to current context.");
  1297. IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
  1298. if (!AppAcceptingEvents)
  1299. return;
  1300. // Filter duplicate
  1301. const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseButton, (int)mouse_button);
  1302. const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
  1303. if (latest_button_down == down)
  1304. return;
  1305. ImGuiInputEvent e;
  1306. e.Type = ImGuiInputEventType_MouseButton;
  1307. e.Source = ImGuiInputSource_Mouse;
  1308. e.MouseButton.Button = mouse_button;
  1309. e.MouseButton.Down = down;
  1310. g.InputEventsQueue.push_back(e);
  1311. }
  1312. // Queue a mouse wheel event (most mouse/API will only have a Y component)
  1313. void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
  1314. {
  1315. ImGuiContext& g = *GImGui;
  1316. IM_ASSERT(&g.IO == this && "Can only add events to current context.");
  1317. // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
  1318. if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
  1319. return;
  1320. ImGuiInputEvent e;
  1321. e.Type = ImGuiInputEventType_MouseWheel;
  1322. e.Source = ImGuiInputSource_Mouse;
  1323. e.MouseWheel.WheelX = wheel_x;
  1324. e.MouseWheel.WheelY = wheel_y;
  1325. g.InputEventsQueue.push_back(e);
  1326. }
  1327. void ImGuiIO::AddFocusEvent(bool focused)
  1328. {
  1329. ImGuiContext& g = *GImGui;
  1330. IM_ASSERT(&g.IO == this && "Can only add events to current context.");
  1331. // Filter duplicate
  1332. const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Focus);
  1333. const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
  1334. if (latest_focused == focused)
  1335. return;
  1336. ImGuiInputEvent e;
  1337. e.Type = ImGuiInputEventType_Focus;
  1338. e.AppFocused.Focused = focused;
  1339. g.InputEventsQueue.push_back(e);
  1340. }
  1341. //-----------------------------------------------------------------------------
  1342. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  1343. //-----------------------------------------------------------------------------
  1344. ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
  1345. {
  1346. IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
  1347. ImVec2 p_last = p1;
  1348. ImVec2 p_closest;
  1349. float p_closest_dist2 = FLT_MAX;
  1350. float t_step = 1.0f / (float)num_segments;
  1351. for (int i_step = 1; i_step <= num_segments; i_step++)
  1352. {
  1353. ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
  1354. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1355. float dist2 = ImLengthSqr(p - p_line);
  1356. if (dist2 < p_closest_dist2)
  1357. {
  1358. p_closest = p_line;
  1359. p_closest_dist2 = dist2;
  1360. }
  1361. p_last = p_current;
  1362. }
  1363. return p_closest;
  1364. }
  1365. // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
  1366. static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
  1367. {
  1368. float dx = x4 - x1;
  1369. float dy = y4 - y1;
  1370. float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
  1371. float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
  1372. d2 = (d2 >= 0) ? d2 : -d2;
  1373. d3 = (d3 >= 0) ? d3 : -d3;
  1374. if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
  1375. {
  1376. ImVec2 p_current(x4, y4);
  1377. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1378. float dist2 = ImLengthSqr(p - p_line);
  1379. if (dist2 < p_closest_dist2)
  1380. {
  1381. p_closest = p_line;
  1382. p_closest_dist2 = dist2;
  1383. }
  1384. p_last = p_current;
  1385. }
  1386. else if (level < 10)
  1387. {
  1388. float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
  1389. float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
  1390. float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
  1391. float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
  1392. float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
  1393. float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
  1394. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
  1395. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
  1396. }
  1397. }
  1398. // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
  1399. // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
  1400. ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
  1401. {
  1402. IM_ASSERT(tess_tol > 0.0f);
  1403. ImVec2 p_last = p1;
  1404. ImVec2 p_closest;
  1405. float p_closest_dist2 = FLT_MAX;
  1406. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
  1407. return p_closest;
  1408. }
  1409. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  1410. {
  1411. ImVec2 ap = p - a;
  1412. ImVec2 ab_dir = b - a;
  1413. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  1414. if (dot < 0.0f)
  1415. return a;
  1416. float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
  1417. if (dot > ab_len_sqr)
  1418. return b;
  1419. return a + ab_dir * dot / ab_len_sqr;
  1420. }
  1421. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1422. {
  1423. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  1424. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  1425. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  1426. return ((b1 == b2) && (b2 == b3));
  1427. }
  1428. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  1429. {
  1430. ImVec2 v0 = b - a;
  1431. ImVec2 v1 = c - a;
  1432. ImVec2 v2 = p - a;
  1433. const float denom = v0.x * v1.y - v1.x * v0.y;
  1434. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  1435. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  1436. out_u = 1.0f - out_v - out_w;
  1437. }
  1438. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1439. {
  1440. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  1441. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  1442. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  1443. float dist2_ab = ImLengthSqr(p - proj_ab);
  1444. float dist2_bc = ImLengthSqr(p - proj_bc);
  1445. float dist2_ca = ImLengthSqr(p - proj_ca);
  1446. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  1447. if (m == dist2_ab)
  1448. return proj_ab;
  1449. if (m == dist2_bc)
  1450. return proj_bc;
  1451. return proj_ca;
  1452. }
  1453. //-----------------------------------------------------------------------------
  1454. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  1455. //-----------------------------------------------------------------------------
  1456. // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
  1457. int ImStricmp(const char* str1, const char* str2)
  1458. {
  1459. int d;
  1460. while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
  1461. return d;
  1462. }
  1463. int ImStrnicmp(const char* str1, const char* str2, size_t count)
  1464. {
  1465. int d = 0;
  1466. while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  1467. return d;
  1468. }
  1469. void ImStrncpy(char* dst, const char* src, size_t count)
  1470. {
  1471. if (count < 1)
  1472. return;
  1473. if (count > 1)
  1474. strncpy(dst, src, count - 1);
  1475. dst[count - 1] = 0;
  1476. }
  1477. char* ImStrdup(const char* str)
  1478. {
  1479. size_t len = strlen(str);
  1480. void* buf = IM_ALLOC(len + 1);
  1481. return (char*)memcpy(buf, (const void*)str, len + 1);
  1482. }
  1483. char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
  1484. {
  1485. size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
  1486. size_t src_size = strlen(src) + 1;
  1487. if (dst_buf_size < src_size)
  1488. {
  1489. IM_FREE(dst);
  1490. dst = (char*)IM_ALLOC(src_size);
  1491. if (p_dst_size)
  1492. *p_dst_size = src_size;
  1493. }
  1494. return (char*)memcpy(dst, (const void*)src, src_size);
  1495. }
  1496. const char* ImStrchrRange(const char* str, const char* str_end, char c)
  1497. {
  1498. const char* p = (const char*)memchr(str, (int)c, str_end - str);
  1499. return p;
  1500. }
  1501. int ImStrlenW(const ImWchar* str)
  1502. {
  1503. //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
  1504. int n = 0;
  1505. while (*str++) n++;
  1506. return n;
  1507. }
  1508. // Find end-of-line. Return pointer will point to either first \n, either str_end.
  1509. const char* ImStreolRange(const char* str, const char* str_end)
  1510. {
  1511. const char* p = (const char*)memchr(str, '\n', str_end - str);
  1512. return p ? p : str_end;
  1513. }
  1514. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  1515. {
  1516. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  1517. buf_mid_line--;
  1518. return buf_mid_line;
  1519. }
  1520. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  1521. {
  1522. if (!needle_end)
  1523. needle_end = needle + strlen(needle);
  1524. const char un0 = (char)ImToUpper(*needle);
  1525. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  1526. {
  1527. if (ImToUpper(*haystack) == un0)
  1528. {
  1529. const char* b = needle + 1;
  1530. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  1531. if (ImToUpper(*a) != ImToUpper(*b))
  1532. break;
  1533. if (b == needle_end)
  1534. return haystack;
  1535. }
  1536. haystack++;
  1537. }
  1538. return NULL;
  1539. }
  1540. // Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
  1541. void ImStrTrimBlanks(char* buf)
  1542. {
  1543. char* p = buf;
  1544. while (p[0] == ' ' || p[0] == '\t') // Leading blanks
  1545. p++;
  1546. char* p_start = p;
  1547. while (*p != 0) // Find end of string
  1548. p++;
  1549. while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
  1550. p--;
  1551. if (p_start != buf) // Copy memory if we had leading blanks
  1552. memmove(buf, p_start, p - p_start);
  1553. buf[p - p_start] = 0; // Zero terminate
  1554. }
  1555. const char* ImStrSkipBlank(const char* str)
  1556. {
  1557. while (str[0] == ' ' || str[0] == '\t')
  1558. str++;
  1559. return str;
  1560. }
  1561. // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  1562. // 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.
  1563. // B) When buf==NULL vsnprintf() will return the output size.
  1564. #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1565. // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
  1566. // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1567. // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
  1568. // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
  1569. #ifdef IMGUI_USE_STB_SPRINTF
  1570. #define STB_SPRINTF_IMPLEMENTATION
  1571. #ifdef IMGUI_STB_SPRINTF_FILENAME
  1572. #include IMGUI_STB_SPRINTF_FILENAME
  1573. #else
  1574. #include "stb_sprintf.h"
  1575. #endif
  1576. #endif
  1577. #if defined(_MSC_VER) && !defined(vsnprintf)
  1578. #define vsnprintf _vsnprintf
  1579. #endif
  1580. int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
  1581. {
  1582. va_list args;
  1583. va_start(args, fmt);
  1584. #ifdef IMGUI_USE_STB_SPRINTF
  1585. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1586. #else
  1587. int w = vsnprintf(buf, buf_size, fmt, args);
  1588. #endif
  1589. va_end(args);
  1590. if (buf == NULL)
  1591. return w;
  1592. if (w == -1 || w >= (int)buf_size)
  1593. w = (int)buf_size - 1;
  1594. buf[w] = 0;
  1595. return w;
  1596. }
  1597. int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
  1598. {
  1599. #ifdef IMGUI_USE_STB_SPRINTF
  1600. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1601. #else
  1602. int w = vsnprintf(buf, buf_size, fmt, args);
  1603. #endif
  1604. if (buf == NULL)
  1605. return w;
  1606. if (w == -1 || w >= (int)buf_size)
  1607. w = (int)buf_size - 1;
  1608. buf[w] = 0;
  1609. return w;
  1610. }
  1611. #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1612. void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
  1613. {
  1614. ImGuiContext& g = *GImGui;
  1615. va_list args;
  1616. va_start(args, fmt);
  1617. int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
  1618. *out_buf = g.TempBuffer.Data;
  1619. if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
  1620. va_end(args);
  1621. }
  1622. void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
  1623. {
  1624. ImGuiContext& g = *GImGui;
  1625. int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
  1626. *out_buf = g.TempBuffer.Data;
  1627. if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
  1628. }
  1629. // CRC32 needs a 1KB lookup table (not cache friendly)
  1630. // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
  1631. // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
  1632. static const ImU32 GCrc32LookupTable[256] =
  1633. {
  1634. 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
  1635. 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
  1636. 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
  1637. 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
  1638. 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
  1639. 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
  1640. 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
  1641. 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
  1642. 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
  1643. 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
  1644. 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
  1645. 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
  1646. 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
  1647. 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
  1648. 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
  1649. 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
  1650. };
  1651. // Known size hash
  1652. // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
  1653. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1654. ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
  1655. {
  1656. ImU32 crc = ~seed;
  1657. const unsigned char* data = (const unsigned char*)data_p;
  1658. const ImU32* crc32_lut = GCrc32LookupTable;
  1659. while (data_size-- != 0)
  1660. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
  1661. return ~crc;
  1662. }
  1663. // Zero-terminated string hash, with support for ### to reset back to seed value
  1664. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  1665. // Because this syntax is rarely used we are optimizing for the common case.
  1666. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  1667. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
  1668. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1669. ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
  1670. {
  1671. seed = ~seed;
  1672. ImU32 crc = seed;
  1673. const unsigned char* data = (const unsigned char*)data_p;
  1674. const ImU32* crc32_lut = GCrc32LookupTable;
  1675. if (data_size != 0)
  1676. {
  1677. while (data_size-- != 0)
  1678. {
  1679. unsigned char c = *data++;
  1680. if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
  1681. crc = seed;
  1682. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1683. }
  1684. }
  1685. else
  1686. {
  1687. while (unsigned char c = *data++)
  1688. {
  1689. if (c == '#' && data[0] == '#' && data[1] == '#')
  1690. crc = seed;
  1691. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1692. }
  1693. }
  1694. return ~crc;
  1695. }
  1696. //-----------------------------------------------------------------------------
  1697. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  1698. //-----------------------------------------------------------------------------
  1699. // Default file functions
  1700. #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1701. ImFileHandle ImFileOpen(const char* filename, const char* mode)
  1702. {
  1703. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
  1704. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
  1705. // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
  1706. const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
  1707. const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
  1708. ImVector<ImWchar> buf;
  1709. buf.resize(filename_wsize + mode_wsize);
  1710. ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
  1711. ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
  1712. return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
  1713. #else
  1714. return fopen(filename, mode);
  1715. #endif
  1716. }
  1717. // We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
  1718. bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
  1719. ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
  1720. ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
  1721. ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
  1722. #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1723. // Helper: Load file content into memory
  1724. // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
  1725. // This can't really be used with "rt" because fseek size won't match read size.
  1726. void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
  1727. {
  1728. IM_ASSERT(filename && mode);
  1729. if (out_file_size)
  1730. *out_file_size = 0;
  1731. ImFileHandle f;
  1732. if ((f = ImFileOpen(filename, mode)) == NULL)
  1733. return NULL;
  1734. size_t file_size = (size_t)ImFileGetSize(f);
  1735. if (file_size == (size_t)-1)
  1736. {
  1737. ImFileClose(f);
  1738. return NULL;
  1739. }
  1740. void* file_data = IM_ALLOC(file_size + padding_bytes);
  1741. if (file_data == NULL)
  1742. {
  1743. ImFileClose(f);
  1744. return NULL;
  1745. }
  1746. if (ImFileRead(file_data, 1, file_size, f) != file_size)
  1747. {
  1748. ImFileClose(f);
  1749. IM_FREE(file_data);
  1750. return NULL;
  1751. }
  1752. if (padding_bytes > 0)
  1753. memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
  1754. ImFileClose(f);
  1755. if (out_file_size)
  1756. *out_file_size = file_size;
  1757. return file_data;
  1758. }
  1759. //-----------------------------------------------------------------------------
  1760. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  1761. //-----------------------------------------------------------------------------
  1762. // Convert UTF-8 to 32-bit character, process single character input.
  1763. // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
  1764. // We handle UTF-8 decoding error by skipping forward.
  1765. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1766. {
  1767. static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
  1768. static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
  1769. static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
  1770. static const int shiftc[] = { 0, 18, 12, 6, 0 };
  1771. static const int shifte[] = { 0, 6, 4, 2, 0 };
  1772. int len = lengths[*(const unsigned char*)in_text >> 3];
  1773. int wanted = len + !len;
  1774. if (in_text_end == NULL)
  1775. in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
  1776. // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
  1777. // so it is fast even with excessive branching.
  1778. unsigned char s[4];
  1779. s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
  1780. s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
  1781. s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
  1782. s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
  1783. // Assume a four-byte character and load four bytes. Unused bits are shifted out.
  1784. *out_char = (uint32_t)(s[0] & masks[len]) << 18;
  1785. *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
  1786. *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
  1787. *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
  1788. *out_char >>= shiftc[len];
  1789. // Accumulate the various error conditions.
  1790. int e = 0;
  1791. e = (*out_char < mins[len]) << 6; // non-canonical encoding
  1792. e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
  1793. e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
  1794. e |= (s[1] & 0xc0) >> 2;
  1795. e |= (s[2] & 0xc0) >> 4;
  1796. e |= (s[3] ) >> 6;
  1797. e ^= 0x2a; // top two bits of each tail byte correct?
  1798. e >>= shifte[len];
  1799. if (e)
  1800. {
  1801. // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
  1802. // One byte is consumed in case of invalid first byte of in_text.
  1803. // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
  1804. // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
  1805. wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
  1806. *out_char = IM_UNICODE_CODEPOINT_INVALID;
  1807. }
  1808. return wanted;
  1809. }
  1810. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1811. {
  1812. ImWchar* buf_out = buf;
  1813. ImWchar* buf_end = buf + buf_size;
  1814. while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1815. {
  1816. unsigned int c;
  1817. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1818. if (c == 0)
  1819. break;
  1820. *buf_out++ = (ImWchar)c;
  1821. }
  1822. *buf_out = 0;
  1823. if (in_text_remaining)
  1824. *in_text_remaining = in_text;
  1825. return (int)(buf_out - buf);
  1826. }
  1827. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1828. {
  1829. int char_count = 0;
  1830. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1831. {
  1832. unsigned int c;
  1833. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1834. if (c == 0)
  1835. break;
  1836. char_count++;
  1837. }
  1838. return char_count;
  1839. }
  1840. // Based on stb_to_utf8() from github.com/nothings/stb/
  1841. static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
  1842. {
  1843. if (c < 0x80)
  1844. {
  1845. buf[0] = (char)c;
  1846. return 1;
  1847. }
  1848. if (c < 0x800)
  1849. {
  1850. if (buf_size < 2) return 0;
  1851. buf[0] = (char)(0xc0 + (c >> 6));
  1852. buf[1] = (char)(0x80 + (c & 0x3f));
  1853. return 2;
  1854. }
  1855. if (c < 0x10000)
  1856. {
  1857. if (buf_size < 3) return 0;
  1858. buf[0] = (char)(0xe0 + (c >> 12));
  1859. buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
  1860. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1861. return 3;
  1862. }
  1863. if (c <= 0x10FFFF)
  1864. {
  1865. if (buf_size < 4) return 0;
  1866. buf[0] = (char)(0xf0 + (c >> 18));
  1867. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1868. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1869. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1870. return 4;
  1871. }
  1872. // Invalid code point, the max unicode is 0x10FFFF
  1873. return 0;
  1874. }
  1875. const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
  1876. {
  1877. int count = ImTextCharToUtf8_inline(out_buf, 5, c);
  1878. out_buf[count] = 0;
  1879. return out_buf;
  1880. }
  1881. // Not optimal but we very rarely use this function.
  1882. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
  1883. {
  1884. unsigned int unused = 0;
  1885. return ImTextCharFromUtf8(&unused, in_text, in_text_end);
  1886. }
  1887. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1888. {
  1889. if (c < 0x80) return 1;
  1890. if (c < 0x800) return 2;
  1891. if (c < 0x10000) return 3;
  1892. if (c <= 0x10FFFF) return 4;
  1893. return 3;
  1894. }
  1895. int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1896. {
  1897. char* buf_p = out_buf;
  1898. const char* buf_end = out_buf + out_buf_size;
  1899. while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1900. {
  1901. unsigned int c = (unsigned int)(*in_text++);
  1902. if (c < 0x80)
  1903. *buf_p++ = (char)c;
  1904. else
  1905. buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
  1906. }
  1907. *buf_p = 0;
  1908. return (int)(buf_p - out_buf);
  1909. }
  1910. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1911. {
  1912. int bytes_count = 0;
  1913. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1914. {
  1915. unsigned int c = (unsigned int)(*in_text++);
  1916. if (c < 0x80)
  1917. bytes_count++;
  1918. else
  1919. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1920. }
  1921. return bytes_count;
  1922. }
  1923. //-----------------------------------------------------------------------------
  1924. // [SECTION] MISC HELPERS/UTILITIES (Color functions)
  1925. // Note: The Convert functions are early design which are not consistent with other API.
  1926. //-----------------------------------------------------------------------------
  1927. IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
  1928. {
  1929. float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
  1930. int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
  1931. int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
  1932. int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
  1933. return IM_COL32(r, g, b, 0xFF);
  1934. }
  1935. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1936. {
  1937. float s = 1.0f / 255.0f;
  1938. return ImVec4(
  1939. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1940. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1941. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1942. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1943. }
  1944. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1945. {
  1946. ImU32 out;
  1947. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1948. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1949. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1950. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1951. return out;
  1952. }
  1953. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1954. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1955. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1956. {
  1957. float K = 0.f;
  1958. if (g < b)
  1959. {
  1960. ImSwap(g, b);
  1961. K = -1.f;
  1962. }
  1963. if (r < g)
  1964. {
  1965. ImSwap(r, g);
  1966. K = -2.f / 6.f - K;
  1967. }
  1968. const float chroma = r - (g < b ? g : b);
  1969. out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
  1970. out_s = chroma / (r + 1e-20f);
  1971. out_v = r;
  1972. }
  1973. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1974. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1975. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1976. {
  1977. if (s == 0.0f)
  1978. {
  1979. // gray
  1980. out_r = out_g = out_b = v;
  1981. return;
  1982. }
  1983. h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
  1984. int i = (int)h;
  1985. float f = h - (float)i;
  1986. float p = v * (1.0f - s);
  1987. float q = v * (1.0f - s * f);
  1988. float t = v * (1.0f - s * (1.0f - f));
  1989. switch (i)
  1990. {
  1991. case 0: out_r = v; out_g = t; out_b = p; break;
  1992. case 1: out_r = q; out_g = v; out_b = p; break;
  1993. case 2: out_r = p; out_g = v; out_b = t; break;
  1994. case 3: out_r = p; out_g = q; out_b = v; break;
  1995. case 4: out_r = t; out_g = p; out_b = v; break;
  1996. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1997. }
  1998. }
  1999. //-----------------------------------------------------------------------------
  2000. // [SECTION] ImGuiStorage
  2001. // Helper: Key->value storage
  2002. //-----------------------------------------------------------------------------
  2003. // std::lower_bound but without the bullshit
  2004. static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
  2005. {
  2006. ImGuiStorage::ImGuiStoragePair* first = data.Data;
  2007. ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
  2008. size_t count = (size_t)(last - first);
  2009. while (count > 0)
  2010. {
  2011. size_t count2 = count >> 1;
  2012. ImGuiStorage::ImGuiStoragePair* mid = first + count2;
  2013. if (mid->key < key)
  2014. {
  2015. first = ++mid;
  2016. count -= count2 + 1;
  2017. }
  2018. else
  2019. {
  2020. count = count2;
  2021. }
  2022. }
  2023. return first;
  2024. }
  2025. // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
  2026. void ImGuiStorage::BuildSortByKey()
  2027. {
  2028. struct StaticFunc
  2029. {
  2030. static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
  2031. {
  2032. // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
  2033. if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
  2034. if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
  2035. return 0;
  2036. }
  2037. };
  2038. ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
  2039. }
  2040. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  2041. {
  2042. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  2043. if (it == Data.end() || it->key != key)
  2044. return default_val;
  2045. return it->val_i;
  2046. }
  2047. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  2048. {
  2049. return GetInt(key, default_val ? 1 : 0) != 0;
  2050. }
  2051. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  2052. {
  2053. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  2054. if (it == Data.end() || it->key != key)
  2055. return default_val;
  2056. return it->val_f;
  2057. }
  2058. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  2059. {
  2060. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  2061. if (it == Data.end() || it->key != key)
  2062. return NULL;
  2063. return it->val_p;
  2064. }
  2065. // 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.
  2066. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  2067. {
  2068. ImGuiStoragePair* it = LowerBound(Data, key);
  2069. if (it == Data.end() || it->key != key)
  2070. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  2071. return &it->val_i;
  2072. }
  2073. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  2074. {
  2075. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  2076. }
  2077. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  2078. {
  2079. ImGuiStoragePair* it = LowerBound(Data, key);
  2080. if (it == Data.end() || it->key != key)
  2081. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  2082. return &it->val_f;
  2083. }
  2084. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  2085. {
  2086. ImGuiStoragePair* it = LowerBound(Data, key);
  2087. if (it == Data.end() || it->key != key)
  2088. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  2089. return &it->val_p;
  2090. }
  2091. // 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)
  2092. void ImGuiStorage::SetInt(ImGuiID key, int val)
  2093. {
  2094. ImGuiStoragePair* it = LowerBound(Data, key);
  2095. if (it == Data.end() || it->key != key)
  2096. {
  2097. Data.insert(it, ImGuiStoragePair(key, val));
  2098. return;
  2099. }
  2100. it->val_i = val;
  2101. }
  2102. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  2103. {
  2104. SetInt(key, val ? 1 : 0);
  2105. }
  2106. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  2107. {
  2108. ImGuiStoragePair* it = LowerBound(Data, key);
  2109. if (it == Data.end() || it->key != key)
  2110. {
  2111. Data.insert(it, ImGuiStoragePair(key, val));
  2112. return;
  2113. }
  2114. it->val_f = val;
  2115. }
  2116. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  2117. {
  2118. ImGuiStoragePair* it = LowerBound(Data, key);
  2119. if (it == Data.end() || it->key != key)
  2120. {
  2121. Data.insert(it, ImGuiStoragePair(key, val));
  2122. return;
  2123. }
  2124. it->val_p = val;
  2125. }
  2126. void ImGuiStorage::SetAllInt(int v)
  2127. {
  2128. for (int i = 0; i < Data.Size; i++)
  2129. Data[i].val_i = v;
  2130. }
  2131. //-----------------------------------------------------------------------------
  2132. // [SECTION] ImGuiTextFilter
  2133. //-----------------------------------------------------------------------------
  2134. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  2135. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
  2136. {
  2137. InputBuf[0] = 0;
  2138. CountGrep = 0;
  2139. if (default_filter)
  2140. {
  2141. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  2142. Build();
  2143. }
  2144. }
  2145. bool ImGuiTextFilter::Draw(const char* label, float width)
  2146. {
  2147. if (width != 0.0f)
  2148. ImGui::SetNextItemWidth(width);
  2149. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  2150. if (value_changed)
  2151. Build();
  2152. return value_changed;
  2153. }
  2154. void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
  2155. {
  2156. out->resize(0);
  2157. const char* wb = b;
  2158. const char* we = wb;
  2159. while (we < e)
  2160. {
  2161. if (*we == separator)
  2162. {
  2163. out->push_back(ImGuiTextRange(wb, we));
  2164. wb = we + 1;
  2165. }
  2166. we++;
  2167. }
  2168. if (wb != we)
  2169. out->push_back(ImGuiTextRange(wb, we));
  2170. }
  2171. void ImGuiTextFilter::Build()
  2172. {
  2173. Filters.resize(0);
  2174. ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
  2175. input_range.split(',', &Filters);
  2176. CountGrep = 0;
  2177. for (int i = 0; i != Filters.Size; i++)
  2178. {
  2179. ImGuiTextRange& f = Filters[i];
  2180. while (f.b < f.e && ImCharIsBlankA(f.b[0]))
  2181. f.b++;
  2182. while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
  2183. f.e--;
  2184. if (f.empty())
  2185. continue;
  2186. if (Filters[i].b[0] != '-')
  2187. CountGrep += 1;
  2188. }
  2189. }
  2190. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  2191. {
  2192. if (Filters.empty())
  2193. return true;
  2194. if (text == NULL)
  2195. text = "";
  2196. for (int i = 0; i != Filters.Size; i++)
  2197. {
  2198. const ImGuiTextRange& f = Filters[i];
  2199. if (f.empty())
  2200. continue;
  2201. if (f.b[0] == '-')
  2202. {
  2203. // Subtract
  2204. if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
  2205. return false;
  2206. }
  2207. else
  2208. {
  2209. // Grep
  2210. if (ImStristr(text, text_end, f.b, f.e) != NULL)
  2211. return true;
  2212. }
  2213. }
  2214. // Implicit * grep
  2215. if (CountGrep == 0)
  2216. return true;
  2217. return false;
  2218. }
  2219. //-----------------------------------------------------------------------------
  2220. // [SECTION] ImGuiTextBuffer
  2221. //-----------------------------------------------------------------------------
  2222. // On some platform vsnprintf() takes va_list by reference and modifies it.
  2223. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  2224. #ifndef va_copy
  2225. #if defined(__GNUC__) || defined(__clang__)
  2226. #define va_copy(dest, src) __builtin_va_copy(dest, src)
  2227. #else
  2228. #define va_copy(dest, src) (dest = src)
  2229. #endif
  2230. #endif
  2231. char ImGuiTextBuffer::EmptyString[1] = { 0 };
  2232. void ImGuiTextBuffer::append(const char* str, const char* str_end)
  2233. {
  2234. int len = str_end ? (int)(str_end - str) : (int)strlen(str);
  2235. // Add zero-terminator the first time
  2236. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  2237. const int needed_sz = write_off + len;
  2238. if (write_off + len >= Buf.Capacity)
  2239. {
  2240. int new_capacity = Buf.Capacity * 2;
  2241. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  2242. }
  2243. Buf.resize(needed_sz);
  2244. memcpy(&Buf[write_off - 1], str, (size_t)len);
  2245. Buf[write_off - 1 + len] = 0;
  2246. }
  2247. void ImGuiTextBuffer::appendf(const char* fmt, ...)
  2248. {
  2249. va_list args;
  2250. va_start(args, fmt);
  2251. appendfv(fmt, args);
  2252. va_end(args);
  2253. }
  2254. // Helper: Text buffer for logging/accumulating text
  2255. void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
  2256. {
  2257. va_list args_copy;
  2258. va_copy(args_copy, args);
  2259. int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  2260. if (len <= 0)
  2261. {
  2262. va_end(args_copy);
  2263. return;
  2264. }
  2265. // Add zero-terminator the first time
  2266. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  2267. const int needed_sz = write_off + len;
  2268. if (write_off + len >= Buf.Capacity)
  2269. {
  2270. int new_capacity = Buf.Capacity * 2;
  2271. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  2272. }
  2273. Buf.resize(needed_sz);
  2274. ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
  2275. va_end(args_copy);
  2276. }
  2277. //-----------------------------------------------------------------------------
  2278. // [SECTION] ImGuiListClipper
  2279. // This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
  2280. // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
  2281. //-----------------------------------------------------------------------------
  2282. // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
  2283. // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
  2284. static bool GetSkipItemForListClipping()
  2285. {
  2286. ImGuiContext& g = *GImGui;
  2287. return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
  2288. }
  2289. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  2290. // Legacy helper to calculate coarse clipping of large list of evenly sized items.
  2291. // This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
  2292. // Prefer using ImGuiListClipper which can returns non-contiguous ranges.
  2293. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  2294. {
  2295. ImGuiContext& g = *GImGui;
  2296. ImGuiWindow* window = g.CurrentWindow;
  2297. if (g.LogEnabled)
  2298. {
  2299. // If logging is active, do not perform any clipping
  2300. *out_items_display_start = 0;
  2301. *out_items_display_end = items_count;
  2302. return;
  2303. }
  2304. if (GetSkipItemForListClipping())
  2305. {
  2306. *out_items_display_start = *out_items_display_end = 0;
  2307. return;
  2308. }
  2309. // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
  2310. // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
  2311. ImRect rect = window->ClipRect;
  2312. if (g.NavMoveScoringItems)
  2313. rect.Add(g.NavScoringNoClipRect);
  2314. if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
  2315. rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
  2316. const ImVec2 pos = window->DC.CursorPos;
  2317. int start = (int)((rect.Min.y - pos.y) / items_height);
  2318. int end = (int)((rect.Max.y - pos.y) / items_height);
  2319. // When performing a navigation request, ensure we have one item extra in the direction we are moving to
  2320. // FIXME: Verify this works with tabbing
  2321. const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
  2322. if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
  2323. start--;
  2324. if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
  2325. end++;
  2326. start = ImClamp(start, 0, items_count);
  2327. end = ImClamp(end + 1, start, items_count);
  2328. *out_items_display_start = start;
  2329. *out_items_display_end = end;
  2330. }
  2331. #endif
  2332. static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
  2333. {
  2334. if (ranges.Size - offset <= 1)
  2335. return;
  2336. // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
  2337. for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
  2338. for (int i = offset; i < sort_end + offset; ++i)
  2339. if (ranges[i].Min > ranges[i + 1].Min)
  2340. ImSwap(ranges[i], ranges[i + 1]);
  2341. // Now fuse ranges together as much as possible.
  2342. for (int i = 1 + offset; i < ranges.Size; i++)
  2343. {
  2344. IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
  2345. if (ranges[i - 1].Max < ranges[i].Min)
  2346. continue;
  2347. ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
  2348. ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
  2349. ranges.erase(ranges.Data + i);
  2350. i--;
  2351. }
  2352. }
  2353. static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
  2354. {
  2355. // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
  2356. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
  2357. // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
  2358. ImGuiContext& g = *GImGui;
  2359. ImGuiWindow* window = g.CurrentWindow;
  2360. float off_y = pos_y - window->DC.CursorPos.y;
  2361. window->DC.CursorPos.y = pos_y;
  2362. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
  2363. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
  2364. window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
  2365. if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
  2366. columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  2367. if (ImGuiTable* table = g.CurrentTable)
  2368. {
  2369. if (table->IsInsideRow)
  2370. ImGui::TableEndRow(table);
  2371. table->RowPosY2 = window->DC.CursorPos.y;
  2372. const int row_increase = (int)((off_y / line_height) + 0.5f);
  2373. //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
  2374. table->RowBgColorCounter += row_increase;
  2375. }
  2376. }
  2377. static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
  2378. {
  2379. // StartPosY starts from ItemsFrozen hence the subtraction
  2380. // Perform the add and multiply with double to allow seeking through larger ranges
  2381. ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
  2382. float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
  2383. ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
  2384. }
  2385. ImGuiListClipper::ImGuiListClipper()
  2386. {
  2387. memset(this, 0, sizeof(*this));
  2388. ItemsCount = -1;
  2389. }
  2390. ImGuiListClipper::~ImGuiListClipper()
  2391. {
  2392. End();
  2393. }
  2394. void ImGuiListClipper::Begin(int items_count, float items_height)
  2395. {
  2396. ImGuiContext& g = *GImGui;
  2397. ImGuiWindow* window = g.CurrentWindow;
  2398. IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
  2399. if (ImGuiTable* table = g.CurrentTable)
  2400. if (table->IsInsideRow)
  2401. ImGui::TableEndRow(table);
  2402. StartPosY = window->DC.CursorPos.y;
  2403. ItemsHeight = items_height;
  2404. ItemsCount = items_count;
  2405. DisplayStart = -1;
  2406. DisplayEnd = 0;
  2407. // Acquire temporary buffer
  2408. if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
  2409. g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
  2410. ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
  2411. data->Reset(this);
  2412. data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
  2413. TempData = data;
  2414. }
  2415. void ImGuiListClipper::End()
  2416. {
  2417. ImGuiContext& g = *GImGui;
  2418. if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
  2419. {
  2420. // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
  2421. IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
  2422. if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
  2423. ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
  2424. // Restore temporary buffer and fix back pointers which may be invalidated when nesting
  2425. IM_ASSERT(data->ListClipper == this);
  2426. data->StepNo = data->Ranges.Size;
  2427. if (--g.ClipperTempDataStacked > 0)
  2428. {
  2429. data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
  2430. data->ListClipper->TempData = data;
  2431. }
  2432. TempData = NULL;
  2433. }
  2434. ItemsCount = -1;
  2435. }
  2436. void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
  2437. {
  2438. ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
  2439. IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
  2440. IM_ASSERT(item_min <= item_max);
  2441. if (item_min < item_max)
  2442. data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
  2443. }
  2444. static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
  2445. {
  2446. ImGuiContext& g = *GImGui;
  2447. ImGuiWindow* window = g.CurrentWindow;
  2448. ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
  2449. IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
  2450. ImGuiTable* table = g.CurrentTable;
  2451. if (table && table->IsInsideRow)
  2452. ImGui::TableEndRow(table);
  2453. // No items
  2454. if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
  2455. return false;
  2456. // While we are in frozen row state, keep displaying items one by one, unclipped
  2457. // FIXME: Could be stored as a table-agnostic state.
  2458. if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
  2459. {
  2460. clipper->DisplayStart = data->ItemsFrozen;
  2461. clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
  2462. if (clipper->DisplayStart < clipper->DisplayEnd)
  2463. data->ItemsFrozen++;
  2464. return true;
  2465. }
  2466. // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
  2467. bool calc_clipping = false;
  2468. if (data->StepNo == 0)
  2469. {
  2470. clipper->StartPosY = window->DC.CursorPos.y;
  2471. if (clipper->ItemsHeight <= 0.0f)
  2472. {
  2473. // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
  2474. data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
  2475. clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
  2476. clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
  2477. data->StepNo = 1;
  2478. return true;
  2479. }
  2480. calc_clipping = true; // If on the first step with known item height, calculate clipping.
  2481. }
  2482. // Step 1: Let the clipper infer height from first range
  2483. if (clipper->ItemsHeight <= 0.0f)
  2484. {
  2485. IM_ASSERT(data->StepNo == 1);
  2486. if (table)
  2487. IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
  2488. clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
  2489. bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
  2490. if (affected_by_floating_point_precision)
  2491. clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
  2492. IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
  2493. calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
  2494. }
  2495. // Step 0 or 1: Calculate the actual ranges of visible elements.
  2496. const int already_submitted = clipper->DisplayEnd;
  2497. if (calc_clipping)
  2498. {
  2499. if (g.LogEnabled)
  2500. {
  2501. // If logging is active, do not perform any clipping
  2502. data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
  2503. }
  2504. else
  2505. {
  2506. // Add range selected to be included for navigation
  2507. const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
  2508. if (is_nav_request)
  2509. data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
  2510. if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
  2511. data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
  2512. // Add focused/active item
  2513. ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
  2514. if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
  2515. data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
  2516. // Add visible range
  2517. const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
  2518. const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
  2519. data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
  2520. }
  2521. // Convert position ranges to item index ranges
  2522. // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
  2523. // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
  2524. // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
  2525. for (int i = 0; i < data->Ranges.Size; i++)
  2526. if (data->Ranges[i].PosToIndexConvert)
  2527. {
  2528. int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
  2529. int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
  2530. data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
  2531. data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
  2532. data->Ranges[i].PosToIndexConvert = false;
  2533. }
  2534. ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
  2535. }
  2536. // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
  2537. if (data->StepNo < data->Ranges.Size)
  2538. {
  2539. clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
  2540. clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
  2541. if (clipper->DisplayStart > already_submitted) //-V1051
  2542. ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
  2543. data->StepNo++;
  2544. return true;
  2545. }
  2546. // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
  2547. // Advance the cursor to the end of the list and then returns 'false' to end the loop.
  2548. if (clipper->ItemsCount < INT_MAX)
  2549. ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
  2550. return false;
  2551. }
  2552. bool ImGuiListClipper::Step()
  2553. {
  2554. ImGuiContext& g = *GImGui;
  2555. bool need_items_height = (ItemsHeight <= 0.0f);
  2556. bool ret = ImGuiListClipper_StepInternal(this);
  2557. if (ret && (DisplayStart == DisplayEnd))
  2558. ret = false;
  2559. if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
  2560. IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
  2561. if (need_items_height && ItemsHeight > 0.0f)
  2562. IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
  2563. if (ret)
  2564. IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
  2565. else
  2566. IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
  2567. if (!ret)
  2568. End();
  2569. return ret;
  2570. }
  2571. //-----------------------------------------------------------------------------
  2572. // [SECTION] STYLING
  2573. //-----------------------------------------------------------------------------
  2574. ImGuiStyle& ImGui::GetStyle()
  2575. {
  2576. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  2577. return GImGui->Style;
  2578. }
  2579. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  2580. {
  2581. ImGuiStyle& style = GImGui->Style;
  2582. ImVec4 c = style.Colors[idx];
  2583. c.w *= style.Alpha * alpha_mul;
  2584. return ColorConvertFloat4ToU32(c);
  2585. }
  2586. ImU32 ImGui::GetColorU32(const ImVec4& col)
  2587. {
  2588. ImGuiStyle& style = GImGui->Style;
  2589. ImVec4 c = col;
  2590. c.w *= style.Alpha;
  2591. return ColorConvertFloat4ToU32(c);
  2592. }
  2593. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  2594. {
  2595. ImGuiStyle& style = GImGui->Style;
  2596. return style.Colors[idx];
  2597. }
  2598. ImU32 ImGui::GetColorU32(ImU32 col)
  2599. {
  2600. ImGuiStyle& style = GImGui->Style;
  2601. if (style.Alpha >= 1.0f)
  2602. return col;
  2603. ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  2604. a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  2605. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  2606. }
  2607. // 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
  2608. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  2609. {
  2610. ImGuiContext& g = *GImGui;
  2611. ImGuiColorMod backup;
  2612. backup.Col = idx;
  2613. backup.BackupValue = g.Style.Colors[idx];
  2614. g.ColorStack.push_back(backup);
  2615. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  2616. }
  2617. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  2618. {
  2619. ImGuiContext& g = *GImGui;
  2620. ImGuiColorMod backup;
  2621. backup.Col = idx;
  2622. backup.BackupValue = g.Style.Colors[idx];
  2623. g.ColorStack.push_back(backup);
  2624. g.Style.Colors[idx] = col;
  2625. }
  2626. void ImGui::PopStyleColor(int count)
  2627. {
  2628. ImGuiContext& g = *GImGui;
  2629. if (g.ColorStack.Size < count)
  2630. {
  2631. IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
  2632. count = g.ColorStack.Size;
  2633. }
  2634. while (count > 0)
  2635. {
  2636. ImGuiColorMod& backup = g.ColorStack.back();
  2637. g.Style.Colors[backup.Col] = backup.BackupValue;
  2638. g.ColorStack.pop_back();
  2639. count--;
  2640. }
  2641. }
  2642. struct ImGuiStyleVarInfo
  2643. {
  2644. ImGuiDataType Type;
  2645. ImU32 Count;
  2646. ImU32 Offset;
  2647. void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  2648. };
  2649. static const ImGuiStyleVarInfo GStyleVarInfo[] =
  2650. {
  2651. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  2652. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
  2653. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  2654. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  2655. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
  2656. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  2657. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
  2658. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
  2659. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
  2660. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
  2661. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
  2662. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  2663. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  2664. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
  2665. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  2666. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  2667. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  2668. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
  2669. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
  2670. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
  2671. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  2672. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
  2673. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
  2674. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  2675. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
  2676. };
  2677. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  2678. {
  2679. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
  2680. IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
  2681. return &GStyleVarInfo[idx];
  2682. }
  2683. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  2684. {
  2685. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2686. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
  2687. {
  2688. ImGuiContext& g = *GImGui;
  2689. float* pvar = (float*)var_info->GetVarPtr(&g.Style);
  2690. g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
  2691. *pvar = val;
  2692. return;
  2693. }
  2694. IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
  2695. }
  2696. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  2697. {
  2698. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2699. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
  2700. {
  2701. ImGuiContext& g = *GImGui;
  2702. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
  2703. g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
  2704. *pvar = val;
  2705. return;
  2706. }
  2707. IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
  2708. }
  2709. void ImGui::PopStyleVar(int count)
  2710. {
  2711. ImGuiContext& g = *GImGui;
  2712. if (g.StyleVarStack.Size < count)
  2713. {
  2714. IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
  2715. count = g.StyleVarStack.Size;
  2716. }
  2717. while (count > 0)
  2718. {
  2719. // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
  2720. ImGuiStyleMod& backup = g.StyleVarStack.back();
  2721. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  2722. void* data = info->GetVarPtr(&g.Style);
  2723. if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
  2724. else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
  2725. g.StyleVarStack.pop_back();
  2726. count--;
  2727. }
  2728. }
  2729. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  2730. {
  2731. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  2732. switch (idx)
  2733. {
  2734. case ImGuiCol_Text: return "Text";
  2735. case ImGuiCol_TextDisabled: return "TextDisabled";
  2736. case ImGuiCol_WindowBg: return "WindowBg";
  2737. case ImGuiCol_ChildBg: return "ChildBg";
  2738. case ImGuiCol_PopupBg: return "PopupBg";
  2739. case ImGuiCol_Border: return "Border";
  2740. case ImGuiCol_BorderShadow: return "BorderShadow";
  2741. case ImGuiCol_FrameBg: return "FrameBg";
  2742. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  2743. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  2744. case ImGuiCol_TitleBg: return "TitleBg";
  2745. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  2746. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  2747. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  2748. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  2749. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  2750. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  2751. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  2752. case ImGuiCol_CheckMark: return "CheckMark";
  2753. case ImGuiCol_SliderGrab: return "SliderGrab";
  2754. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  2755. case ImGuiCol_Button: return "Button";
  2756. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  2757. case ImGuiCol_ButtonActive: return "ButtonActive";
  2758. case ImGuiCol_Header: return "Header";
  2759. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  2760. case ImGuiCol_HeaderActive: return "HeaderActive";
  2761. case ImGuiCol_Separator: return "Separator";
  2762. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  2763. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  2764. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  2765. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  2766. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  2767. case ImGuiCol_Tab: return "Tab";
  2768. case ImGuiCol_TabHovered: return "TabHovered";
  2769. case ImGuiCol_TabActive: return "TabActive";
  2770. case ImGuiCol_TabUnfocused: return "TabUnfocused";
  2771. case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
  2772. case ImGuiCol_PlotLines: return "PlotLines";
  2773. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  2774. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  2775. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  2776. case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
  2777. case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
  2778. case ImGuiCol_TableBorderLight: return "TableBorderLight";
  2779. case ImGuiCol_TableRowBg: return "TableRowBg";
  2780. case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
  2781. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  2782. case ImGuiCol_DragDropTarget: return "DragDropTarget";
  2783. case ImGuiCol_NavHighlight: return "NavHighlight";
  2784. case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
  2785. case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
  2786. case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
  2787. }
  2788. IM_ASSERT(0);
  2789. return "Unknown";
  2790. }
  2791. //-----------------------------------------------------------------------------
  2792. // [SECTION] RENDER HELPERS
  2793. // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
  2794. // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
  2795. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
  2796. //-----------------------------------------------------------------------------
  2797. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  2798. {
  2799. const char* text_display_end = text;
  2800. if (!text_end)
  2801. text_end = (const char*)-1;
  2802. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2803. text_display_end++;
  2804. return text_display_end;
  2805. }
  2806. // Internal ImGui functions to render text
  2807. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  2808. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  2809. {
  2810. ImGuiContext& g = *GImGui;
  2811. ImGuiWindow* window = g.CurrentWindow;
  2812. // Hide anything after a '##' string
  2813. const char* text_display_end;
  2814. if (hide_text_after_hash)
  2815. {
  2816. text_display_end = FindRenderedTextEnd(text, text_end);
  2817. }
  2818. else
  2819. {
  2820. if (!text_end)
  2821. text_end = text + strlen(text); // FIXME-OPT
  2822. text_display_end = text_end;
  2823. }
  2824. if (text != text_display_end)
  2825. {
  2826. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  2827. if (g.LogEnabled)
  2828. LogRenderedText(&pos, text, text_display_end);
  2829. }
  2830. }
  2831. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  2832. {
  2833. ImGuiContext& g = *GImGui;
  2834. ImGuiWindow* window = g.CurrentWindow;
  2835. if (!text_end)
  2836. text_end = text + strlen(text); // FIXME-OPT
  2837. if (text != text_end)
  2838. {
  2839. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  2840. if (g.LogEnabled)
  2841. LogRenderedText(&pos, text, text_end);
  2842. }
  2843. }
  2844. // Default clip_rect uses (pos_min,pos_max)
  2845. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  2846. void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
  2847. {
  2848. // Perform CPU side clipping for single clipped element to avoid using scissor state
  2849. ImVec2 pos = pos_min;
  2850. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  2851. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  2852. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  2853. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  2854. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  2855. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  2856. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  2857. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  2858. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  2859. // Render
  2860. if (need_clipping)
  2861. {
  2862. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  2863. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  2864. }
  2865. else
  2866. {
  2867. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2868. }
  2869. }
  2870. 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)
  2871. {
  2872. // Hide anything after a '##' string
  2873. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  2874. const int text_len = (int)(text_display_end - text);
  2875. if (text_len == 0)
  2876. return;
  2877. ImGuiContext& g = *GImGui;
  2878. ImGuiWindow* window = g.CurrentWindow;
  2879. RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
  2880. if (g.LogEnabled)
  2881. LogRenderedText(&pos_min, text, text_display_end);
  2882. }
  2883. // Another overly complex function until we reorganize everything into a nice all-in-one helper.
  2884. // This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
  2885. // This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
  2886. void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
  2887. {
  2888. ImGuiContext& g = *GImGui;
  2889. if (text_end_full == NULL)
  2890. text_end_full = FindRenderedTextEnd(text);
  2891. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
  2892. //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
  2893. //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
  2894. //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
  2895. // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
  2896. if (text_size.x > pos_max.x - pos_min.x)
  2897. {
  2898. // Hello wo...
  2899. // | | |
  2900. // min max ellipsis_max
  2901. // <-> this is generally some padding value
  2902. const ImFont* font = draw_list->_Data->Font;
  2903. const float font_size = draw_list->_Data->FontSize;
  2904. const char* text_end_ellipsis = NULL;
  2905. ImWchar ellipsis_char = font->EllipsisChar;
  2906. int ellipsis_char_count = 1;
  2907. if (ellipsis_char == (ImWchar)-1)
  2908. {
  2909. ellipsis_char = font->DotChar;
  2910. ellipsis_char_count = 3;
  2911. }
  2912. const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
  2913. float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
  2914. float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
  2915. if (ellipsis_char_count > 1)
  2916. {
  2917. // Full ellipsis size without free spacing after it.
  2918. const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
  2919. ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
  2920. ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
  2921. }
  2922. // We can now claim the space between pos_max.x and ellipsis_max.x
  2923. const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
  2924. float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
  2925. if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
  2926. {
  2927. // Always display at least 1 character if there's no room for character + ellipsis
  2928. text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
  2929. text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
  2930. }
  2931. while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
  2932. {
  2933. // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
  2934. text_end_ellipsis--;
  2935. text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
  2936. }
  2937. // Render text, render ellipsis
  2938. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
  2939. float ellipsis_x = pos_min.x + text_size_clipped_x;
  2940. if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
  2941. for (int i = 0; i < ellipsis_char_count; i++)
  2942. {
  2943. font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
  2944. ellipsis_x += ellipsis_glyph_width;
  2945. }
  2946. }
  2947. else
  2948. {
  2949. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
  2950. }
  2951. if (g.LogEnabled)
  2952. LogRenderedText(&pos_min, text, text_end_full);
  2953. }
  2954. // Render a rectangle shaped with optional rounding and borders
  2955. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2956. {
  2957. ImGuiContext& g = *GImGui;
  2958. ImGuiWindow* window = g.CurrentWindow;
  2959. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2960. const float border_size = g.Style.FrameBorderSize;
  2961. if (border && border_size > 0.0f)
  2962. {
  2963. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
  2964. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  2965. }
  2966. }
  2967. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  2968. {
  2969. ImGuiContext& g = *GImGui;
  2970. ImGuiWindow* window = g.CurrentWindow;
  2971. const float border_size = g.Style.FrameBorderSize;
  2972. if (border_size > 0.0f)
  2973. {
  2974. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
  2975. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  2976. }
  2977. }
  2978. void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
  2979. {
  2980. ImGuiContext& g = *GImGui;
  2981. if (id != g.NavId)
  2982. return;
  2983. if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
  2984. return;
  2985. ImGuiWindow* window = g.CurrentWindow;
  2986. if (window->DC.NavHideHighlightOneFrame)
  2987. return;
  2988. float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
  2989. ImRect display_rect = bb;
  2990. display_rect.ClipWith(window->ClipRect);
  2991. if (flags & ImGuiNavHighlightFlags_TypeDefault)
  2992. {
  2993. const float THICKNESS = 2.0f;
  2994. const float DISTANCE = 3.0f + THICKNESS * 0.5f;
  2995. display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
  2996. bool fully_visible = window->ClipRect.Contains(display_rect);
  2997. if (!fully_visible)
  2998. window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
  2999. window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
  3000. if (!fully_visible)
  3001. window->DrawList->PopClipRect();
  3002. }
  3003. if (flags & ImGuiNavHighlightFlags_TypeThin)
  3004. {
  3005. window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
  3006. }
  3007. }
  3008. void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
  3009. {
  3010. ImGuiContext& g = *GImGui;
  3011. IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
  3012. for (int n = 0; n < g.Viewports.Size; n++)
  3013. {
  3014. ImGuiViewportP* viewport = g.Viewports[n];
  3015. ImDrawList* draw_list = GetForegroundDrawList(viewport);
  3016. ImFontAtlas* font_atlas = draw_list->_Data->Font->ContainerAtlas;
  3017. ImVec2 offset, size, uv[4];
  3018. if (font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
  3019. {
  3020. const ImVec2 pos = base_pos - offset;
  3021. const float scale = base_scale;
  3022. ImTextureID tex_id = font_atlas->TexID;
  3023. draw_list->PushTextureID(tex_id);
  3024. draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
  3025. draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
  3026. draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border);
  3027. draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill);
  3028. draw_list->PopTextureID();
  3029. }
  3030. }
  3031. }
  3032. //-----------------------------------------------------------------------------
  3033. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  3034. //-----------------------------------------------------------------------------
  3035. // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
  3036. ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
  3037. {
  3038. memset(this, 0, sizeof(*this));
  3039. Name = ImStrdup(name);
  3040. NameBufLen = (int)strlen(name) + 1;
  3041. ID = ImHashStr(name);
  3042. IDStack.push_back(ID);
  3043. MoveId = GetID("#MOVE");
  3044. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  3045. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  3046. AutoFitFramesX = AutoFitFramesY = -1;
  3047. AutoPosLastDirection = ImGuiDir_None;
  3048. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  3049. SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
  3050. LastFrameActive = -1;
  3051. LastTimeActive = -1.0f;
  3052. FontWindowScale = 1.0f;
  3053. SettingsOffset = -1;
  3054. DrawList = &DrawListInst;
  3055. DrawList->_Data = &context->DrawListSharedData;
  3056. DrawList->_OwnerName = Name;
  3057. }
  3058. ImGuiWindow::~ImGuiWindow()
  3059. {
  3060. IM_ASSERT(DrawList == &DrawListInst);
  3061. IM_DELETE(Name);
  3062. ColumnsStorage.clear_destruct();
  3063. }
  3064. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  3065. {
  3066. ImGuiID seed = IDStack.back();
  3067. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  3068. ImGuiContext& g = *GImGui;
  3069. if (g.DebugHookIdInfo == id)
  3070. ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
  3071. return id;
  3072. }
  3073. ImGuiID ImGuiWindow::GetID(const void* ptr)
  3074. {
  3075. ImGuiID seed = IDStack.back();
  3076. ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
  3077. ImGuiContext& g = *GImGui;
  3078. if (g.DebugHookIdInfo == id)
  3079. ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
  3080. return id;
  3081. }
  3082. ImGuiID ImGuiWindow::GetID(int n)
  3083. {
  3084. ImGuiID seed = IDStack.back();
  3085. ImGuiID id = ImHashData(&n, sizeof(n), seed);
  3086. ImGuiContext& g = *GImGui;
  3087. if (g.DebugHookIdInfo == id)
  3088. ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
  3089. return id;
  3090. }
  3091. // This is only used in rare/specific situations to manufacture an ID out of nowhere.
  3092. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
  3093. {
  3094. ImGuiID seed = IDStack.back();
  3095. ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
  3096. ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
  3097. return id;
  3098. }
  3099. static void SetCurrentWindow(ImGuiWindow* window)
  3100. {
  3101. ImGuiContext& g = *GImGui;
  3102. g.CurrentWindow = window;
  3103. g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
  3104. if (window)
  3105. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  3106. }
  3107. void ImGui::GcCompactTransientMiscBuffers()
  3108. {
  3109. ImGuiContext& g = *GImGui;
  3110. g.ItemFlagsStack.clear();
  3111. g.GroupStack.clear();
  3112. TableGcCompactSettings();
  3113. }
  3114. // Free up/compact internal window buffers, we can use this when a window becomes unused.
  3115. // Not freed:
  3116. // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
  3117. // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
  3118. void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
  3119. {
  3120. window->MemoryCompacted = true;
  3121. window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
  3122. window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
  3123. window->IDStack.clear();
  3124. window->DrawList->_ClearFreeMemory();
  3125. window->DC.ChildWindows.clear();
  3126. window->DC.ItemWidthStack.clear();
  3127. window->DC.TextWrapPosStack.clear();
  3128. }
  3129. void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
  3130. {
  3131. // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
  3132. // The other buffers tends to amortize much faster.
  3133. window->MemoryCompacted = false;
  3134. window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
  3135. window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
  3136. window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
  3137. }
  3138. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  3139. {
  3140. ImGuiContext& g = *GImGui;
  3141. // While most behaved code would make an effort to not steal active id during window move/drag operations,
  3142. // we at least need to be resilient to it. Cancelling the move is rather aggressive and users of 'master' branch
  3143. // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
  3144. if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
  3145. {
  3146. IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
  3147. g.MovingWindow = NULL;
  3148. }
  3149. // Set active id
  3150. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  3151. if (g.ActiveIdIsJustActivated)
  3152. {
  3153. IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
  3154. g.ActiveIdTimer = 0.0f;
  3155. g.ActiveIdHasBeenPressedBefore = false;
  3156. g.ActiveIdHasBeenEditedBefore = false;
  3157. g.ActiveIdMouseButton = -1;
  3158. if (id != 0)
  3159. {
  3160. g.LastActiveId = id;
  3161. g.LastActiveIdTimer = 0.0f;
  3162. }
  3163. }
  3164. g.ActiveId = id;
  3165. g.ActiveIdAllowOverlap = false;
  3166. g.ActiveIdNoClearOnFocusLoss = false;
  3167. g.ActiveIdWindow = window;
  3168. g.ActiveIdHasBeenEditedThisFrame = false;
  3169. if (id)
  3170. {
  3171. g.ActiveIdIsAlive = id;
  3172. g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? (ImGuiInputSource)ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
  3173. }
  3174. // Clear declaration of inputs claimed by the widget
  3175. // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
  3176. g.ActiveIdUsingNavDirMask = 0x00;
  3177. g.ActiveIdUsingKeyInputMask.ClearAllBits();
  3178. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  3179. g.ActiveIdUsingNavInputMask = 0x00;
  3180. #endif
  3181. }
  3182. void ImGui::ClearActiveID()
  3183. {
  3184. SetActiveID(0, NULL); // g.ActiveId = 0;
  3185. }
  3186. void ImGui::SetHoveredID(ImGuiID id)
  3187. {
  3188. ImGuiContext& g = *GImGui;
  3189. g.HoveredId = id;
  3190. g.HoveredIdAllowOverlap = false;
  3191. g.HoveredIdUsingMouseWheel = false;
  3192. if (id != 0 && g.HoveredIdPreviousFrame != id)
  3193. g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
  3194. }
  3195. ImGuiID ImGui::GetHoveredID()
  3196. {
  3197. ImGuiContext& g = *GImGui;
  3198. return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
  3199. }
  3200. // This is called by ItemAdd().
  3201. // Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
  3202. void ImGui::KeepAliveID(ImGuiID id)
  3203. {
  3204. ImGuiContext& g = *GImGui;
  3205. if (g.ActiveId == id)
  3206. g.ActiveIdIsAlive = id;
  3207. if (g.ActiveIdPreviousFrame == id)
  3208. g.ActiveIdPreviousFrameIsAlive = true;
  3209. }
  3210. void ImGui::MarkItemEdited(ImGuiID id)
  3211. {
  3212. // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
  3213. // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
  3214. ImGuiContext& g = *GImGui;
  3215. IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
  3216. IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
  3217. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
  3218. g.ActiveIdHasBeenEditedThisFrame = true;
  3219. g.ActiveIdHasBeenEditedBefore = true;
  3220. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
  3221. }
  3222. static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
  3223. {
  3224. // An active popup disable hovering on other windows (apart from its own children)
  3225. // FIXME-OPT: This could be cached/stored within the window.
  3226. ImGuiContext& g = *GImGui;
  3227. if (g.NavWindow)
  3228. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
  3229. if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
  3230. {
  3231. // For the purpose of those flags we differentiate "standard popup" from "modal popup"
  3232. // NB: The 'else' is important because Modal windows are also Popups.
  3233. bool want_inhibit = false;
  3234. if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
  3235. want_inhibit = true;
  3236. else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  3237. want_inhibit = true;
  3238. // Inhibit hover unless the window is within the stack of our modal/popup
  3239. if (want_inhibit)
  3240. if (!ImGui::IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
  3241. return false;
  3242. }
  3243. return true;
  3244. }
  3245. // This is roughly matching the behavior of internal-facing ItemHoverable()
  3246. // - 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()
  3247. // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
  3248. bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
  3249. {
  3250. ImGuiContext& g = *GImGui;
  3251. ImGuiWindow* window = g.CurrentWindow;
  3252. if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
  3253. {
  3254. if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
  3255. return false;
  3256. if (!IsItemFocused())
  3257. return false;
  3258. }
  3259. else
  3260. {
  3261. // Test for bounding box overlap, as updated as ItemAdd()
  3262. ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
  3263. if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
  3264. return false;
  3265. IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy)) == 0); // Flags not supported by this function
  3266. // Done with rectangle culling so we can perform heavier checks now
  3267. // Test if we are hovering the right window (our window could be behind another window)
  3268. // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
  3269. // [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
  3270. // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
  3271. // the test that has been running for a long while.
  3272. if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
  3273. if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
  3274. return false;
  3275. // Test if another item is active (e.g. being dragged)
  3276. if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
  3277. if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
  3278. return false;
  3279. // Test if interactions on this window are blocked by an active popup or modal.
  3280. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
  3281. if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
  3282. return false;
  3283. // Test if the item is disabled
  3284. if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
  3285. return false;
  3286. // Special handling for calling after Begin() which represent the title bar or tab.
  3287. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
  3288. if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
  3289. return false;
  3290. }
  3291. // Handle hover delay
  3292. // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
  3293. float delay;
  3294. if (flags & ImGuiHoveredFlags_DelayNormal)
  3295. delay = g.IO.HoverDelayNormal;
  3296. else if (flags & ImGuiHoveredFlags_DelayShort)
  3297. delay = g.IO.HoverDelayShort;
  3298. else
  3299. delay = 0.0f;
  3300. if (delay > 0.0f)
  3301. {
  3302. ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
  3303. if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
  3304. g.HoverDelayTimer = 0.0f;
  3305. g.HoverDelayId = hover_delay_id;
  3306. return g.HoverDelayTimer >= delay;
  3307. }
  3308. return true;
  3309. }
  3310. // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
  3311. bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
  3312. {
  3313. ImGuiContext& g = *GImGui;
  3314. if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
  3315. return false;
  3316. ImGuiWindow* window = g.CurrentWindow;
  3317. if (g.HoveredWindow != window)
  3318. return false;
  3319. if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
  3320. return false;
  3321. if (!IsMouseHoveringRect(bb.Min, bb.Max))
  3322. return false;
  3323. // Done with rectangle culling so we can perform heavier checks now.
  3324. ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
  3325. if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
  3326. {
  3327. g.HoveredIdDisabled = true;
  3328. return false;
  3329. }
  3330. // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
  3331. // hover test in widgets code. We could also decide to split this function is two.
  3332. if (id != 0)
  3333. SetHoveredID(id);
  3334. // When disabled we'll return false but still set HoveredId
  3335. if (item_flags & ImGuiItemFlags_Disabled)
  3336. {
  3337. // Release active id if turning disabled
  3338. if (g.ActiveId == id)
  3339. ClearActiveID();
  3340. g.HoveredIdDisabled = true;
  3341. return false;
  3342. }
  3343. if (id != 0)
  3344. {
  3345. // [DEBUG] Item Picker tool!
  3346. // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
  3347. // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
  3348. // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
  3349. if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
  3350. GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
  3351. if (g.DebugItemPickerBreakId == id)
  3352. IM_DEBUG_BREAK();
  3353. }
  3354. if (g.NavDisableMouseHover)
  3355. return false;
  3356. return true;
  3357. }
  3358. // FIXME: This is inlined/duplicated in ItemAdd()
  3359. bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
  3360. {
  3361. ImGuiContext& g = *GImGui;
  3362. ImGuiWindow* window = g.CurrentWindow;
  3363. if (!bb.Overlaps(window->ClipRect))
  3364. if (id == 0 || (id != g.ActiveId && id != g.NavId))
  3365. if (!g.LogEnabled)
  3366. return true;
  3367. return false;
  3368. }
  3369. // This is also inlined in ItemAdd()
  3370. // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
  3371. void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
  3372. {
  3373. ImGuiContext& g = *GImGui;
  3374. g.LastItemData.ID = item_id;
  3375. g.LastItemData.InFlags = in_flags;
  3376. g.LastItemData.StatusFlags = item_flags;
  3377. g.LastItemData.Rect = item_rect;
  3378. }
  3379. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  3380. {
  3381. if (wrap_pos_x < 0.0f)
  3382. return 0.0f;
  3383. ImGuiContext& g = *GImGui;
  3384. ImGuiWindow* window = g.CurrentWindow;
  3385. if (wrap_pos_x == 0.0f)
  3386. {
  3387. // We could decide to setup a default wrapping max point for auto-resizing windows,
  3388. // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
  3389. //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
  3390. // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
  3391. //else
  3392. wrap_pos_x = window->WorkRect.Max.x;
  3393. }
  3394. else if (wrap_pos_x > 0.0f)
  3395. {
  3396. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  3397. }
  3398. return ImMax(wrap_pos_x - pos.x, 1.0f);
  3399. }
  3400. // IM_ALLOC() == ImGui::MemAlloc()
  3401. void* ImGui::MemAlloc(size_t size)
  3402. {
  3403. if (ImGuiContext* ctx = GImGui)
  3404. ctx->IO.MetricsActiveAllocations++;
  3405. return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
  3406. }
  3407. // IM_FREE() == ImGui::MemFree()
  3408. void ImGui::MemFree(void* ptr)
  3409. {
  3410. if (ptr)
  3411. if (ImGuiContext* ctx = GImGui)
  3412. ctx->IO.MetricsActiveAllocations--;
  3413. return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
  3414. }
  3415. const char* ImGui::GetClipboardText()
  3416. {
  3417. ImGuiContext& g = *GImGui;
  3418. return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
  3419. }
  3420. void ImGui::SetClipboardText(const char* text)
  3421. {
  3422. ImGuiContext& g = *GImGui;
  3423. if (g.IO.SetClipboardTextFn)
  3424. g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
  3425. }
  3426. const char* ImGui::GetVersion()
  3427. {
  3428. return IMGUI_VERSION;
  3429. }
  3430. // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
  3431. // 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
  3432. ImGuiContext* ImGui::GetCurrentContext()
  3433. {
  3434. return GImGui;
  3435. }
  3436. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  3437. {
  3438. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  3439. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  3440. #else
  3441. GImGui = ctx;
  3442. #endif
  3443. }
  3444. void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
  3445. {
  3446. GImAllocatorAllocFunc = alloc_func;
  3447. GImAllocatorFreeFunc = free_func;
  3448. GImAllocatorUserData = user_data;
  3449. }
  3450. // This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
  3451. void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
  3452. {
  3453. *p_alloc_func = GImAllocatorAllocFunc;
  3454. *p_free_func = GImAllocatorFreeFunc;
  3455. *p_user_data = GImAllocatorUserData;
  3456. }
  3457. ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
  3458. {
  3459. ImGuiContext* prev_ctx = GetCurrentContext();
  3460. ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
  3461. SetCurrentContext(ctx);
  3462. Initialize();
  3463. if (prev_ctx != NULL)
  3464. SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
  3465. return ctx;
  3466. }
  3467. void ImGui::DestroyContext(ImGuiContext* ctx)
  3468. {
  3469. ImGuiContext* prev_ctx = GetCurrentContext();
  3470. if (ctx == NULL) //-V1051
  3471. ctx = prev_ctx;
  3472. SetCurrentContext(ctx);
  3473. Shutdown();
  3474. SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
  3475. IM_DELETE(ctx);
  3476. }
  3477. // No specific ordering/dependency support, will see as needed
  3478. ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
  3479. {
  3480. ImGuiContext& g = *ctx;
  3481. IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
  3482. g.Hooks.push_back(*hook);
  3483. g.Hooks.back().HookId = ++g.HookIdNext;
  3484. return g.HookIdNext;
  3485. }
  3486. // Deferred removal, avoiding issue with changing vector while iterating it
  3487. void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
  3488. {
  3489. ImGuiContext& g = *ctx;
  3490. IM_ASSERT(hook_id != 0);
  3491. for (int n = 0; n < g.Hooks.Size; n++)
  3492. if (g.Hooks[n].HookId == hook_id)
  3493. g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
  3494. }
  3495. // Call context hooks (used by e.g. test engine)
  3496. // We assume a small number of hooks so all stored in same array
  3497. void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
  3498. {
  3499. ImGuiContext& g = *ctx;
  3500. for (int n = 0; n < g.Hooks.Size; n++)
  3501. if (g.Hooks[n].Type == hook_type)
  3502. g.Hooks[n].Callback(&g, &g.Hooks[n]);
  3503. }
  3504. ImGuiIO& ImGui::GetIO()
  3505. {
  3506. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  3507. return GImGui->IO;
  3508. }
  3509. // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
  3510. ImDrawData* ImGui::GetDrawData()
  3511. {
  3512. ImGuiContext& g = *GImGui;
  3513. ImGuiViewportP* viewport = g.Viewports[0];
  3514. return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
  3515. }
  3516. double ImGui::GetTime()
  3517. {
  3518. return GImGui->Time;
  3519. }
  3520. int ImGui::GetFrameCount()
  3521. {
  3522. return GImGui->FrameCount;
  3523. }
  3524. static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
  3525. {
  3526. // Create the draw list on demand, because they are not frequently used for all viewports
  3527. ImGuiContext& g = *GImGui;
  3528. IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
  3529. ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
  3530. if (draw_list == NULL)
  3531. {
  3532. draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
  3533. draw_list->_OwnerName = drawlist_name;
  3534. viewport->DrawLists[drawlist_no] = draw_list;
  3535. }
  3536. // Our ImDrawList system requires that there is always a command
  3537. if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
  3538. {
  3539. draw_list->_ResetForNewFrame();
  3540. draw_list->PushTextureID(g.IO.Fonts->TexID);
  3541. draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
  3542. viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
  3543. }
  3544. return draw_list;
  3545. }
  3546. ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
  3547. {
  3548. return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
  3549. }
  3550. ImDrawList* ImGui::GetBackgroundDrawList()
  3551. {
  3552. ImGuiContext& g = *GImGui;
  3553. return GetBackgroundDrawList(g.Viewports[0]);
  3554. }
  3555. ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
  3556. {
  3557. return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
  3558. }
  3559. ImDrawList* ImGui::GetForegroundDrawList()
  3560. {
  3561. ImGuiContext& g = *GImGui;
  3562. return GetForegroundDrawList(g.Viewports[0]);
  3563. }
  3564. ImDrawListSharedData* ImGui::GetDrawListSharedData()
  3565. {
  3566. return &GImGui->DrawListSharedData;
  3567. }
  3568. void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
  3569. {
  3570. // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
  3571. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
  3572. // This is because we want ActiveId to be set even when the window is not permitted to move.
  3573. ImGuiContext& g = *GImGui;
  3574. FocusWindow(window);
  3575. SetActiveID(window->MoveId, window);
  3576. g.NavDisableHighlight = true;
  3577. g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
  3578. g.ActiveIdNoClearOnFocusLoss = true;
  3579. SetActiveIdUsingAllKeyboardKeys();
  3580. bool can_move_window = true;
  3581. if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
  3582. can_move_window = false;
  3583. if (can_move_window)
  3584. g.MovingWindow = window;
  3585. }
  3586. // Handle mouse moving window
  3587. // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
  3588. // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
  3589. // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
  3590. // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
  3591. void ImGui::UpdateMouseMovingWindowNewFrame()
  3592. {
  3593. ImGuiContext& g = *GImGui;
  3594. if (g.MovingWindow != NULL)
  3595. {
  3596. // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
  3597. // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
  3598. KeepAliveID(g.ActiveId);
  3599. IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
  3600. ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
  3601. if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
  3602. {
  3603. ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
  3604. SetWindowPos(moving_window, pos, ImGuiCond_Always);
  3605. FocusWindow(g.MovingWindow);
  3606. }
  3607. else
  3608. {
  3609. g.MovingWindow = NULL;
  3610. ClearActiveID();
  3611. }
  3612. }
  3613. else
  3614. {
  3615. // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
  3616. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
  3617. {
  3618. KeepAliveID(g.ActiveId);
  3619. if (!g.IO.MouseDown[0])
  3620. ClearActiveID();
  3621. }
  3622. }
  3623. }
  3624. // Initiate moving window when clicking on empty space or title bar.
  3625. // Handle left-click and right-click focus.
  3626. void ImGui::UpdateMouseMovingWindowEndFrame()
  3627. {
  3628. ImGuiContext& g = *GImGui;
  3629. if (g.ActiveId != 0 || g.HoveredId != 0)
  3630. return;
  3631. // Unless we just made a window/popup appear
  3632. if (g.NavWindow && g.NavWindow->Appearing)
  3633. return;
  3634. // Click on empty space to focus window and start moving
  3635. // (after we're done with all our widgets)
  3636. if (g.IO.MouseClicked[0])
  3637. {
  3638. // Handle the edge case of a popup being closed while clicking in its empty space.
  3639. // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
  3640. ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
  3641. const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
  3642. if (root_window != NULL && !is_closed_popup)
  3643. {
  3644. StartMouseMovingWindow(g.HoveredWindow); //-V595
  3645. // Cancel moving if clicked outside of title bar
  3646. if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
  3647. if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
  3648. g.MovingWindow = NULL;
  3649. // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
  3650. if (g.HoveredIdDisabled)
  3651. g.MovingWindow = NULL;
  3652. }
  3653. else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
  3654. {
  3655. // Clicking on void disable focus
  3656. FocusWindow(NULL);
  3657. }
  3658. }
  3659. // With right mouse button we close popups without changing focus based on where the mouse is aimed
  3660. // Instead, focus will be restored to the window under the bottom-most closed popup.
  3661. // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
  3662. if (g.IO.MouseClicked[1])
  3663. {
  3664. // Find the top-most window between HoveredWindow and the top-most Modal Window.
  3665. // This is where we can trim the popup stack.
  3666. ImGuiWindow* modal = GetTopMostPopupModal();
  3667. bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
  3668. ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
  3669. }
  3670. }
  3671. static bool IsWindowActiveAndVisible(ImGuiWindow* window)
  3672. {
  3673. return (window->Active) && (!window->Hidden);
  3674. }
  3675. static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
  3676. {
  3677. IM_ASSERT(ImGui::IsAliasKey(key));
  3678. ImGuiKeyData* key_data = ImGui::GetKeyData(key);
  3679. key_data->Down = v;
  3680. key_data->AnalogValue = analog_value;
  3681. }
  3682. // [Internal] Do not use directly (should read io.KeyMods instead)
  3683. static ImGuiKeyChord GetMergedModsFromBools()
  3684. {
  3685. ImGuiContext& g = *GImGui;
  3686. ImGuiKeyChord key_chord = 0;
  3687. if (g.IO.KeyCtrl) { key_chord |= ImGuiMod_Ctrl; }
  3688. if (g.IO.KeyShift) { key_chord |= ImGuiMod_Shift; }
  3689. if (g.IO.KeyAlt) { key_chord |= ImGuiMod_Alt; }
  3690. if (g.IO.KeySuper) { key_chord |= ImGuiMod_Super; }
  3691. return key_chord;
  3692. }
  3693. static void ImGui::UpdateKeyboardInputs()
  3694. {
  3695. ImGuiContext& g = *GImGui;
  3696. ImGuiIO& io = g.IO;
  3697. // Import legacy keys or verify they are not used
  3698. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  3699. if (io.BackendUsingLegacyKeyArrays == 0)
  3700. {
  3701. // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
  3702. for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
  3703. IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
  3704. }
  3705. else
  3706. {
  3707. if (g.FrameCount == 0)
  3708. for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
  3709. IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
  3710. // Build reverse KeyMap (Named -> Legacy)
  3711. for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
  3712. if (io.KeyMap[n] != -1)
  3713. {
  3714. IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
  3715. io.KeyMap[io.KeyMap[n]] = n;
  3716. }
  3717. // Import legacy keys into new ones
  3718. for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
  3719. if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
  3720. {
  3721. const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
  3722. IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
  3723. io.KeysData[key].Down = io.KeysDown[n];
  3724. if (key != n)
  3725. io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
  3726. io.BackendUsingLegacyKeyArrays = 1;
  3727. }
  3728. if (io.BackendUsingLegacyKeyArrays == 1)
  3729. {
  3730. GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
  3731. GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
  3732. GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
  3733. GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
  3734. }
  3735. }
  3736. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  3737. const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  3738. if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
  3739. {
  3740. #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
  3741. #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2) do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
  3742. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
  3743. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
  3744. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
  3745. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
  3746. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
  3747. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
  3748. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
  3749. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
  3750. MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
  3751. MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
  3752. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
  3753. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
  3754. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
  3755. MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
  3756. #undef NAV_MAP_KEY
  3757. }
  3758. #endif
  3759. #endif
  3760. // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools, update aliases
  3761. io.KeyMods = GetMergedModsFromBools();
  3762. for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
  3763. UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
  3764. UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
  3765. UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
  3766. // Clear gamepad data if disabled
  3767. if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
  3768. for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
  3769. {
  3770. io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
  3771. io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
  3772. }
  3773. // Update keys
  3774. for (int i = 0; i < IM_ARRAYSIZE(io.KeysData); i++)
  3775. {
  3776. ImGuiKeyData* key_data = &io.KeysData[i];
  3777. key_data->DownDurationPrev = key_data->DownDuration;
  3778. key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
  3779. }
  3780. }
  3781. static void ImGui::UpdateMouseInputs()
  3782. {
  3783. ImGuiContext& g = *GImGui;
  3784. ImGuiIO& io = g.IO;
  3785. // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
  3786. if (IsMousePosValid(&io.MousePos))
  3787. io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
  3788. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
  3789. if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
  3790. io.MouseDelta = io.MousePos - io.MousePosPrev;
  3791. else
  3792. io.MouseDelta = ImVec2(0.0f, 0.0f);
  3793. // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
  3794. if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
  3795. g.NavDisableMouseHover = false;
  3796. io.MousePosPrev = io.MousePos;
  3797. for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
  3798. {
  3799. io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
  3800. io.MouseClickedCount[i] = 0; // Will be filled below
  3801. io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
  3802. io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
  3803. io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
  3804. if (io.MouseClicked[i])
  3805. {
  3806. bool is_repeated_click = false;
  3807. if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
  3808. {
  3809. ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  3810. if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
  3811. is_repeated_click = true;
  3812. }
  3813. if (is_repeated_click)
  3814. io.MouseClickedLastCount[i]++;
  3815. else
  3816. io.MouseClickedLastCount[i] = 1;
  3817. io.MouseClickedTime[i] = g.Time;
  3818. io.MouseClickedPos[i] = io.MousePos;
  3819. io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
  3820. io.MouseDragMaxDistanceSqr[i] = 0.0f;
  3821. }
  3822. else if (io.MouseDown[i])
  3823. {
  3824. // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
  3825. float delta_sqr_click_pos = IsMousePosValid(&io.MousePos) ? ImLengthSqr(io.MousePos - io.MouseClickedPos[i]) : 0.0f;
  3826. io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], delta_sqr_click_pos);
  3827. }
  3828. // We provide io.MouseDoubleClicked[] as a legacy service
  3829. io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
  3830. // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
  3831. if (io.MouseClicked[i])
  3832. g.NavDisableMouseHover = false;
  3833. }
  3834. }
  3835. static void LockWheelingWindow(ImGuiWindow* window)
  3836. {
  3837. ImGuiContext& g = *GImGui;
  3838. g.WheelingWindowReleaseTimer = window ? WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER : 0.0f;
  3839. if (g.WheelingWindow == window)
  3840. return;
  3841. IMGUI_DEBUG_LOG_IO("LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
  3842. g.WheelingWindow = window;
  3843. g.WheelingWindowRefMousePos = g.IO.MousePos;
  3844. }
  3845. void ImGui::UpdateMouseWheel()
  3846. {
  3847. ImGuiContext& g = *GImGui;
  3848. // Reset the locked window if we move the mouse or after the timer elapses
  3849. if (g.WheelingWindow != NULL)
  3850. {
  3851. g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
  3852. if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
  3853. g.WheelingWindowReleaseTimer = 0.0f;
  3854. if (g.WheelingWindowReleaseTimer <= 0.0f)
  3855. LockWheelingWindow(NULL);
  3856. }
  3857. const bool hovered_id_using_mouse_wheel = (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel);
  3858. const bool active_id_using_mouse_wheel_x = g.ActiveIdUsingKeyInputMask.TestBit(ImGuiKey_MouseWheelX);
  3859. const bool active_id_using_mouse_wheel_y = g.ActiveIdUsingKeyInputMask.TestBit(ImGuiKey_MouseWheelY);
  3860. ImVec2 wheel;
  3861. wheel.x = (!hovered_id_using_mouse_wheel && !active_id_using_mouse_wheel_x) ? g.IO.MouseWheelH : 0.0f;
  3862. wheel.y = (!hovered_id_using_mouse_wheel && !active_id_using_mouse_wheel_y) ? g.IO.MouseWheel : 0;
  3863. if (wheel.x == 0.0f && wheel.y == 0.0f)
  3864. return;
  3865. //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
  3866. ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
  3867. if (!mouse_window || mouse_window->Collapsed)
  3868. return;
  3869. // Zoom / Scale window
  3870. // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
  3871. if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  3872. {
  3873. LockWheelingWindow(mouse_window);
  3874. ImGuiWindow* window = mouse_window;
  3875. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  3876. const float scale = new_font_scale / window->FontWindowScale;
  3877. window->FontWindowScale = new_font_scale;
  3878. if (window == window->RootWindow)
  3879. {
  3880. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  3881. SetWindowPos(window, window->Pos + offset, 0);
  3882. window->Size = ImFloor(window->Size * scale);
  3883. window->SizeFull = ImFloor(window->SizeFull * scale);
  3884. }
  3885. return;
  3886. }
  3887. if (g.IO.KeyCtrl)
  3888. return;
  3889. // Mouse wheel scrolling
  3890. // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
  3891. // (we avoid doing it on OSX as it the OS input layer handles this already)
  3892. const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
  3893. if (swap_axis)
  3894. {
  3895. wheel.x = wheel.y;
  3896. wheel.y = 0.0f;
  3897. }
  3898. // Vertical Mouse Wheel scrolling
  3899. // Bubble up into parent window if:
  3900. // - a child window doesn't allow any scrolling.
  3901. // - a child window doesn't need scrolling because it is already at the edge for the direction we are going in.
  3902. // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
  3903. if (wheel.y != 0.0f)
  3904. {
  3905. ImGuiWindow* window = mouse_window;
  3906. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3907. window = window->ParentWindow;
  3908. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3909. {
  3910. LockWheelingWindow(mouse_window);
  3911. float max_step = window->InnerRect.GetHeight() * 0.67f;
  3912. float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
  3913. SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
  3914. }
  3915. }
  3916. // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
  3917. if (wheel.x != 0.0f)
  3918. {
  3919. ImGuiWindow* window = mouse_window;
  3920. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3921. window = window->ParentWindow;
  3922. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3923. {
  3924. LockWheelingWindow(mouse_window);
  3925. float max_step = window->InnerRect.GetWidth() * 0.67f;
  3926. float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
  3927. SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
  3928. }
  3929. }
  3930. }
  3931. // The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
  3932. void ImGui::UpdateHoveredWindowAndCaptureFlags()
  3933. {
  3934. ImGuiContext& g = *GImGui;
  3935. ImGuiIO& io = g.IO;
  3936. g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
  3937. // Find the window hovered by mouse:
  3938. // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
  3939. // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
  3940. // - 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.
  3941. bool clear_hovered_windows = false;
  3942. FindHoveredWindow();
  3943. // Modal windows prevents mouse from hovering behind them.
  3944. ImGuiWindow* modal_window = GetTopMostPopupModal();
  3945. if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window))
  3946. clear_hovered_windows = true;
  3947. // Disabled mouse?
  3948. if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
  3949. clear_hovered_windows = true;
  3950. // We track click ownership. When clicked outside of a window the click is owned by the application and
  3951. // won't report hovering nor request capture even while dragging over our windows afterward.
  3952. const bool has_open_popup = (g.OpenPopupStack.Size > 0);
  3953. const bool has_open_modal = (modal_window != NULL);
  3954. int mouse_earliest_down = -1;
  3955. bool mouse_any_down = false;
  3956. for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
  3957. {
  3958. if (io.MouseClicked[i])
  3959. {
  3960. io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
  3961. io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
  3962. }
  3963. mouse_any_down |= io.MouseDown[i];
  3964. if (io.MouseDown[i])
  3965. if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
  3966. mouse_earliest_down = i;
  3967. }
  3968. const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
  3969. const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
  3970. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  3971. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
  3972. const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
  3973. if (!mouse_avail && !mouse_dragging_extern_payload)
  3974. clear_hovered_windows = true;
  3975. if (clear_hovered_windows)
  3976. g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3977. // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
  3978. // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
  3979. if (g.WantCaptureMouseNextFrame != -1)
  3980. {
  3981. io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
  3982. }
  3983. else
  3984. {
  3985. io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
  3986. io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
  3987. }
  3988. // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
  3989. if (g.WantCaptureKeyboardNextFrame != -1)
  3990. io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
  3991. else
  3992. io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
  3993. if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
  3994. io.WantCaptureKeyboard = true;
  3995. // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
  3996. io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
  3997. }
  3998. void ImGui::NewFrame()
  3999. {
  4000. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  4001. ImGuiContext& g = *GImGui;
  4002. // Remove pending delete hooks before frame start.
  4003. // This deferred removal avoid issues of removal while iterating the hook vector
  4004. for (int n = g.Hooks.Size - 1; n >= 0; n--)
  4005. if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
  4006. g.Hooks.erase(&g.Hooks[n]);
  4007. CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
  4008. // Check and assert for various common IO and Configuration mistakes
  4009. ErrorCheckNewFrameSanityChecks();
  4010. // Load settings on first frame, save settings when modified (after a delay)
  4011. UpdateSettings();
  4012. g.Time += g.IO.DeltaTime;
  4013. g.WithinFrameScope = true;
  4014. g.FrameCount += 1;
  4015. g.TooltipOverrideCount = 0;
  4016. g.WindowsActiveCount = 0;
  4017. g.MenusIdSubmittedThisFrame.resize(0);
  4018. // Calculate frame-rate for the user, as a purely luxurious feature
  4019. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  4020. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  4021. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  4022. g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
  4023. g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
  4024. UpdateViewportsNewFrame();
  4025. // Setup current font and draw list shared data
  4026. g.IO.Fonts->Locked = true;
  4027. SetCurrentFont(GetDefaultFont());
  4028. IM_ASSERT(g.Font->IsLoaded());
  4029. ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  4030. for (int n = 0; n < g.Viewports.Size; n++)
  4031. virtual_space.Add(g.Viewports[n]->GetMainRect());
  4032. g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
  4033. g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
  4034. g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
  4035. g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
  4036. if (g.Style.AntiAliasedLines)
  4037. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
  4038. if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
  4039. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
  4040. if (g.Style.AntiAliasedFill)
  4041. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
  4042. if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
  4043. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
  4044. // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
  4045. for (int n = 0; n < g.Viewports.Size; n++)
  4046. {
  4047. ImGuiViewportP* viewport = g.Viewports[n];
  4048. viewport->DrawDataP.Clear();
  4049. }
  4050. // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
  4051. if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
  4052. KeepAliveID(g.DragDropPayload.SourceId);
  4053. // Update HoveredId data
  4054. if (!g.HoveredIdPreviousFrame)
  4055. g.HoveredIdTimer = 0.0f;
  4056. if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
  4057. g.HoveredIdNotActiveTimer = 0.0f;
  4058. if (g.HoveredId)
  4059. g.HoveredIdTimer += g.IO.DeltaTime;
  4060. if (g.HoveredId && g.ActiveId != g.HoveredId)
  4061. g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
  4062. g.HoveredIdPreviousFrame = g.HoveredId;
  4063. g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel;
  4064. g.HoveredId = 0;
  4065. g.HoveredIdAllowOverlap = false;
  4066. g.HoveredIdUsingMouseWheel = false;
  4067. g.HoveredIdDisabled = false;
  4068. // Clear ActiveID if the item is not alive anymore.
  4069. // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
  4070. // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
  4071. if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
  4072. {
  4073. IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
  4074. ClearActiveID();
  4075. }
  4076. // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
  4077. if (g.ActiveId)
  4078. g.ActiveIdTimer += g.IO.DeltaTime;
  4079. g.LastActiveIdTimer += g.IO.DeltaTime;
  4080. g.ActiveIdPreviousFrame = g.ActiveId;
  4081. g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
  4082. g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
  4083. g.ActiveIdIsAlive = 0;
  4084. g.ActiveIdHasBeenEditedThisFrame = false;
  4085. g.ActiveIdPreviousFrameIsAlive = false;
  4086. g.ActiveIdIsJustActivated = false;
  4087. if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
  4088. g.TempInputId = 0;
  4089. if (g.ActiveId == 0)
  4090. {
  4091. g.ActiveIdUsingNavDirMask = 0x00;
  4092. g.ActiveIdUsingKeyInputMask.ClearAllBits();
  4093. }
  4094. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  4095. if (g.ActiveId == 0)
  4096. g.ActiveIdUsingNavInputMask = 0;
  4097. else if (g.ActiveIdUsingNavInputMask != 0)
  4098. {
  4099. // If your custom widget code used: { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
  4100. // Since IMGUI_VERSION_NUM >= 18804 it should be: { SetActiveIdUsingKey(ImGuiKey_Escape); SetActiveIdUsingKey(ImGuiKey_NavGamepadCancel); }
  4101. if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
  4102. SetActiveIdUsingKey(ImGuiKey_Escape);
  4103. if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
  4104. IM_ASSERT(0); // Other values unsupported
  4105. }
  4106. #endif
  4107. // Update hover delay for IsItemHovered() with delays and tooltips
  4108. g.HoverDelayIdPreviousFrame = g.HoverDelayId;
  4109. if (g.HoverDelayId != 0)
  4110. {
  4111. //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
  4112. g.HoverDelayTimer += g.IO.DeltaTime;
  4113. g.HoverDelayClearTimer = 0.0f;
  4114. g.HoverDelayId = 0;
  4115. }
  4116. else if (g.HoverDelayTimer > 0.0f)
  4117. {
  4118. // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
  4119. g.HoverDelayClearTimer += g.IO.DeltaTime;
  4120. if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
  4121. g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
  4122. }
  4123. // Drag and drop
  4124. g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
  4125. g.DragDropAcceptIdCurr = 0;
  4126. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  4127. g.DragDropWithinSource = false;
  4128. g.DragDropWithinTarget = false;
  4129. g.DragDropHoldJustPressedId = 0;
  4130. // Close popups on focus lost (currently wip/opt-in)
  4131. //if (g.IO.AppFocusLost)
  4132. // ClosePopupsExceptModals();
  4133. // Process input queue (trickle as many events as possible)
  4134. g.InputEventsTrail.resize(0);
  4135. UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
  4136. // Update keyboard input state
  4137. UpdateKeyboardInputs();
  4138. //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
  4139. //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
  4140. //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
  4141. //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
  4142. // Update gamepad/keyboard navigation
  4143. NavUpdate();
  4144. // Update mouse input state
  4145. UpdateMouseInputs();
  4146. // Find hovered window
  4147. // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
  4148. UpdateHoveredWindowAndCaptureFlags();
  4149. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
  4150. UpdateMouseMovingWindowNewFrame();
  4151. // Background darkening/whitening
  4152. if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
  4153. g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  4154. else
  4155. g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
  4156. g.MouseCursor = ImGuiMouseCursor_Arrow;
  4157. g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
  4158. // Platform IME data: reset for the frame
  4159. g.PlatformImeDataPrev = g.PlatformImeData;
  4160. g.PlatformImeData.WantVisible = false;
  4161. // Mouse wheel scrolling, scale
  4162. UpdateMouseWheel();
  4163. // Mark all windows as not visible and compact unused memory.
  4164. IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
  4165. const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
  4166. for (int i = 0; i != g.Windows.Size; i++)
  4167. {
  4168. ImGuiWindow* window = g.Windows[i];
  4169. window->WasActive = window->Active;
  4170. window->Active = false;
  4171. window->WriteAccessed = false;
  4172. window->BeginCountPreviousFrame = window->BeginCount;
  4173. window->BeginCount = 0;
  4174. // Garbage collect transient buffers of recently unused windows
  4175. if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
  4176. GcCompactTransientWindowBuffers(window);
  4177. }
  4178. // Garbage collect transient buffers of recently unused tables
  4179. for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
  4180. if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
  4181. TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
  4182. for (int i = 0; i < g.TablesTempData.Size; i++)
  4183. if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
  4184. TableGcCompactTransientBuffers(&g.TablesTempData[i]);
  4185. if (g.GcCompactAll)
  4186. GcCompactTransientMiscBuffers();
  4187. g.GcCompactAll = false;
  4188. // Closing the focused window restore focus to the first active root window in descending z-order
  4189. if (g.NavWindow && !g.NavWindow->WasActive)
  4190. FocusTopMostWindowUnderOne(NULL, NULL);
  4191. // No window should be open at the beginning of the frame.
  4192. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  4193. g.CurrentWindowStack.resize(0);
  4194. g.BeginPopupStack.resize(0);
  4195. g.ItemFlagsStack.resize(0);
  4196. g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
  4197. g.GroupStack.resize(0);
  4198. // [DEBUG] Update debug features
  4199. UpdateDebugToolItemPicker();
  4200. UpdateDebugToolStackQueries();
  4201. // Create implicit/fallback window - which we will only render it if the user has added something to it.
  4202. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
  4203. // This fallback is particularly important as it prevents ImGui:: calls from crashing.
  4204. g.WithinFrameScopeWithImplicitWindow = true;
  4205. SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
  4206. Begin("Debug##Default");
  4207. IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
  4208. CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
  4209. }
  4210. void ImGui::Initialize()
  4211. {
  4212. ImGuiContext& g = *GImGui;
  4213. IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
  4214. // Add .ini handle for ImGuiWindow type
  4215. {
  4216. ImGuiSettingsHandler ini_handler;
  4217. ini_handler.TypeName = "Window";
  4218. ini_handler.TypeHash = ImHashStr("Window");
  4219. ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
  4220. ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
  4221. ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
  4222. ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
  4223. ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
  4224. AddSettingsHandler(&ini_handler);
  4225. }
  4226. // Add .ini handle for ImGuiTable type
  4227. TableSettingsAddSettingsHandler();
  4228. // Create default viewport
  4229. ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
  4230. g.Viewports.push_back(viewport);
  4231. g.TempBuffer.resize(1024 * 3 + 1, 0);
  4232. #ifdef IMGUI_HAS_DOCK
  4233. #endif
  4234. g.Initialized = true;
  4235. }
  4236. // This function is merely here to free heap allocations.
  4237. void ImGui::Shutdown()
  4238. {
  4239. // 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)
  4240. ImGuiContext& g = *GImGui;
  4241. if (g.IO.Fonts && g.FontAtlasOwnedByContext)
  4242. {
  4243. g.IO.Fonts->Locked = false;
  4244. IM_DELETE(g.IO.Fonts);
  4245. }
  4246. g.IO.Fonts = NULL;
  4247. g.DrawListSharedData.TempBuffer.clear();
  4248. // Cleanup of other data are conditional on actually having initialized Dear ImGui.
  4249. if (!g.Initialized)
  4250. return;
  4251. // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
  4252. if (g.SettingsLoaded && g.IO.IniFilename != NULL)
  4253. SaveIniSettingsToDisk(g.IO.IniFilename);
  4254. CallContextHooks(&g, ImGuiContextHookType_Shutdown);
  4255. // Clear everything else
  4256. g.Windows.clear_delete();
  4257. g.WindowsFocusOrder.clear();
  4258. g.WindowsTempSortBuffer.clear();
  4259. g.CurrentWindow = NULL;
  4260. g.CurrentWindowStack.clear();
  4261. g.WindowsById.Clear();
  4262. g.NavWindow = NULL;
  4263. g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
  4264. g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
  4265. g.MovingWindow = NULL;
  4266. g.ColorStack.clear();
  4267. g.StyleVarStack.clear();
  4268. g.FontStack.clear();
  4269. g.OpenPopupStack.clear();
  4270. g.BeginPopupStack.clear();
  4271. g.Viewports.clear_delete();
  4272. g.TabBars.Clear();
  4273. g.CurrentTabBarStack.clear();
  4274. g.ShrinkWidthBuffer.clear();
  4275. g.ClipperTempData.clear_destruct();
  4276. g.Tables.Clear();
  4277. g.TablesTempData.clear_destruct();
  4278. g.DrawChannelsTempMergeBuffer.clear();
  4279. g.ClipboardHandlerData.clear();
  4280. g.MenusIdSubmittedThisFrame.clear();
  4281. g.InputTextState.ClearFreeMemory();
  4282. g.SettingsWindows.clear();
  4283. g.SettingsHandlers.clear();
  4284. if (g.LogFile)
  4285. {
  4286. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  4287. if (g.LogFile != stdout)
  4288. #endif
  4289. ImFileClose(g.LogFile);
  4290. g.LogFile = NULL;
  4291. }
  4292. g.LogBuffer.clear();
  4293. g.DebugLogBuf.clear();
  4294. g.Initialized = false;
  4295. }
  4296. // FIXME: Add a more explicit sort order in the window structure.
  4297. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
  4298. {
  4299. const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
  4300. const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
  4301. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  4302. return d;
  4303. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  4304. return d;
  4305. return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
  4306. }
  4307. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
  4308. {
  4309. out_sorted_windows->push_back(window);
  4310. if (window->Active)
  4311. {
  4312. int count = window->DC.ChildWindows.Size;
  4313. ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  4314. for (int i = 0; i < count; i++)
  4315. {
  4316. ImGuiWindow* child = window->DC.ChildWindows[i];
  4317. if (child->Active)
  4318. AddWindowToSortBuffer(out_sorted_windows, child);
  4319. }
  4320. }
  4321. }
  4322. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
  4323. {
  4324. if (draw_list->CmdBuffer.Size == 0)
  4325. return;
  4326. if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
  4327. return;
  4328. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
  4329. // May trigger for you if you are using PrimXXX functions incorrectly.
  4330. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  4331. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  4332. if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
  4333. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  4334. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
  4335. // If this assert triggers because you are drawing lots of stuff manually:
  4336. // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
  4337. // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
  4338. // - If you want large meshes with more than 64K vertices, you can either:
  4339. // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
  4340. // Most example backends already support this from 1.71. Pre-1.71 backends won't.
  4341. // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
  4342. // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
  4343. // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
  4344. // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
  4345. // Your own engine or render API may use different parameters or function calls to specify index sizes.
  4346. // 2 and 4 bytes indices are generally supported by most graphics API.
  4347. // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
  4348. // the 64K limit to split your draw commands in multiple draw lists.
  4349. if (sizeof(ImDrawIdx) == 2)
  4350. IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
  4351. out_list->push_back(draw_list);
  4352. }
  4353. static void AddWindowToDrawData(ImGuiWindow* window, int layer)
  4354. {
  4355. ImGuiContext& g = *GImGui;
  4356. ImGuiViewportP* viewport = g.Viewports[0];
  4357. g.IO.MetricsRenderWindows++;
  4358. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
  4359. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  4360. {
  4361. ImGuiWindow* child = window->DC.ChildWindows[i];
  4362. if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
  4363. AddWindowToDrawData(child, layer);
  4364. }
  4365. }
  4366. static inline int GetWindowDisplayLayer(ImGuiWindow* window)
  4367. {
  4368. return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
  4369. }
  4370. // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
  4371. static inline void AddRootWindowToDrawData(ImGuiWindow* window)
  4372. {
  4373. AddWindowToDrawData(window, GetWindowDisplayLayer(window));
  4374. }
  4375. void ImDrawDataBuilder::FlattenIntoSingleLayer()
  4376. {
  4377. int n = Layers[0].Size;
  4378. int size = n;
  4379. for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
  4380. size += Layers[i].Size;
  4381. Layers[0].resize(size);
  4382. for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
  4383. {
  4384. ImVector<ImDrawList*>& layer = Layers[layer_n];
  4385. if (layer.empty())
  4386. continue;
  4387. memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  4388. n += layer.Size;
  4389. layer.resize(0);
  4390. }
  4391. }
  4392. static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
  4393. {
  4394. ImGuiIO& io = ImGui::GetIO();
  4395. ImDrawData* draw_data = &viewport->DrawDataP;
  4396. draw_data->Valid = true;
  4397. draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
  4398. draw_data->CmdListsCount = draw_lists->Size;
  4399. draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
  4400. draw_data->DisplayPos = viewport->Pos;
  4401. draw_data->DisplaySize = viewport->Size;
  4402. draw_data->FramebufferScale = io.DisplayFramebufferScale;
  4403. for (int n = 0; n < draw_lists->Size; n++)
  4404. {
  4405. ImDrawList* draw_list = draw_lists->Data[n];
  4406. draw_list->_PopUnusedDrawCmd();
  4407. draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
  4408. draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
  4409. }
  4410. }
  4411. // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
  4412. // - When using this function it is sane to ensure that float are perfectly rounded to integer values,
  4413. // so that e.g. (int)(max.x-min.x) in user's render produce correct result.
  4414. // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
  4415. // some frequently called functions which to modify both channels and clipping simultaneously tend to use the
  4416. // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
  4417. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  4418. {
  4419. ImGuiWindow* window = GetCurrentWindow();
  4420. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  4421. window->ClipRect = window->DrawList->_ClipRectStack.back();
  4422. }
  4423. void ImGui::PopClipRect()
  4424. {
  4425. ImGuiWindow* window = GetCurrentWindow();
  4426. window->DrawList->PopClipRect();
  4427. window->ClipRect = window->DrawList->_ClipRectStack.back();
  4428. }
  4429. static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
  4430. {
  4431. if ((col & IM_COL32_A_MASK) == 0)
  4432. return;
  4433. ImGuiViewportP* viewport = (ImGuiViewportP*)GetMainViewport();
  4434. ImRect viewport_rect = viewport->GetMainRect();
  4435. // Draw behind window by moving the draw command at the FRONT of the draw list
  4436. {
  4437. // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
  4438. // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
  4439. // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
  4440. ImDrawList* draw_list = window->RootWindow->DrawList;
  4441. if (draw_list->CmdBuffer.Size == 0)
  4442. draw_list->AddDrawCmd();
  4443. draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
  4444. draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
  4445. ImDrawCmd cmd = draw_list->CmdBuffer.back();
  4446. IM_ASSERT(cmd.ElemCount == 6);
  4447. draw_list->CmdBuffer.pop_back();
  4448. draw_list->CmdBuffer.push_front(cmd);
  4449. draw_list->PopClipRect();
  4450. draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
  4451. }
  4452. }
  4453. ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
  4454. {
  4455. ImGuiContext& g = *GImGui;
  4456. ImGuiWindow* bottom_most_visible_window = parent_window;
  4457. for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
  4458. {
  4459. ImGuiWindow* window = g.Windows[i];
  4460. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  4461. continue;
  4462. if (!IsWindowWithinBeginStackOf(window, parent_window))
  4463. break;
  4464. if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
  4465. bottom_most_visible_window = window;
  4466. }
  4467. return bottom_most_visible_window;
  4468. }
  4469. static void ImGui::RenderDimmedBackgrounds()
  4470. {
  4471. ImGuiContext& g = *GImGui;
  4472. ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
  4473. if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
  4474. return;
  4475. const bool dim_bg_for_modal = (modal_window != NULL);
  4476. const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
  4477. if (!dim_bg_for_modal && !dim_bg_for_window_list)
  4478. return;
  4479. if (dim_bg_for_modal)
  4480. {
  4481. // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
  4482. ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
  4483. RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
  4484. }
  4485. else if (dim_bg_for_window_list)
  4486. {
  4487. // Draw dimming behind CTRL+Tab target window
  4488. RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
  4489. // Draw border around CTRL+Tab target window
  4490. ImGuiWindow* window = g.NavWindowingTargetAnim;
  4491. ImGuiViewport* viewport = GetMainViewport();
  4492. float distance = g.FontSize;
  4493. ImRect bb = window->Rect();
  4494. bb.Expand(distance);
  4495. if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
  4496. bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
  4497. if (window->DrawList->CmdBuffer.Size == 0)
  4498. window->DrawList->AddDrawCmd();
  4499. window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
  4500. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
  4501. window->DrawList->PopClipRect();
  4502. }
  4503. }
  4504. // 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.
  4505. void ImGui::EndFrame()
  4506. {
  4507. ImGuiContext& g = *GImGui;
  4508. IM_ASSERT(g.Initialized);
  4509. // Don't process EndFrame() multiple times.
  4510. if (g.FrameCountEnded == g.FrameCount)
  4511. return;
  4512. IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
  4513. CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
  4514. ErrorCheckEndFrameSanityChecks();
  4515. // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  4516. if (g.IO.SetPlatformImeDataFn && memcmp(&g.PlatformImeData, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
  4517. g.IO.SetPlatformImeDataFn(GetMainViewport(), &g.PlatformImeData);
  4518. // Hide implicit/fallback "Debug" window if it hasn't been used
  4519. g.WithinFrameScopeWithImplicitWindow = false;
  4520. if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
  4521. g.CurrentWindow->Active = false;
  4522. End();
  4523. // Update navigation: CTRL+Tab, wrap-around requests
  4524. NavEndFrame();
  4525. // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
  4526. if (g.DragDropActive)
  4527. {
  4528. bool is_delivered = g.DragDropPayload.Delivery;
  4529. bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
  4530. if (is_delivered || is_elapsed)
  4531. ClearDragDrop();
  4532. }
  4533. // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
  4534. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  4535. {
  4536. g.DragDropWithinSource = true;
  4537. SetTooltip("...");
  4538. g.DragDropWithinSource = false;
  4539. }
  4540. // End frame
  4541. g.WithinFrameScope = false;
  4542. g.FrameCountEnded = g.FrameCount;
  4543. // Initiate moving window + handle left-click and right-click focus
  4544. UpdateMouseMovingWindowEndFrame();
  4545. // Sort the window list so that all child windows are after their parent
  4546. // We cannot do that on FocusWindow() because children may not exist yet
  4547. g.WindowsTempSortBuffer.resize(0);
  4548. g.WindowsTempSortBuffer.reserve(g.Windows.Size);
  4549. for (int i = 0; i != g.Windows.Size; i++)
  4550. {
  4551. ImGuiWindow* window = g.Windows[i];
  4552. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  4553. continue;
  4554. AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
  4555. }
  4556. // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
  4557. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
  4558. g.Windows.swap(g.WindowsTempSortBuffer);
  4559. g.IO.MetricsActiveWindows = g.WindowsActiveCount;
  4560. // Unlock font atlas
  4561. g.IO.Fonts->Locked = false;
  4562. // Clear Input data for next frame
  4563. g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
  4564. g.IO.InputQueueCharacters.resize(0);
  4565. CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
  4566. }
  4567. // Prepare the data for rendering so you can call GetDrawData()
  4568. // (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
  4569. // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
  4570. void ImGui::Render()
  4571. {
  4572. ImGuiContext& g = *GImGui;
  4573. IM_ASSERT(g.Initialized);
  4574. if (g.FrameCountEnded != g.FrameCount)
  4575. EndFrame();
  4576. const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
  4577. g.FrameCountRendered = g.FrameCount;
  4578. g.IO.MetricsRenderWindows = 0;
  4579. CallContextHooks(&g, ImGuiContextHookType_RenderPre);
  4580. // Add background ImDrawList (for each active viewport)
  4581. for (int n = 0; n != g.Viewports.Size; n++)
  4582. {
  4583. ImGuiViewportP* viewport = g.Viewports[n];
  4584. viewport->DrawDataBuilder.Clear();
  4585. if (viewport->DrawLists[0] != NULL)
  4586. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
  4587. }
  4588. // Draw modal/window whitening backgrounds
  4589. if (first_render_of_frame)
  4590. RenderDimmedBackgrounds();
  4591. // Add ImDrawList to render
  4592. ImGuiWindow* windows_to_render_top_most[2];
  4593. windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
  4594. windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
  4595. for (int n = 0; n != g.Windows.Size; n++)
  4596. {
  4597. ImGuiWindow* window = g.Windows[n];
  4598. IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
  4599. if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
  4600. AddRootWindowToDrawData(window);
  4601. }
  4602. for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
  4603. if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
  4604. AddRootWindowToDrawData(windows_to_render_top_most[n]);
  4605. // Draw software mouse cursor if requested by io.MouseDrawCursor flag
  4606. if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
  4607. RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
  4608. // Setup ImDrawData structures for end-user
  4609. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
  4610. for (int n = 0; n < g.Viewports.Size; n++)
  4611. {
  4612. ImGuiViewportP* viewport = g.Viewports[n];
  4613. viewport->DrawDataBuilder.FlattenIntoSingleLayer();
  4614. // Add foreground ImDrawList (for each active viewport)
  4615. if (viewport->DrawLists[1] != NULL)
  4616. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
  4617. SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
  4618. ImDrawData* draw_data = &viewport->DrawDataP;
  4619. g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
  4620. g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
  4621. }
  4622. CallContextHooks(&g, ImGuiContextHookType_RenderPost);
  4623. }
  4624. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  4625. // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
  4626. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  4627. {
  4628. ImGuiContext& g = *GImGui;
  4629. const char* text_display_end;
  4630. if (hide_text_after_double_hash)
  4631. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  4632. else
  4633. text_display_end = text_end;
  4634. ImFont* font = g.Font;
  4635. const float font_size = g.FontSize;
  4636. if (text == text_display_end)
  4637. return ImVec2(0.0f, font_size);
  4638. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  4639. // Round
  4640. // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
  4641. // FIXME: Investigate using ceilf or e.g.
  4642. // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
  4643. // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
  4644. text_size.x = IM_FLOOR(text_size.x + 0.99999f);
  4645. return text_size;
  4646. }
  4647. // Find window given position, search front-to-back
  4648. // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
  4649. // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
  4650. // called, aka before the next Begin(). Moving window isn't affected.
  4651. static void FindHoveredWindow()
  4652. {
  4653. ImGuiContext& g = *GImGui;
  4654. ImGuiWindow* hovered_window = NULL;
  4655. ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
  4656. if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
  4657. hovered_window = g.MovingWindow;
  4658. ImVec2 padding_regular = g.Style.TouchExtraPadding;
  4659. ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
  4660. for (int i = g.Windows.Size - 1; i >= 0; i--)
  4661. {
  4662. ImGuiWindow* window = g.Windows[i];
  4663. IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
  4664. if (!window->Active || window->Hidden)
  4665. continue;
  4666. if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
  4667. continue;
  4668. // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
  4669. ImRect bb(window->OuterRectClipped);
  4670. if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
  4671. bb.Expand(padding_regular);
  4672. else
  4673. bb.Expand(padding_for_resize);
  4674. if (!bb.Contains(g.IO.MousePos))
  4675. continue;
  4676. // Support for one rectangular hole in any given window
  4677. // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
  4678. if (window->HitTestHoleSize.x != 0)
  4679. {
  4680. ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
  4681. ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
  4682. if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
  4683. continue;
  4684. }
  4685. if (hovered_window == NULL)
  4686. hovered_window = window;
  4687. IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
  4688. if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
  4689. hovered_window_ignoring_moving_window = window;
  4690. if (hovered_window && hovered_window_ignoring_moving_window)
  4691. break;
  4692. }
  4693. g.HoveredWindow = hovered_window;
  4694. g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
  4695. }
  4696. bool ImGui::IsItemActive()
  4697. {
  4698. ImGuiContext& g = *GImGui;
  4699. if (g.ActiveId)
  4700. return g.ActiveId == g.LastItemData.ID;
  4701. return false;
  4702. }
  4703. bool ImGui::IsItemActivated()
  4704. {
  4705. ImGuiContext& g = *GImGui;
  4706. if (g.ActiveId)
  4707. if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
  4708. return true;
  4709. return false;
  4710. }
  4711. bool ImGui::IsItemDeactivated()
  4712. {
  4713. ImGuiContext& g = *GImGui;
  4714. if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
  4715. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
  4716. return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
  4717. }
  4718. bool ImGui::IsItemDeactivatedAfterEdit()
  4719. {
  4720. ImGuiContext& g = *GImGui;
  4721. return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
  4722. }
  4723. // == GetItemID() == GetFocusID()
  4724. bool ImGui::IsItemFocused()
  4725. {
  4726. ImGuiContext& g = *GImGui;
  4727. if (g.NavId != g.LastItemData.ID || g.NavId == 0)
  4728. return false;
  4729. return true;
  4730. }
  4731. // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
  4732. // Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
  4733. bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
  4734. {
  4735. return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
  4736. }
  4737. bool ImGui::IsItemToggledOpen()
  4738. {
  4739. ImGuiContext& g = *GImGui;
  4740. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
  4741. }
  4742. bool ImGui::IsItemToggledSelection()
  4743. {
  4744. ImGuiContext& g = *GImGui;
  4745. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
  4746. }
  4747. bool ImGui::IsAnyItemHovered()
  4748. {
  4749. ImGuiContext& g = *GImGui;
  4750. return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
  4751. }
  4752. bool ImGui::IsAnyItemActive()
  4753. {
  4754. ImGuiContext& g = *GImGui;
  4755. return g.ActiveId != 0;
  4756. }
  4757. bool ImGui::IsAnyItemFocused()
  4758. {
  4759. ImGuiContext& g = *GImGui;
  4760. return g.NavId != 0 && !g.NavDisableHighlight;
  4761. }
  4762. bool ImGui::IsItemVisible()
  4763. {
  4764. ImGuiContext& g = *GImGui;
  4765. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
  4766. }
  4767. bool ImGui::IsItemEdited()
  4768. {
  4769. ImGuiContext& g = *GImGui;
  4770. return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
  4771. }
  4772. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  4773. // FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
  4774. void ImGui::SetItemAllowOverlap()
  4775. {
  4776. ImGuiContext& g = *GImGui;
  4777. ImGuiID id = g.LastItemData.ID;
  4778. if (g.HoveredId == id)
  4779. g.HoveredIdAllowOverlap = true;
  4780. if (g.ActiveId == id)
  4781. g.ActiveIdAllowOverlap = true;
  4782. }
  4783. void ImGui::SetItemUsingMouseWheel()
  4784. {
  4785. ImGuiContext& g = *GImGui;
  4786. ImGuiID id = g.LastItemData.ID;
  4787. if (g.HoveredId == id)
  4788. g.HoveredIdUsingMouseWheel = true;
  4789. if (g.ActiveId == id)
  4790. {
  4791. g.ActiveIdUsingKeyInputMask.SetBit(ImGuiKey_MouseWheelX);
  4792. g.ActiveIdUsingKeyInputMask.SetBit(ImGuiKey_MouseWheelY);
  4793. }
  4794. }
  4795. void ImGui::SetActiveIdUsingAllKeyboardKeys()
  4796. {
  4797. ImGuiContext& g = *GImGui;
  4798. IM_ASSERT(g.ActiveId != 0);
  4799. g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
  4800. g.ActiveIdUsingKeyInputMask.SetBitRange(ImGuiKey_Keyboard_BEGIN, ImGuiKey_Keyboard_END);
  4801. //g.ActiveIdUsingKeyInputMask.SetBit(ImGuiKey_ModCtrl);
  4802. //g.ActiveIdUsingKeyInputMask.SetBit(ImGuiKey_ModShift);
  4803. //g.ActiveIdUsingKeyInputMask.SetBit(ImGuiKey_ModAlt);
  4804. //g.ActiveIdUsingKeyInputMask.SetBit(ImGuiKey_ModSuper);
  4805. NavMoveRequestCancel();
  4806. }
  4807. ImVec2 ImGui::GetItemRectMin()
  4808. {
  4809. ImGuiContext& g = *GImGui;
  4810. return g.LastItemData.Rect.Min;
  4811. }
  4812. ImVec2 ImGui::GetItemRectMax()
  4813. {
  4814. ImGuiContext& g = *GImGui;
  4815. return g.LastItemData.Rect.Max;
  4816. }
  4817. ImVec2 ImGui::GetItemRectSize()
  4818. {
  4819. ImGuiContext& g = *GImGui;
  4820. return g.LastItemData.Rect.GetSize();
  4821. }
  4822. bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
  4823. {
  4824. ImGuiContext& g = *GImGui;
  4825. ImGuiWindow* parent_window = g.CurrentWindow;
  4826. flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;
  4827. flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
  4828. // Size
  4829. const ImVec2 content_avail = GetContentRegionAvail();
  4830. ImVec2 size = ImFloor(size_arg);
  4831. const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
  4832. if (size.x <= 0.0f)
  4833. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
  4834. if (size.y <= 0.0f)
  4835. size.y = ImMax(content_avail.y + size.y, 4.0f);
  4836. SetNextWindowSize(size);
  4837. // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
  4838. const char* temp_window_name;
  4839. if (name)
  4840. ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
  4841. else
  4842. ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
  4843. const float backup_border_size = g.Style.ChildBorderSize;
  4844. if (!border)
  4845. g.Style.ChildBorderSize = 0.0f;
  4846. bool ret = Begin(temp_window_name, NULL, flags);
  4847. g.Style.ChildBorderSize = backup_border_size;
  4848. ImGuiWindow* child_window = g.CurrentWindow;
  4849. child_window->ChildId = id;
  4850. child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
  4851. // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
  4852. // While this is not really documented/defined, it seems that the expected thing to do.
  4853. if (child_window->BeginCount == 1)
  4854. parent_window->DC.CursorPos = child_window->Pos;
  4855. // Process navigation-in immediately so NavInit can run on first frame
  4856. if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
  4857. {
  4858. FocusWindow(child_window);
  4859. NavInitWindow(child_window, false);
  4860. SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
  4861. g.ActiveIdSource = ImGuiInputSource_Nav;
  4862. }
  4863. return ret;
  4864. }
  4865. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4866. {
  4867. ImGuiWindow* window = GetCurrentWindow();
  4868. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  4869. }
  4870. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4871. {
  4872. IM_ASSERT(id != 0);
  4873. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  4874. }
  4875. void ImGui::EndChild()
  4876. {
  4877. ImGuiContext& g = *GImGui;
  4878. ImGuiWindow* window = g.CurrentWindow;
  4879. IM_ASSERT(g.WithinEndChild == false);
  4880. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
  4881. g.WithinEndChild = true;
  4882. if (window->BeginCount > 1)
  4883. {
  4884. End();
  4885. }
  4886. else
  4887. {
  4888. ImVec2 sz = window->Size;
  4889. if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  4890. sz.x = ImMax(4.0f, sz.x);
  4891. if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
  4892. sz.y = ImMax(4.0f, sz.y);
  4893. End();
  4894. ImGuiWindow* parent_window = g.CurrentWindow;
  4895. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  4896. ItemSize(sz);
  4897. if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
  4898. {
  4899. ItemAdd(bb, window->ChildId);
  4900. RenderNavHighlight(bb, window->ChildId);
  4901. // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
  4902. if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
  4903. RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
  4904. }
  4905. else
  4906. {
  4907. // Not navigable into
  4908. ItemAdd(bb, 0);
  4909. }
  4910. if (g.HoveredWindow == window)
  4911. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
  4912. }
  4913. g.WithinEndChild = false;
  4914. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  4915. }
  4916. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  4917. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  4918. {
  4919. ImGuiContext& g = *GImGui;
  4920. const ImGuiStyle& style = g.Style;
  4921. PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
  4922. PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
  4923. PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
  4924. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  4925. bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  4926. PopStyleVar(3);
  4927. PopStyleColor();
  4928. return ret;
  4929. }
  4930. void ImGui::EndChildFrame()
  4931. {
  4932. EndChild();
  4933. }
  4934. static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
  4935. {
  4936. window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
  4937. window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
  4938. window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
  4939. }
  4940. ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
  4941. {
  4942. ImGuiContext& g = *GImGui;
  4943. return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
  4944. }
  4945. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  4946. {
  4947. ImGuiID id = ImHashStr(name);
  4948. return FindWindowByID(id);
  4949. }
  4950. static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
  4951. {
  4952. window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y));
  4953. if (settings->Size.x > 0 && settings->Size.y > 0)
  4954. window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
  4955. window->Collapsed = settings->Collapsed;
  4956. }
  4957. static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
  4958. {
  4959. ImGuiContext& g = *GImGui;
  4960. const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
  4961. const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
  4962. if ((just_created || child_flag_changed) && !new_is_explicit_child)
  4963. {
  4964. IM_ASSERT(!g.WindowsFocusOrder.contains(window));
  4965. g.WindowsFocusOrder.push_back(window);
  4966. window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
  4967. }
  4968. else if (!just_created && child_flag_changed && new_is_explicit_child)
  4969. {
  4970. IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
  4971. for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
  4972. g.WindowsFocusOrder[n]->FocusOrder--;
  4973. g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
  4974. window->FocusOrder = -1;
  4975. }
  4976. window->IsExplicitChild = new_is_explicit_child;
  4977. }
  4978. static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
  4979. {
  4980. ImGuiContext& g = *GImGui;
  4981. //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
  4982. // Create window the first time
  4983. ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
  4984. window->Flags = flags;
  4985. g.WindowsById.SetVoidPtr(window->ID, window);
  4986. // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  4987. const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  4988. window->Pos = main_viewport->Pos + ImVec2(60, 60);
  4989. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  4990. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4991. if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
  4992. {
  4993. // Retrieve settings from .ini file
  4994. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  4995. SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
  4996. ApplyWindowSettings(window, settings);
  4997. }
  4998. window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
  4999. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  5000. {
  5001. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  5002. window->AutoFitOnlyGrows = false;
  5003. }
  5004. else
  5005. {
  5006. if (window->Size.x <= 0.0f)
  5007. window->AutoFitFramesX = 2;
  5008. if (window->Size.y <= 0.0f)
  5009. window->AutoFitFramesY = 2;
  5010. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  5011. }
  5012. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  5013. g.Windows.push_front(window); // Quite slow but rare and only once
  5014. else
  5015. g.Windows.push_back(window);
  5016. return window;
  5017. }
  5018. static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
  5019. {
  5020. ImGuiContext& g = *GImGui;
  5021. ImVec2 new_size = size_desired;
  5022. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
  5023. {
  5024. // Using -1,-1 on either X/Y axis to preserve the current size.
  5025. ImRect cr = g.NextWindowData.SizeConstraintRect;
  5026. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  5027. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  5028. if (g.NextWindowData.SizeCallback)
  5029. {
  5030. ImGuiSizeCallbackData data;
  5031. data.UserData = g.NextWindowData.SizeCallbackUserData;
  5032. data.Pos = window->Pos;
  5033. data.CurrentSize = window->SizeFull;
  5034. data.DesiredSize = new_size;
  5035. g.NextWindowData.SizeCallback(&data);
  5036. new_size = data.DesiredSize;
  5037. }
  5038. new_size.x = IM_FLOOR(new_size.x);
  5039. new_size.y = IM_FLOOR(new_size.y);
  5040. }
  5041. // Minimum size
  5042. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  5043. {
  5044. ImGuiWindow* window_for_height = window;
  5045. const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight();
  5046. new_size = ImMax(new_size, g.Style.WindowMinSize);
  5047. new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
  5048. }
  5049. return new_size;
  5050. }
  5051. static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
  5052. {
  5053. bool preserve_old_content_sizes = false;
  5054. if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  5055. preserve_old_content_sizes = true;
  5056. else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
  5057. preserve_old_content_sizes = true;
  5058. if (preserve_old_content_sizes)
  5059. {
  5060. *content_size_current = window->ContentSize;
  5061. *content_size_ideal = window->ContentSizeIdeal;
  5062. return;
  5063. }
  5064. content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
  5065. content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
  5066. content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
  5067. content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
  5068. }
  5069. static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
  5070. {
  5071. ImGuiContext& g = *GImGui;
  5072. ImGuiStyle& style = g.Style;
  5073. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  5074. ImVec2 size_pad = window->WindowPadding * 2.0f;
  5075. ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height);
  5076. if (window->Flags & ImGuiWindowFlags_Tooltip)
  5077. {
  5078. // Tooltip always resize
  5079. return size_desired;
  5080. }
  5081. else
  5082. {
  5083. // Maximum window size is determined by the viewport size or monitor size
  5084. const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
  5085. const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
  5086. ImVec2 size_min = style.WindowMinSize;
  5087. if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
  5088. size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
  5089. // FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows?
  5090. ImVec2 avail_size = ImGui::GetMainViewport()->Size;
  5091. ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
  5092. // When the window cannot fit all contents (either because of constraints, either because screen is too small),
  5093. // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
  5094. ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  5095. bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - 0.0f < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
  5096. bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_up_height < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
  5097. if (will_have_scrollbar_x)
  5098. size_auto_fit.y += style.ScrollbarSize;
  5099. if (will_have_scrollbar_y)
  5100. size_auto_fit.x += style.ScrollbarSize;
  5101. return size_auto_fit;
  5102. }
  5103. }
  5104. ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
  5105. {
  5106. ImVec2 size_contents_current;
  5107. ImVec2 size_contents_ideal;
  5108. CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
  5109. ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
  5110. ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  5111. return size_final;
  5112. }
  5113. static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
  5114. {
  5115. if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  5116. return ImGuiCol_PopupBg;
  5117. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  5118. return ImGuiCol_ChildBg;
  5119. return ImGuiCol_WindowBg;
  5120. }
  5121. static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
  5122. {
  5123. ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
  5124. ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
  5125. ImVec2 size_expected = pos_max - pos_min;
  5126. ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
  5127. *out_pos = pos_min;
  5128. if (corner_norm.x == 0.0f)
  5129. out_pos->x -= (size_constrained.x - size_expected.x);
  5130. if (corner_norm.y == 0.0f)
  5131. out_pos->y -= (size_constrained.y - size_expected.y);
  5132. *out_size = size_constrained;
  5133. }
  5134. // Data for resizing from corner
  5135. struct ImGuiResizeGripDef
  5136. {
  5137. ImVec2 CornerPosN;
  5138. ImVec2 InnerDir;
  5139. int AngleMin12, AngleMax12;
  5140. };
  5141. static const ImGuiResizeGripDef resize_grip_def[4] =
  5142. {
  5143. { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
  5144. { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
  5145. { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
  5146. { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
  5147. };
  5148. // Data for resizing from borders
  5149. struct ImGuiResizeBorderDef
  5150. {
  5151. ImVec2 InnerDir;
  5152. ImVec2 SegmentN1, SegmentN2;
  5153. float OuterAngle;
  5154. };
  5155. static const ImGuiResizeBorderDef resize_border_def[4] =
  5156. {
  5157. { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
  5158. { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
  5159. { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
  5160. { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
  5161. };
  5162. static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
  5163. {
  5164. ImRect rect = window->Rect();
  5165. if (thickness == 0.0f)
  5166. rect.Max -= ImVec2(1, 1);
  5167. if (border_n == ImGuiDir_Left) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); }
  5168. if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); }
  5169. if (border_n == ImGuiDir_Up) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); }
  5170. if (border_n == ImGuiDir_Down) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); }
  5171. IM_ASSERT(0);
  5172. return ImRect();
  5173. }
  5174. // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
  5175. ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
  5176. {
  5177. IM_ASSERT(n >= 0 && n < 4);
  5178. ImGuiID id = window->ID;
  5179. id = ImHashStr("#RESIZE", 0, id);
  5180. id = ImHashData(&n, sizeof(int), id);
  5181. return id;
  5182. }
  5183. // Borders (Left, Right, Up, Down)
  5184. ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
  5185. {
  5186. IM_ASSERT(dir >= 0 && dir < 4);
  5187. int n = (int)dir + 4;
  5188. ImGuiID id = window->ID;
  5189. id = ImHashStr("#RESIZE", 0, id);
  5190. id = ImHashData(&n, sizeof(int), id);
  5191. return id;
  5192. }
  5193. // Handle resize for: Resize Grips, Borders, Gamepad
  5194. // Return true when using auto-fit (double-click on resize grip)
  5195. static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
  5196. {
  5197. ImGuiContext& g = *GImGui;
  5198. ImGuiWindowFlags flags = window->Flags;
  5199. if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5200. return false;
  5201. if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
  5202. return false;
  5203. bool ret_auto_fit = false;
  5204. const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
  5205. const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  5206. const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
  5207. const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
  5208. ImVec2 pos_target(FLT_MAX, FLT_MAX);
  5209. ImVec2 size_target(FLT_MAX, FLT_MAX);
  5210. // Resize grips and borders are on layer 1
  5211. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  5212. // Manual resize grips
  5213. PushID("#RESIZE");
  5214. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5215. {
  5216. const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
  5217. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
  5218. // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
  5219. bool hovered, held;
  5220. ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
  5221. if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
  5222. if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
  5223. ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
  5224. KeepAliveID(resize_grip_id);
  5225. ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  5226. //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
  5227. if (hovered || held)
  5228. g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  5229. if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
  5230. {
  5231. // Manual auto-fit when double-clicking
  5232. size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  5233. ret_auto_fit = true;
  5234. ClearActiveID();
  5235. }
  5236. else if (held)
  5237. {
  5238. // Resize from any of the four corners
  5239. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  5240. ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
  5241. ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
  5242. ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
  5243. corner_target = ImClamp(corner_target, clamp_min, clamp_max);
  5244. CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
  5245. }
  5246. // Only lower-left grip is visible before hovering/activating
  5247. if (resize_grip_n == 0 || held || hovered)
  5248. resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  5249. }
  5250. for (int border_n = 0; border_n < resize_border_count; border_n++)
  5251. {
  5252. const ImGuiResizeBorderDef& def = resize_border_def[border_n];
  5253. const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  5254. bool hovered, held;
  5255. ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
  5256. ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
  5257. KeepAliveID(border_id);
  5258. ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  5259. //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
  5260. if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
  5261. {
  5262. g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
  5263. if (held)
  5264. *border_held = border_n;
  5265. }
  5266. if (held)
  5267. {
  5268. ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
  5269. ImVec2 clamp_max(border_n == ImGuiDir_Left ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? visibility_rect.Max.y : +FLT_MAX);
  5270. ImVec2 border_target = window->Pos;
  5271. border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
  5272. border_target = ImClamp(border_target, clamp_min, clamp_max);
  5273. CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
  5274. }
  5275. }
  5276. PopID();
  5277. // Restore nav layer
  5278. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5279. // Navigation resize (keyboard/gamepad)
  5280. // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
  5281. // Not even sure the callback works here.
  5282. if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
  5283. {
  5284. ImVec2 nav_resize_dir;
  5285. if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
  5286. nav_resize_dir = GetKeyVector2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
  5287. if (g.NavInputSource == ImGuiInputSource_Gamepad)
  5288. nav_resize_dir = GetKeyVector2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
  5289. if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
  5290. {
  5291. const float NAV_RESIZE_SPEED = 600.0f;
  5292. const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
  5293. g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
  5294. g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, visibility_rect.Min - window->Pos - window->Size); // We need Pos+Size >= visibility_rect.Min, so Size >= visibility_rect.Min - Pos, so size_delta >= visibility_rect.Min - window->Pos - window->Size
  5295. g.NavWindowingToggleLayer = false;
  5296. g.NavDisableMouseHover = true;
  5297. resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
  5298. ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
  5299. if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
  5300. {
  5301. // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
  5302. size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
  5303. g.NavWindowingAccumDeltaSize -= accum_floored;
  5304. }
  5305. }
  5306. }
  5307. // Apply back modified position/size to window
  5308. if (size_target.x != FLT_MAX)
  5309. {
  5310. window->SizeFull = size_target;
  5311. MarkIniSettingsDirty(window);
  5312. }
  5313. if (pos_target.x != FLT_MAX)
  5314. {
  5315. window->Pos = ImFloor(pos_target);
  5316. MarkIniSettingsDirty(window);
  5317. }
  5318. window->Size = window->SizeFull;
  5319. return ret_auto_fit;
  5320. }
  5321. static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)
  5322. {
  5323. ImGuiContext& g = *GImGui;
  5324. ImVec2 size_for_clamping = window->Size;
  5325. if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5326. size_for_clamping.y = window->TitleBarHeight();
  5327. window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
  5328. }
  5329. static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
  5330. {
  5331. ImGuiContext& g = *GImGui;
  5332. float rounding = window->WindowRounding;
  5333. float border_size = window->WindowBorderSize;
  5334. if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
  5335. window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  5336. int border_held = window->ResizeBorderHeld;
  5337. if (border_held != -1)
  5338. {
  5339. const ImGuiResizeBorderDef& def = resize_border_def[border_held];
  5340. ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
  5341. window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
  5342. window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
  5343. window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
  5344. }
  5345. if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5346. {
  5347. float y = window->Pos.y + window->TitleBarHeight() - 1;
  5348. window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
  5349. }
  5350. }
  5351. // Draw background and borders
  5352. // Draw and handle scrollbars
  5353. void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
  5354. {
  5355. ImGuiContext& g = *GImGui;
  5356. ImGuiStyle& style = g.Style;
  5357. ImGuiWindowFlags flags = window->Flags;
  5358. // Ensure that ScrollBar doesn't read last frame's SkipItems
  5359. IM_ASSERT(window->BeginCount == 0);
  5360. window->SkipItems = false;
  5361. // Draw window + handle manual resize
  5362. // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
  5363. const float window_rounding = window->WindowRounding;
  5364. const float window_border_size = window->WindowBorderSize;
  5365. if (window->Collapsed)
  5366. {
  5367. // Title bar only
  5368. float backup_border_size = style.FrameBorderSize;
  5369. g.Style.FrameBorderSize = window->WindowBorderSize;
  5370. ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
  5371. RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
  5372. g.Style.FrameBorderSize = backup_border_size;
  5373. }
  5374. else
  5375. {
  5376. // Window background
  5377. if (!(flags & ImGuiWindowFlags_NoBackground))
  5378. {
  5379. ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
  5380. bool override_alpha = false;
  5381. float alpha = 1.0f;
  5382. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
  5383. {
  5384. alpha = g.NextWindowData.BgAlphaVal;
  5385. override_alpha = true;
  5386. }
  5387. if (override_alpha)
  5388. bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
  5389. window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
  5390. }
  5391. // Title bar
  5392. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  5393. {
  5394. ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  5395. window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
  5396. }
  5397. // Menu bar
  5398. if (flags & ImGuiWindowFlags_MenuBar)
  5399. {
  5400. ImRect menu_bar_rect = window->MenuBarRect();
  5401. 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.
  5402. window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
  5403. if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
  5404. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  5405. }
  5406. // Scrollbars
  5407. if (window->ScrollbarX)
  5408. Scrollbar(ImGuiAxis_X);
  5409. if (window->ScrollbarY)
  5410. Scrollbar(ImGuiAxis_Y);
  5411. // Render resize grips (after their input handling so we don't have a frame of latency)
  5412. if (!(flags & ImGuiWindowFlags_NoResize))
  5413. {
  5414. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5415. {
  5416. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  5417. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
  5418. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
  5419. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
  5420. 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);
  5421. window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
  5422. }
  5423. }
  5424. // Borders
  5425. RenderWindowOuterBorders(window);
  5426. }
  5427. }
  5428. // Render title text, collapse button, close button
  5429. void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
  5430. {
  5431. ImGuiContext& g = *GImGui;
  5432. ImGuiStyle& style = g.Style;
  5433. ImGuiWindowFlags flags = window->Flags;
  5434. const bool has_close_button = (p_open != NULL);
  5435. const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
  5436. // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
  5437. // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
  5438. const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
  5439. g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
  5440. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  5441. // Layout buttons
  5442. // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
  5443. float pad_l = style.FramePadding.x;
  5444. float pad_r = style.FramePadding.x;
  5445. float button_sz = g.FontSize;
  5446. ImVec2 close_button_pos;
  5447. ImVec2 collapse_button_pos;
  5448. if (has_close_button)
  5449. {
  5450. pad_r += button_sz;
  5451. close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5452. }
  5453. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
  5454. {
  5455. pad_r += button_sz;
  5456. collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5457. }
  5458. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
  5459. {
  5460. collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
  5461. pad_l += button_sz;
  5462. }
  5463. // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
  5464. if (has_collapse_button)
  5465. if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
  5466. window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
  5467. // Close button
  5468. if (has_close_button)
  5469. if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
  5470. *p_open = false;
  5471. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5472. g.CurrentItemFlags = item_flags_backup;
  5473. // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
  5474. // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
  5475. const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
  5476. const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
  5477. // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
  5478. // while uncentered title text will still reach edges correctly.
  5479. if (pad_l > style.FramePadding.x)
  5480. pad_l += g.Style.ItemInnerSpacing.x;
  5481. if (pad_r > style.FramePadding.x)
  5482. pad_r += g.Style.ItemInnerSpacing.x;
  5483. if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
  5484. {
  5485. float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
  5486. float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
  5487. pad_l = ImMax(pad_l, pad_extend * centerness);
  5488. pad_r = ImMax(pad_r, pad_extend * centerness);
  5489. }
  5490. ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
  5491. ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
  5492. if (flags & ImGuiWindowFlags_UnsavedDocument)
  5493. {
  5494. ImVec2 marker_pos;
  5495. marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
  5496. marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
  5497. if (marker_pos.x > layout_r.Min.x)
  5498. {
  5499. RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
  5500. clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
  5501. }
  5502. }
  5503. //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
  5504. //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
  5505. RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
  5506. }
  5507. void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
  5508. {
  5509. window->ParentWindow = parent_window;
  5510. window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
  5511. if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  5512. window->RootWindow = parent_window->RootWindow;
  5513. if (parent_window && (flags & ImGuiWindowFlags_Popup))
  5514. window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
  5515. if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  5516. window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
  5517. while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
  5518. {
  5519. IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
  5520. window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
  5521. }
  5522. }
  5523. // When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
  5524. // should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
  5525. // In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
  5526. // - Window // FindBlockingModal() returns Modal1
  5527. // - Window // .. returns Modal1
  5528. // - Modal1 // .. returns Modal2
  5529. // - Window // .. returns Modal2
  5530. // - Window // .. returns Modal2
  5531. // - Modal2 // .. returns Modal2
  5532. static ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
  5533. {
  5534. ImGuiContext& g = *GImGui;
  5535. if (g.OpenPopupStack.Size <= 0)
  5536. return NULL;
  5537. // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
  5538. for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
  5539. {
  5540. ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
  5541. if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
  5542. continue;
  5543. if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
  5544. continue;
  5545. if (IsWindowWithinBeginStackOf(window, popup_window)) // Window is rendered over last modal, no render order change needed.
  5546. break;
  5547. for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
  5548. if (IsWindowWithinBeginStackOf(window, parent))
  5549. return popup_window; // Place window above its begin stack parent.
  5550. }
  5551. return NULL;
  5552. }
  5553. // Push a new Dear ImGui window to add widgets to.
  5554. // - 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.
  5555. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  5556. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  5557. // 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.
  5558. // - 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.
  5559. // - 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.
  5560. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  5561. {
  5562. ImGuiContext& g = *GImGui;
  5563. const ImGuiStyle& style = g.Style;
  5564. IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
  5565. IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
  5566. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  5567. // Find or create
  5568. ImGuiWindow* window = FindWindowByName(name);
  5569. const bool window_just_created = (window == NULL);
  5570. if (window_just_created)
  5571. window = CreateNewWindow(name, flags);
  5572. // Automatically disable manual moving/resizing when NoInputs is set
  5573. if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
  5574. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  5575. if (flags & ImGuiWindowFlags_NavFlattened)
  5576. IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
  5577. const int current_frame = g.FrameCount;
  5578. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  5579. window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
  5580. // Update the Appearing flag
  5581. bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  5582. if (flags & ImGuiWindowFlags_Popup)
  5583. {
  5584. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5585. window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
  5586. window_just_activated_by_user |= (window != popup_ref.Window);
  5587. }
  5588. window->Appearing = window_just_activated_by_user;
  5589. if (window->Appearing)
  5590. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
  5591. // Update Flags, LastFrameActive, BeginOrderXXX fields
  5592. if (first_begin_of_the_frame)
  5593. {
  5594. UpdateWindowInFocusOrderList(window, window_just_created, flags);
  5595. window->Flags = (ImGuiWindowFlags)flags;
  5596. window->LastFrameActive = current_frame;
  5597. window->LastTimeActive = (float)g.Time;
  5598. window->BeginOrderWithinParent = 0;
  5599. window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
  5600. }
  5601. else
  5602. {
  5603. flags = window->Flags;
  5604. }
  5605. // 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
  5606. ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
  5607. ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
  5608. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  5609. // We allow window memory to be compacted so recreate the base stack when needed.
  5610. if (window->IDStack.Size == 0)
  5611. window->IDStack.push_back(window->ID);
  5612. // Add to stack
  5613. // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
  5614. g.CurrentWindow = window;
  5615. ImGuiWindowStackData window_stack_data;
  5616. window_stack_data.Window = window;
  5617. window_stack_data.ParentLastItemDataBackup = g.LastItemData;
  5618. window_stack_data.StackSizesOnBegin.SetToCurrentState();
  5619. g.CurrentWindowStack.push_back(window_stack_data);
  5620. g.CurrentWindow = NULL;
  5621. if (flags & ImGuiWindowFlags_ChildMenu)
  5622. g.BeginMenuCount++;
  5623. if (flags & ImGuiWindowFlags_Popup)
  5624. {
  5625. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5626. popup_ref.Window = window;
  5627. popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
  5628. g.BeginPopupStack.push_back(popup_ref);
  5629. window->PopupId = popup_ref.PopupId;
  5630. }
  5631. // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
  5632. if (first_begin_of_the_frame)
  5633. {
  5634. UpdateWindowParentAndRootLinks(window, flags, parent_window);
  5635. window->ParentWindowInBeginStack = parent_window_in_stack;
  5636. }
  5637. // Process SetNextWindow***() calls
  5638. // (FIXME: Consider splitting the HasXXX flags into X/Y components
  5639. bool window_pos_set_by_api = false;
  5640. bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
  5641. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
  5642. {
  5643. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
  5644. if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
  5645. {
  5646. // May be processed on the next frame if this is our first frame and we are measuring size
  5647. // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
  5648. window->SetWindowPosVal = g.NextWindowData.PosVal;
  5649. window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
  5650. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5651. }
  5652. else
  5653. {
  5654. SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
  5655. }
  5656. }
  5657. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
  5658. {
  5659. window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
  5660. window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
  5661. SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
  5662. }
  5663. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
  5664. {
  5665. if (g.NextWindowData.ScrollVal.x >= 0.0f)
  5666. {
  5667. window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
  5668. window->ScrollTargetCenterRatio.x = 0.0f;
  5669. }
  5670. if (g.NextWindowData.ScrollVal.y >= 0.0f)
  5671. {
  5672. window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
  5673. window->ScrollTargetCenterRatio.y = 0.0f;
  5674. }
  5675. }
  5676. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
  5677. window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
  5678. else if (first_begin_of_the_frame)
  5679. window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
  5680. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
  5681. SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
  5682. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
  5683. FocusWindow(window);
  5684. if (window->Appearing)
  5685. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
  5686. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  5687. if (first_begin_of_the_frame)
  5688. {
  5689. // Initialize
  5690. const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
  5691. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
  5692. window->Active = true;
  5693. window->HasCloseButton = (p_open != NULL);
  5694. window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
  5695. window->IDStack.resize(1);
  5696. window->DrawList->_ResetForNewFrame();
  5697. window->DC.CurrentTableIdx = -1;
  5698. // Restore buffer capacity when woken from a compacted state, to avoid
  5699. if (window->MemoryCompacted)
  5700. GcAwakeTransientWindowBuffers(window);
  5701. // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
  5702. // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
  5703. bool window_title_visible_elsewhere = false;
  5704. if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
  5705. window_title_visible_elsewhere = true;
  5706. if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
  5707. {
  5708. size_t buf_len = (size_t)window->NameBufLen;
  5709. window->Name = ImStrdupcpy(window->Name, &buf_len, name);
  5710. window->NameBufLen = (int)buf_len;
  5711. }
  5712. // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
  5713. // Update contents size from last frame for auto-fitting (or use explicit size)
  5714. CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
  5715. if (window->HiddenFramesCanSkipItems > 0)
  5716. window->HiddenFramesCanSkipItems--;
  5717. if (window->HiddenFramesCannotSkipItems > 0)
  5718. window->HiddenFramesCannotSkipItems--;
  5719. if (window->HiddenFramesForRenderOnly > 0)
  5720. window->HiddenFramesForRenderOnly--;
  5721. // Hide new windows for one frame until they calculate their size
  5722. if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
  5723. window->HiddenFramesCannotSkipItems = 1;
  5724. // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
  5725. // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
  5726. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
  5727. {
  5728. window->HiddenFramesCannotSkipItems = 1;
  5729. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  5730. {
  5731. if (!window_size_x_set_by_api)
  5732. window->Size.x = window->SizeFull.x = 0.f;
  5733. if (!window_size_y_set_by_api)
  5734. window->Size.y = window->SizeFull.y = 0.f;
  5735. window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
  5736. }
  5737. }
  5738. // SELECT VIEWPORT
  5739. // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
  5740. ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
  5741. SetWindowViewport(window, viewport);
  5742. SetCurrentWindow(window);
  5743. // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
  5744. if (flags & ImGuiWindowFlags_ChildWindow)
  5745. window->WindowBorderSize = style.ChildBorderSize;
  5746. else
  5747. window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
  5748. window->WindowPadding = style.WindowPadding;
  5749. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
  5750. window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
  5751. // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
  5752. window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
  5753. window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
  5754. bool use_current_size_for_scrollbar_x = window_just_created;
  5755. bool use_current_size_for_scrollbar_y = window_just_created;
  5756. // Collapse window by double-clicking on title bar
  5757. // 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
  5758. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  5759. {
  5760. // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
  5761. ImRect title_bar_rect = window->TitleBarRect();
  5762. if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
  5763. window->WantCollapseToggle = true;
  5764. if (window->WantCollapseToggle)
  5765. {
  5766. window->Collapsed = !window->Collapsed;
  5767. if (!window->Collapsed)
  5768. use_current_size_for_scrollbar_y = true;
  5769. MarkIniSettingsDirty(window);
  5770. }
  5771. }
  5772. else
  5773. {
  5774. window->Collapsed = false;
  5775. }
  5776. window->WantCollapseToggle = false;
  5777. // SIZE
  5778. // Calculate auto-fit size, handle automatic resize
  5779. const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
  5780. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
  5781. {
  5782. // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
  5783. if (!window_size_x_set_by_api)
  5784. {
  5785. window->SizeFull.x = size_auto_fit.x;
  5786. use_current_size_for_scrollbar_x = true;
  5787. }
  5788. if (!window_size_y_set_by_api)
  5789. {
  5790. window->SizeFull.y = size_auto_fit.y;
  5791. use_current_size_for_scrollbar_y = true;
  5792. }
  5793. }
  5794. else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5795. {
  5796. // Auto-fit may only grow window during the first few frames
  5797. // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  5798. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
  5799. {
  5800. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  5801. use_current_size_for_scrollbar_x = true;
  5802. }
  5803. if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
  5804. {
  5805. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  5806. use_current_size_for_scrollbar_y = true;
  5807. }
  5808. if (!window->Collapsed)
  5809. MarkIniSettingsDirty(window);
  5810. }
  5811. // Apply minimum/maximum window size constraints and final size
  5812. window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
  5813. window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
  5814. // Decoration size
  5815. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  5816. // POSITION
  5817. // Popup latch its initial position, will position itself when it appears next frame
  5818. if (window_just_activated_by_user)
  5819. {
  5820. window->AutoPosLastDirection = ImGuiDir_None;
  5821. if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
  5822. window->Pos = g.BeginPopupStack.back().OpenPopupPos;
  5823. }
  5824. // Position child window
  5825. if (flags & ImGuiWindowFlags_ChildWindow)
  5826. {
  5827. IM_ASSERT(parent_window && parent_window->Active);
  5828. window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
  5829. parent_window->DC.ChildWindows.push_back(window);
  5830. if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
  5831. window->Pos = parent_window->DC.CursorPos;
  5832. }
  5833. const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
  5834. if (window_pos_with_pivot)
  5835. SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
  5836. else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
  5837. window->Pos = FindBestWindowPosForPopup(window);
  5838. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
  5839. window->Pos = FindBestWindowPosForPopup(window);
  5840. else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
  5841. window->Pos = FindBestWindowPosForPopup(window);
  5842. // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
  5843. // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
  5844. ImRect viewport_rect(viewport->GetMainRect());
  5845. ImRect viewport_work_rect(viewport->GetWorkRect());
  5846. ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  5847. ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
  5848. // Clamp position/size so window stays visible within its viewport or monitor
  5849. // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
  5850. if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  5851. if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
  5852. ClampWindowRect(window, visibility_rect);
  5853. window->Pos = ImFloor(window->Pos);
  5854. // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
  5855. // Large values tend to lead to variety of artifacts and are not recommended.
  5856. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
  5857. // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
  5858. //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5859. // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
  5860. // Apply window focus (new and reactivated windows are moved to front)
  5861. bool want_focus = false;
  5862. if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  5863. {
  5864. if (flags & ImGuiWindowFlags_Popup)
  5865. want_focus = true;
  5866. else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
  5867. want_focus = true;
  5868. ImGuiWindow* modal = GetTopMostPopupModal();
  5869. if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))
  5870. {
  5871. // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.
  5872. // Since window is not focused it would reappear at the same display position like the last time it was visible.
  5873. // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.
  5874. // Position window behind a modal that is not a begin-parent of this window.
  5875. want_focus = false;
  5876. if (window == window->RootWindow)
  5877. {
  5878. ImGuiWindow* blocking_modal = FindBlockingModal(window);
  5879. IM_ASSERT(blocking_modal != NULL);
  5880. BringWindowToDisplayBehind(window, blocking_modal);
  5881. }
  5882. }
  5883. }
  5884. // [Test Engine] Register whole window in the item system
  5885. #ifdef IMGUI_ENABLE_TEST_ENGINE
  5886. if (g.TestEngineHookItems)
  5887. {
  5888. IM_ASSERT(window->IDStack.Size == 1);
  5889. window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
  5890. IMGUI_TEST_ENGINE_ITEM_ADD(window->Rect(), window->ID);
  5891. IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
  5892. window->IDStack.Size = 1;
  5893. }
  5894. #endif
  5895. // Handle manual resize: Resize Grips, Borders, Gamepad
  5896. int border_held = -1;
  5897. ImU32 resize_grip_col[4] = {};
  5898. const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
  5899. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  5900. if (!window->Collapsed)
  5901. if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
  5902. use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
  5903. window->ResizeBorderHeld = (signed char)border_held;
  5904. // SCROLLBAR VISIBILITY
  5905. // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
  5906. if (!window->Collapsed)
  5907. {
  5908. // When reading the current size we need to read it after size constraints have been applied.
  5909. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
  5910. ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
  5911. ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
  5912. ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
  5913. float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
  5914. float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
  5915. //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
  5916. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
  5917. window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
  5918. if (window->ScrollbarX && !window->ScrollbarY)
  5919. window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
  5920. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  5921. }
  5922. // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
  5923. // Update various regions. Variables they depend on should be set above in this function.
  5924. // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
  5925. // Outer rectangle
  5926. // Not affected by window border size. Used by:
  5927. // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
  5928. // - Begin() initial clipping rect for drawing window background and borders.
  5929. // - Begin() clipping whole child
  5930. const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
  5931. const ImRect outer_rect = window->Rect();
  5932. const ImRect title_bar_rect = window->TitleBarRect();
  5933. window->OuterRectClipped = outer_rect;
  5934. window->OuterRectClipped.ClipWith(host_rect);
  5935. // Inner rectangle
  5936. // Not affected by window border size. Used by:
  5937. // - InnerClipRect
  5938. // - ScrollToRectEx()
  5939. // - NavUpdatePageUpPageDown()
  5940. // - Scrollbar()
  5941. window->InnerRect.Min.x = window->Pos.x;
  5942. window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
  5943. window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
  5944. window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
  5945. // Inner clipping rectangle.
  5946. // Will extend a little bit outside the normal work region.
  5947. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
  5948. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  5949. // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
  5950. // Affected by window/frame border size. Used by:
  5951. // - Begin() initial clip rect
  5952. float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
  5953. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5954. window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
  5955. window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5956. window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
  5957. window->InnerClipRect.ClipWithFull(host_rect);
  5958. // Default item width. Make it proportional to window size if window manually resizes
  5959. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  5960. window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
  5961. else
  5962. window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
  5963. // SCROLLING
  5964. // Lock down maximum scrolling
  5965. // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
  5966. // for right/bottom aligned items without creating a scrollbar.
  5967. window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
  5968. window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
  5969. // Apply scrolling
  5970. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  5971. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  5972. // DRAWING
  5973. // Setup draw list and outer clipping rectangle
  5974. IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
  5975. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  5976. PushClipRect(host_rect.Min, host_rect.Max, false);
  5977. // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
  5978. // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
  5979. // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
  5980. {
  5981. bool render_decorations_in_parent = false;
  5982. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
  5983. {
  5984. // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
  5985. // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
  5986. ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
  5987. bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
  5988. bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
  5989. if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
  5990. render_decorations_in_parent = true;
  5991. }
  5992. if (render_decorations_in_parent)
  5993. window->DrawList = parent_window->DrawList;
  5994. // Handle title bar, scrollbar, resize grips and resize borders
  5995. const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
  5996. const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
  5997. RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
  5998. if (render_decorations_in_parent)
  5999. window->DrawList = &window->DrawListInst;
  6000. }
  6001. // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
  6002. // Work rectangle.
  6003. // Affected by window padding and border size. Used by:
  6004. // - Columns() for right-most edge
  6005. // - TreeNode(), CollapsingHeader() for right-most edge
  6006. // - BeginTabBar() for right-most edge
  6007. const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
  6008. const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
  6009. const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
  6010. const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
  6011. window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
  6012. window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
  6013. window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
  6014. window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
  6015. window->ParentWorkRect = window->WorkRect;
  6016. // [LEGACY] Content Region
  6017. // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
  6018. // Used by:
  6019. // - Mouse wheel scrolling + many other things
  6020. window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
  6021. window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
  6022. window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
  6023. window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
  6024. // Setup drawing context
  6025. // (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.)
  6026. window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
  6027. window->DC.GroupOffset.x = 0.0f;
  6028. window->DC.ColumnsOffset.x = 0.0f;
  6029. // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
  6030. // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
  6031. double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DC.ColumnsOffset.x;
  6032. double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + decoration_up_height;
  6033. window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
  6034. window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
  6035. window->DC.CursorPos = window->DC.CursorStartPos;
  6036. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  6037. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  6038. window->DC.IdealMaxPos = window->DC.CursorStartPos;
  6039. window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
  6040. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  6041. window->DC.IsSameLine = window->DC.IsSetPos = false;
  6042. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  6043. window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
  6044. window->DC.NavLayersActiveMaskNext = 0x00;
  6045. window->DC.NavHideHighlightOneFrame = false;
  6046. window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
  6047. window->DC.MenuBarAppending = false;
  6048. window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
  6049. window->DC.TreeDepth = 0;
  6050. window->DC.TreeJumpToParentOnPopMask = 0x00;
  6051. window->DC.ChildWindows.resize(0);
  6052. window->DC.StateStorage = &window->StateStorage;
  6053. window->DC.CurrentColumns = NULL;
  6054. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  6055. window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
  6056. window->DC.ItemWidth = window->ItemWidthDefault;
  6057. window->DC.TextWrapPos = -1.0f; // disabled
  6058. window->DC.ItemWidthStack.resize(0);
  6059. window->DC.TextWrapPosStack.resize(0);
  6060. if (window->AutoFitFramesX > 0)
  6061. window->AutoFitFramesX--;
  6062. if (window->AutoFitFramesY > 0)
  6063. window->AutoFitFramesY--;
  6064. // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  6065. if (want_focus)
  6066. {
  6067. FocusWindow(window);
  6068. NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
  6069. }
  6070. // Title bar
  6071. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  6072. RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
  6073. // Clear hit test shape every frame
  6074. window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
  6075. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  6076. // 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.
  6077. // Maybe we can support CTRL+C on every element?
  6078. /*
  6079. //if (g.NavWindow == window && g.ActiveId == 0)
  6080. if (g.ActiveId == window->MoveId)
  6081. if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
  6082. LogToClipboard();
  6083. */
  6084. // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
  6085. // This is useful to allow creating context menus on title bar only, etc.
  6086. SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
  6087. // [Test Engine] Register title bar / tab
  6088. if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
  6089. IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);
  6090. }
  6091. else
  6092. {
  6093. // Append
  6094. SetCurrentWindow(window);
  6095. }
  6096. // Pull/inherit current state
  6097. window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : window->GetID("#FOCUSSCOPE"); // Inherit from parent only // -V595
  6098. PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
  6099. // 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)
  6100. window->WriteAccessed = false;
  6101. window->BeginCount++;
  6102. g.NextWindowData.ClearFlags();
  6103. // Update visibility
  6104. if (first_begin_of_the_frame)
  6105. {
  6106. if (flags & ImGuiWindowFlags_ChildWindow)
  6107. {
  6108. // Child window can be out of sight and have "negative" clip windows.
  6109. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
  6110. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  6111. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
  6112. {
  6113. const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
  6114. if (!g.LogEnabled && !nav_request)
  6115. if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
  6116. window->HiddenFramesCanSkipItems = 1;
  6117. }
  6118. // Hide along with parent or if parent is collapsed
  6119. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
  6120. window->HiddenFramesCanSkipItems = 1;
  6121. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
  6122. window->HiddenFramesCannotSkipItems = 1;
  6123. }
  6124. // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
  6125. if (style.Alpha <= 0.0f)
  6126. window->HiddenFramesCanSkipItems = 1;
  6127. // Update the Hidden flag
  6128. bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
  6129. window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
  6130. // Disable inputs for requested number of frames
  6131. if (window->DisableInputsFrames > 0)
  6132. {
  6133. window->DisableInputsFrames--;
  6134. window->Flags |= ImGuiWindowFlags_NoInputs;
  6135. }
  6136. // Update the SkipItems flag, used to early out of all items functions (no layout required)
  6137. bool skip_items = false;
  6138. if (window->Collapsed || !window->Active || hidden_regular)
  6139. if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
  6140. skip_items = true;
  6141. window->SkipItems = skip_items;
  6142. }
  6143. return !window->SkipItems;
  6144. }
  6145. void ImGui::End()
  6146. {
  6147. ImGuiContext& g = *GImGui;
  6148. ImGuiWindow* window = g.CurrentWindow;
  6149. // Error checking: verify that user hasn't called End() too many times!
  6150. if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
  6151. {
  6152. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
  6153. return;
  6154. }
  6155. IM_ASSERT(g.CurrentWindowStack.Size > 0);
  6156. // Error checking: verify that user doesn't directly call End() on a child window.
  6157. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  6158. IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
  6159. // Close anything that is open
  6160. if (window->DC.CurrentColumns)
  6161. EndColumns();
  6162. PopClipRect(); // Inner window clip rectangle
  6163. // Stop logging
  6164. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  6165. LogFinish();
  6166. if (window->DC.IsSetPos)
  6167. ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
  6168. // Pop from window stack
  6169. g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
  6170. if (window->Flags & ImGuiWindowFlags_ChildMenu)
  6171. g.BeginMenuCount--;
  6172. if (window->Flags & ImGuiWindowFlags_Popup)
  6173. g.BeginPopupStack.pop_back();
  6174. g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();
  6175. g.CurrentWindowStack.pop_back();
  6176. SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
  6177. }
  6178. void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
  6179. {
  6180. ImGuiContext& g = *GImGui;
  6181. IM_ASSERT(window == window->RootWindow);
  6182. const int cur_order = window->FocusOrder;
  6183. IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
  6184. if (g.WindowsFocusOrder.back() == window)
  6185. return;
  6186. const int new_order = g.WindowsFocusOrder.Size - 1;
  6187. for (int n = cur_order; n < new_order; n++)
  6188. {
  6189. g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
  6190. g.WindowsFocusOrder[n]->FocusOrder--;
  6191. IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
  6192. }
  6193. g.WindowsFocusOrder[new_order] = window;
  6194. window->FocusOrder = (short)new_order;
  6195. }
  6196. void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
  6197. {
  6198. ImGuiContext& g = *GImGui;
  6199. ImGuiWindow* current_front_window = g.Windows.back();
  6200. if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
  6201. return;
  6202. for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
  6203. if (g.Windows[i] == window)
  6204. {
  6205. memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
  6206. g.Windows[g.Windows.Size - 1] = window;
  6207. break;
  6208. }
  6209. }
  6210. void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
  6211. {
  6212. ImGuiContext& g = *GImGui;
  6213. if (g.Windows[0] == window)
  6214. return;
  6215. for (int i = 0; i < g.Windows.Size; i++)
  6216. if (g.Windows[i] == window)
  6217. {
  6218. memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
  6219. g.Windows[0] = window;
  6220. break;
  6221. }
  6222. }
  6223. void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
  6224. {
  6225. IM_ASSERT(window != NULL && behind_window != NULL);
  6226. ImGuiContext& g = *GImGui;
  6227. window = window->RootWindow;
  6228. behind_window = behind_window->RootWindow;
  6229. int pos_wnd = FindWindowDisplayIndex(window);
  6230. int pos_beh = FindWindowDisplayIndex(behind_window);
  6231. if (pos_wnd < pos_beh)
  6232. {
  6233. size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
  6234. memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
  6235. g.Windows[pos_beh - 1] = window;
  6236. }
  6237. else
  6238. {
  6239. size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
  6240. memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
  6241. g.Windows[pos_beh] = window;
  6242. }
  6243. }
  6244. int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
  6245. {
  6246. ImGuiContext& g = *GImGui;
  6247. return g.Windows.index_from_ptr(g.Windows.find(window));
  6248. }
  6249. // Moving window to front of display and set focus (which happens to be back of our sorted list)
  6250. void ImGui::FocusWindow(ImGuiWindow* window)
  6251. {
  6252. ImGuiContext& g = *GImGui;
  6253. if (g.NavWindow != window)
  6254. {
  6255. SetNavWindow(window);
  6256. if (window && g.NavDisableMouseHover)
  6257. g.NavMousePosDirty = true;
  6258. g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
  6259. g.NavLayer = ImGuiNavLayer_Main;
  6260. g.NavFocusScopeId = 0;
  6261. g.NavIdIsAlive = false;
  6262. // Close popups if any
  6263. ClosePopupsOverWindow(window, false);
  6264. }
  6265. // Move the root window to the top of the pile
  6266. IM_ASSERT(window == NULL || window->RootWindow != NULL);
  6267. ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
  6268. ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
  6269. // Steal active widgets. Some of the cases it triggers includes:
  6270. // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
  6271. // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
  6272. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
  6273. if (!g.ActiveIdNoClearOnFocusLoss)
  6274. ClearActiveID();
  6275. // Passing NULL allow to disable keyboard focus
  6276. if (!window)
  6277. return;
  6278. // Bring to front
  6279. BringWindowToFocusFront(focus_front_window);
  6280. if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
  6281. BringWindowToDisplayFront(display_front_window);
  6282. }
  6283. void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
  6284. {
  6285. ImGuiContext& g = *GImGui;
  6286. int start_idx = g.WindowsFocusOrder.Size - 1;
  6287. if (under_this_window != NULL)
  6288. {
  6289. // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
  6290. int offset = -1;
  6291. while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
  6292. {
  6293. under_this_window = under_this_window->ParentWindow;
  6294. offset = 0;
  6295. }
  6296. start_idx = FindWindowFocusIndex(under_this_window) + offset;
  6297. }
  6298. for (int i = start_idx; i >= 0; i--)
  6299. {
  6300. // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
  6301. ImGuiWindow* window = g.WindowsFocusOrder[i];
  6302. IM_ASSERT(window == window->RootWindow);
  6303. if (window != ignore_window && window->WasActive)
  6304. if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
  6305. {
  6306. ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
  6307. FocusWindow(focus_window);
  6308. return;
  6309. }
  6310. }
  6311. FocusWindow(NULL);
  6312. }
  6313. // Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
  6314. void ImGui::SetCurrentFont(ImFont* font)
  6315. {
  6316. ImGuiContext& g = *GImGui;
  6317. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  6318. IM_ASSERT(font->Scale > 0.0f);
  6319. g.Font = font;
  6320. g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
  6321. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  6322. ImFontAtlas* atlas = g.Font->ContainerAtlas;
  6323. g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
  6324. g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
  6325. g.DrawListSharedData.Font = g.Font;
  6326. g.DrawListSharedData.FontSize = g.FontSize;
  6327. }
  6328. void ImGui::PushFont(ImFont* font)
  6329. {
  6330. ImGuiContext& g = *GImGui;
  6331. if (!font)
  6332. font = GetDefaultFont();
  6333. SetCurrentFont(font);
  6334. g.FontStack.push_back(font);
  6335. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  6336. }
  6337. void ImGui::PopFont()
  6338. {
  6339. ImGuiContext& g = *GImGui;
  6340. g.CurrentWindow->DrawList->PopTextureID();
  6341. g.FontStack.pop_back();
  6342. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  6343. }
  6344. void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
  6345. {
  6346. ImGuiContext& g = *GImGui;
  6347. ImGuiItemFlags item_flags = g.CurrentItemFlags;
  6348. IM_ASSERT(item_flags == g.ItemFlagsStack.back());
  6349. if (enabled)
  6350. item_flags |= option;
  6351. else
  6352. item_flags &= ~option;
  6353. g.CurrentItemFlags = item_flags;
  6354. g.ItemFlagsStack.push_back(item_flags);
  6355. }
  6356. void ImGui::PopItemFlag()
  6357. {
  6358. ImGuiContext& g = *GImGui;
  6359. IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
  6360. g.ItemFlagsStack.pop_back();
  6361. g.CurrentItemFlags = g.ItemFlagsStack.back();
  6362. }
  6363. // BeginDisabled()/EndDisabled()
  6364. // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
  6365. // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
  6366. // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
  6367. // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
  6368. // - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
  6369. void ImGui::BeginDisabled(bool disabled)
  6370. {
  6371. ImGuiContext& g = *GImGui;
  6372. bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
  6373. if (!was_disabled && disabled)
  6374. {
  6375. g.DisabledAlphaBackup = g.Style.Alpha;
  6376. g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
  6377. }
  6378. if (was_disabled || disabled)
  6379. g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
  6380. g.ItemFlagsStack.push_back(g.CurrentItemFlags);
  6381. g.DisabledStackSize++;
  6382. }
  6383. void ImGui::EndDisabled()
  6384. {
  6385. ImGuiContext& g = *GImGui;
  6386. IM_ASSERT(g.DisabledStackSize > 0);
  6387. g.DisabledStackSize--;
  6388. bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
  6389. //PopItemFlag();
  6390. g.ItemFlagsStack.pop_back();
  6391. g.CurrentItemFlags = g.ItemFlagsStack.back();
  6392. if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
  6393. g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
  6394. }
  6395. // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
  6396. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  6397. {
  6398. PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
  6399. }
  6400. void ImGui::PopAllowKeyboardFocus()
  6401. {
  6402. PopItemFlag();
  6403. }
  6404. void ImGui::PushButtonRepeat(bool repeat)
  6405. {
  6406. PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
  6407. }
  6408. void ImGui::PopButtonRepeat()
  6409. {
  6410. PopItemFlag();
  6411. }
  6412. void ImGui::PushTextWrapPos(float wrap_pos_x)
  6413. {
  6414. ImGuiWindow* window = GetCurrentWindow();
  6415. window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
  6416. window->DC.TextWrapPos = wrap_pos_x;
  6417. }
  6418. void ImGui::PopTextWrapPos()
  6419. {
  6420. ImGuiWindow* window = GetCurrentWindow();
  6421. window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
  6422. window->DC.TextWrapPosStack.pop_back();
  6423. }
  6424. static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy)
  6425. {
  6426. ImGuiWindow* last_window = NULL;
  6427. while (last_window != window)
  6428. {
  6429. last_window = window;
  6430. window = window->RootWindow;
  6431. if (popup_hierarchy)
  6432. window = window->RootWindowPopupTree;
  6433. }
  6434. return window;
  6435. }
  6436. bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy)
  6437. {
  6438. ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy);
  6439. if (window_root == potential_parent)
  6440. return true;
  6441. while (window != NULL)
  6442. {
  6443. if (window == potential_parent)
  6444. return true;
  6445. if (window == window_root) // end of chain
  6446. return false;
  6447. window = window->ParentWindow;
  6448. }
  6449. return false;
  6450. }
  6451. bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
  6452. {
  6453. if (window->RootWindow == potential_parent)
  6454. return true;
  6455. while (window != NULL)
  6456. {
  6457. if (window == potential_parent)
  6458. return true;
  6459. window = window->ParentWindowInBeginStack;
  6460. }
  6461. return false;
  6462. }
  6463. bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
  6464. {
  6465. ImGuiContext& g = *GImGui;
  6466. // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
  6467. const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
  6468. if (display_layer_delta != 0)
  6469. return display_layer_delta > 0;
  6470. for (int i = g.Windows.Size - 1; i >= 0; i--)
  6471. {
  6472. ImGuiWindow* candidate_window = g.Windows[i];
  6473. if (candidate_window == potential_above)
  6474. return true;
  6475. if (candidate_window == potential_below)
  6476. return false;
  6477. }
  6478. return false;
  6479. }
  6480. bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
  6481. {
  6482. IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0); // Flags not supported by this function
  6483. ImGuiContext& g = *GImGui;
  6484. ImGuiWindow* ref_window = g.HoveredWindow;
  6485. ImGuiWindow* cur_window = g.CurrentWindow;
  6486. if (ref_window == NULL)
  6487. return false;
  6488. if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
  6489. {
  6490. IM_ASSERT(cur_window); // Not inside a Begin()/End()
  6491. const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
  6492. if (flags & ImGuiHoveredFlags_RootWindow)
  6493. cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
  6494. bool result;
  6495. if (flags & ImGuiHoveredFlags_ChildWindows)
  6496. result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
  6497. else
  6498. result = (ref_window == cur_window);
  6499. if (!result)
  6500. return false;
  6501. }
  6502. if (!IsWindowContentHoverable(ref_window, flags))
  6503. return false;
  6504. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  6505. if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
  6506. return false;
  6507. return true;
  6508. }
  6509. bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
  6510. {
  6511. ImGuiContext& g = *GImGui;
  6512. ImGuiWindow* ref_window = g.NavWindow;
  6513. ImGuiWindow* cur_window = g.CurrentWindow;
  6514. if (ref_window == NULL)
  6515. return false;
  6516. if (flags & ImGuiFocusedFlags_AnyWindow)
  6517. return true;
  6518. IM_ASSERT(cur_window); // Not inside a Begin()/End()
  6519. const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
  6520. if (flags & ImGuiHoveredFlags_RootWindow)
  6521. cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);
  6522. if (flags & ImGuiHoveredFlags_ChildWindows)
  6523. return IsWindowChildOf(ref_window, cur_window, popup_hierarchy);
  6524. else
  6525. return (ref_window == cur_window);
  6526. }
  6527. // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
  6528. // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
  6529. // If you want a window to never be focused, you may use the e.g. NoInputs flag.
  6530. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
  6531. {
  6532. return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
  6533. }
  6534. float ImGui::GetWindowWidth()
  6535. {
  6536. ImGuiWindow* window = GImGui->CurrentWindow;
  6537. return window->Size.x;
  6538. }
  6539. float ImGui::GetWindowHeight()
  6540. {
  6541. ImGuiWindow* window = GImGui->CurrentWindow;
  6542. return window->Size.y;
  6543. }
  6544. ImVec2 ImGui::GetWindowPos()
  6545. {
  6546. ImGuiContext& g = *GImGui;
  6547. ImGuiWindow* window = g.CurrentWindow;
  6548. return window->Pos;
  6549. }
  6550. void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  6551. {
  6552. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6553. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  6554. return;
  6555. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6556. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6557. window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
  6558. // Set
  6559. const ImVec2 old_pos = window->Pos;
  6560. window->Pos = ImFloor(pos);
  6561. ImVec2 offset = window->Pos - old_pos;
  6562. if (offset.x == 0.0f && offset.y == 0.0f)
  6563. return;
  6564. MarkIniSettingsDirty(window);
  6565. window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
  6566. window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
  6567. window->DC.IdealMaxPos += offset;
  6568. window->DC.CursorStartPos += offset;
  6569. }
  6570. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  6571. {
  6572. ImGuiWindow* window = GetCurrentWindowRead();
  6573. SetWindowPos(window, pos, cond);
  6574. }
  6575. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  6576. {
  6577. if (ImGuiWindow* window = FindWindowByName(name))
  6578. SetWindowPos(window, pos, cond);
  6579. }
  6580. ImVec2 ImGui::GetWindowSize()
  6581. {
  6582. ImGuiWindow* window = GetCurrentWindowRead();
  6583. return window->Size;
  6584. }
  6585. void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  6586. {
  6587. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6588. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  6589. return;
  6590. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6591. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6592. // Set
  6593. ImVec2 old_size = window->SizeFull;
  6594. window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
  6595. window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
  6596. if (size.x <= 0.0f)
  6597. window->AutoFitOnlyGrows = false;
  6598. else
  6599. window->SizeFull.x = IM_FLOOR(size.x);
  6600. if (size.y <= 0.0f)
  6601. window->AutoFitOnlyGrows = false;
  6602. else
  6603. window->SizeFull.y = IM_FLOOR(size.y);
  6604. if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
  6605. MarkIniSettingsDirty(window);
  6606. }
  6607. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  6608. {
  6609. SetWindowSize(GImGui->CurrentWindow, size, cond);
  6610. }
  6611. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  6612. {
  6613. if (ImGuiWindow* window = FindWindowByName(name))
  6614. SetWindowSize(window, size, cond);
  6615. }
  6616. void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  6617. {
  6618. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6619. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  6620. return;
  6621. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6622. // Set
  6623. window->Collapsed = collapsed;
  6624. }
  6625. void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
  6626. {
  6627. IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
  6628. window->HitTestHoleSize = ImVec2ih(size);
  6629. window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
  6630. }
  6631. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  6632. {
  6633. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  6634. }
  6635. bool ImGui::IsWindowCollapsed()
  6636. {
  6637. ImGuiWindow* window = GetCurrentWindowRead();
  6638. return window->Collapsed;
  6639. }
  6640. bool ImGui::IsWindowAppearing()
  6641. {
  6642. ImGuiWindow* window = GetCurrentWindowRead();
  6643. return window->Appearing;
  6644. }
  6645. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  6646. {
  6647. if (ImGuiWindow* window = FindWindowByName(name))
  6648. SetWindowCollapsed(window, collapsed, cond);
  6649. }
  6650. void ImGui::SetWindowFocus()
  6651. {
  6652. FocusWindow(GImGui->CurrentWindow);
  6653. }
  6654. void ImGui::SetWindowFocus(const char* name)
  6655. {
  6656. if (name)
  6657. {
  6658. if (ImGuiWindow* window = FindWindowByName(name))
  6659. FocusWindow(window);
  6660. }
  6661. else
  6662. {
  6663. FocusWindow(NULL);
  6664. }
  6665. }
  6666. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
  6667. {
  6668. ImGuiContext& g = *GImGui;
  6669. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6670. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
  6671. g.NextWindowData.PosVal = pos;
  6672. g.NextWindowData.PosPivotVal = pivot;
  6673. g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
  6674. }
  6675. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  6676. {
  6677. ImGuiContext& g = *GImGui;
  6678. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6679. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
  6680. g.NextWindowData.SizeVal = size;
  6681. g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
  6682. }
  6683. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
  6684. {
  6685. ImGuiContext& g = *GImGui;
  6686. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
  6687. g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
  6688. g.NextWindowData.SizeCallback = custom_callback;
  6689. g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
  6690. }
  6691. // Content size = inner scrollable rectangle, padded with WindowPadding.
  6692. // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
  6693. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  6694. {
  6695. ImGuiContext& g = *GImGui;
  6696. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
  6697. g.NextWindowData.ContentSizeVal = ImFloor(size);
  6698. }
  6699. void ImGui::SetNextWindowScroll(const ImVec2& scroll)
  6700. {
  6701. ImGuiContext& g = *GImGui;
  6702. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
  6703. g.NextWindowData.ScrollVal = scroll;
  6704. }
  6705. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  6706. {
  6707. ImGuiContext& g = *GImGui;
  6708. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6709. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
  6710. g.NextWindowData.CollapsedVal = collapsed;
  6711. g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
  6712. }
  6713. void ImGui::SetNextWindowFocus()
  6714. {
  6715. ImGuiContext& g = *GImGui;
  6716. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
  6717. }
  6718. void ImGui::SetNextWindowBgAlpha(float alpha)
  6719. {
  6720. ImGuiContext& g = *GImGui;
  6721. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
  6722. g.NextWindowData.BgAlphaVal = alpha;
  6723. }
  6724. ImDrawList* ImGui::GetWindowDrawList()
  6725. {
  6726. ImGuiWindow* window = GetCurrentWindow();
  6727. return window->DrawList;
  6728. }
  6729. ImFont* ImGui::GetFont()
  6730. {
  6731. return GImGui->Font;
  6732. }
  6733. float ImGui::GetFontSize()
  6734. {
  6735. return GImGui->FontSize;
  6736. }
  6737. ImVec2 ImGui::GetFontTexUvWhitePixel()
  6738. {
  6739. return GImGui->DrawListSharedData.TexUvWhitePixel;
  6740. }
  6741. void ImGui::SetWindowFontScale(float scale)
  6742. {
  6743. IM_ASSERT(scale > 0.0f);
  6744. ImGuiContext& g = *GImGui;
  6745. ImGuiWindow* window = GetCurrentWindow();
  6746. window->FontWindowScale = scale;
  6747. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  6748. }
  6749. void ImGui::ActivateItem(ImGuiID id)
  6750. {
  6751. ImGuiContext& g = *GImGui;
  6752. g.NavNextActivateId = id;
  6753. g.NavNextActivateFlags = ImGuiActivateFlags_None;
  6754. }
  6755. void ImGui::PushFocusScope(ImGuiID id)
  6756. {
  6757. ImGuiContext& g = *GImGui;
  6758. ImGuiWindow* window = g.CurrentWindow;
  6759. g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent);
  6760. window->DC.NavFocusScopeIdCurrent = id;
  6761. }
  6762. void ImGui::PopFocusScope()
  6763. {
  6764. ImGuiContext& g = *GImGui;
  6765. ImGuiWindow* window = g.CurrentWindow;
  6766. IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
  6767. window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back();
  6768. g.FocusScopeStack.pop_back();
  6769. }
  6770. // Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
  6771. void ImGui::SetKeyboardFocusHere(int offset)
  6772. {
  6773. ImGuiContext& g = *GImGui;
  6774. ImGuiWindow* window = g.CurrentWindow;
  6775. IM_ASSERT(offset >= -1); // -1 is allowed but not below
  6776. IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
  6777. // It makes sense in the vast majority of cases to never interrupt a drag and drop.
  6778. // When we refactor this function into ActivateItem() we may want to make this an option.
  6779. // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
  6780. // is also automatically dropped in the event g.ActiveId is stolen.
  6781. if (g.DragDropActive || g.MovingWindow != NULL)
  6782. {
  6783. IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere() ignored while DragDropActive!\n");
  6784. return;
  6785. }
  6786. SetNavWindow(window);
  6787. ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
  6788. NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
  6789. if (offset == -1)
  6790. {
  6791. NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
  6792. }
  6793. else
  6794. {
  6795. g.NavTabbingDir = 1;
  6796. g.NavTabbingCounter = offset + 1;
  6797. }
  6798. }
  6799. void ImGui::SetItemDefaultFocus()
  6800. {
  6801. ImGuiContext& g = *GImGui;
  6802. ImGuiWindow* window = g.CurrentWindow;
  6803. if (!window->Appearing)
  6804. return;
  6805. if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
  6806. return;
  6807. g.NavInitRequest = false;
  6808. g.NavInitResultId = g.LastItemData.ID;
  6809. g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
  6810. NavUpdateAnyRequestFlag();
  6811. // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
  6812. if (!IsItemVisible())
  6813. ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
  6814. }
  6815. void ImGui::SetStateStorage(ImGuiStorage* tree)
  6816. {
  6817. ImGuiWindow* window = GImGui->CurrentWindow;
  6818. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  6819. }
  6820. ImGuiStorage* ImGui::GetStateStorage()
  6821. {
  6822. ImGuiWindow* window = GImGui->CurrentWindow;
  6823. return window->DC.StateStorage;
  6824. }
  6825. void ImGui::PushID(const char* str_id)
  6826. {
  6827. ImGuiContext& g = *GImGui;
  6828. ImGuiWindow* window = g.CurrentWindow;
  6829. ImGuiID id = window->GetID(str_id);
  6830. window->IDStack.push_back(id);
  6831. }
  6832. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  6833. {
  6834. ImGuiContext& g = *GImGui;
  6835. ImGuiWindow* window = g.CurrentWindow;
  6836. ImGuiID id = window->GetID(str_id_begin, str_id_end);
  6837. window->IDStack.push_back(id);
  6838. }
  6839. void ImGui::PushID(const void* ptr_id)
  6840. {
  6841. ImGuiContext& g = *GImGui;
  6842. ImGuiWindow* window = g.CurrentWindow;
  6843. ImGuiID id = window->GetID(ptr_id);
  6844. window->IDStack.push_back(id);
  6845. }
  6846. void ImGui::PushID(int int_id)
  6847. {
  6848. ImGuiContext& g = *GImGui;
  6849. ImGuiWindow* window = g.CurrentWindow;
  6850. ImGuiID id = window->GetID(int_id);
  6851. window->IDStack.push_back(id);
  6852. }
  6853. // Push a given id value ignoring the ID stack as a seed.
  6854. void ImGui::PushOverrideID(ImGuiID id)
  6855. {
  6856. ImGuiContext& g = *GImGui;
  6857. ImGuiWindow* window = g.CurrentWindow;
  6858. if (g.DebugHookIdInfo == id)
  6859. DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
  6860. window->IDStack.push_back(id);
  6861. }
  6862. // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
  6863. // (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
  6864. // for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
  6865. ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
  6866. {
  6867. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  6868. ImGuiContext& g = *GImGui;
  6869. if (g.DebugHookIdInfo == id)
  6870. DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
  6871. return id;
  6872. }
  6873. void ImGui::PopID()
  6874. {
  6875. ImGuiWindow* window = GImGui->CurrentWindow;
  6876. IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
  6877. window->IDStack.pop_back();
  6878. }
  6879. ImGuiID ImGui::GetID(const char* str_id)
  6880. {
  6881. ImGuiWindow* window = GImGui->CurrentWindow;
  6882. return window->GetID(str_id);
  6883. }
  6884. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  6885. {
  6886. ImGuiWindow* window = GImGui->CurrentWindow;
  6887. return window->GetID(str_id_begin, str_id_end);
  6888. }
  6889. ImGuiID ImGui::GetID(const void* ptr_id)
  6890. {
  6891. ImGuiWindow* window = GImGui->CurrentWindow;
  6892. return window->GetID(ptr_id);
  6893. }
  6894. bool ImGui::IsRectVisible(const ImVec2& size)
  6895. {
  6896. ImGuiWindow* window = GImGui->CurrentWindow;
  6897. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  6898. }
  6899. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  6900. {
  6901. ImGuiWindow* window = GImGui->CurrentWindow;
  6902. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  6903. }
  6904. //-----------------------------------------------------------------------------
  6905. // [SECTION] INPUTS
  6906. //-----------------------------------------------------------------------------
  6907. // Test if mouse cursor is hovering given rectangle
  6908. // NB- Rectangle is clipped by our current clip setting
  6909. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  6910. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  6911. {
  6912. ImGuiContext& g = *GImGui;
  6913. // Clip
  6914. ImRect rect_clipped(r_min, r_max);
  6915. if (clip)
  6916. rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
  6917. // Expand for touch input
  6918. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  6919. if (!rect_for_touch.Contains(g.IO.MousePos))
  6920. return false;
  6921. return true;
  6922. }
  6923. ImGuiKeyData* ImGui::GetKeyData(ImGuiKey key)
  6924. {
  6925. ImGuiContext& g = *GImGui;
  6926. // Special storage location for mods
  6927. if (key & ImGuiMod_Mask_)
  6928. key = ConvertSingleModFlagToKey(key);
  6929. int index;
  6930. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  6931. IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
  6932. if (IsLegacyKey(key))
  6933. index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native
  6934. else
  6935. index = key;
  6936. #else
  6937. IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
  6938. index = key - ImGuiKey_NamedKey_BEGIN;
  6939. #endif
  6940. return &g.IO.KeysData[index];
  6941. }
  6942. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  6943. ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
  6944. {
  6945. ImGuiContext& g = *GImGui;
  6946. IM_ASSERT(IsNamedKey(key));
  6947. const ImGuiKeyData* key_data = GetKeyData(key);
  6948. return (ImGuiKey)(key_data - g.IO.KeysData);
  6949. }
  6950. #endif
  6951. // Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
  6952. static const char* const GKeyNames[] =
  6953. {
  6954. "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
  6955. "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
  6956. "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
  6957. "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
  6958. "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
  6959. "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
  6960. "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
  6961. "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
  6962. "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
  6963. "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
  6964. "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
  6965. "GamepadStart", "GamepadBack",
  6966. "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
  6967. "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
  6968. "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
  6969. "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
  6970. "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
  6971. "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
  6972. "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
  6973. };
  6974. IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
  6975. const char* ImGui::GetKeyName(ImGuiKey key)
  6976. {
  6977. #ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
  6978. IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
  6979. #else
  6980. if (IsLegacyKey(key))
  6981. {
  6982. ImGuiIO& io = GetIO();
  6983. if (io.KeyMap[key] == -1)
  6984. return "N/A";
  6985. IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key]));
  6986. key = (ImGuiKey)io.KeyMap[key];
  6987. }
  6988. #endif
  6989. if (key == ImGuiKey_None)
  6990. return "None";
  6991. if (key & ImGuiMod_Mask_)
  6992. key = ConvertSingleModFlagToKey(key);
  6993. if (!IsNamedKey(key))
  6994. return "Unknown";
  6995. return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
  6996. }
  6997. void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
  6998. {
  6999. ImGuiContext& g = *GImGui;
  7000. ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
  7001. (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
  7002. (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
  7003. (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
  7004. (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
  7005. GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
  7006. }
  7007. // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
  7008. // t1 = current time (e.g.: g.Time)
  7009. // An event is triggered at:
  7010. // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
  7011. int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
  7012. {
  7013. if (t1 == 0.0f)
  7014. return 1;
  7015. if (t0 >= t1)
  7016. return 0;
  7017. if (repeat_rate <= 0.0f)
  7018. return (t0 < repeat_delay) && (t1 >= repeat_delay);
  7019. const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
  7020. const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
  7021. const int count = count_t1 - count_t0;
  7022. return count;
  7023. }
  7024. void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
  7025. {
  7026. ImGuiContext& g = *GImGui;
  7027. switch (flags & ImGuiInputFlags_RepeatRateMask_)
  7028. {
  7029. case ImGuiInputFlags_RepeatRateNavMove: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
  7030. case ImGuiInputFlags_RepeatRateNavTweak: *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
  7031. case ImGuiInputFlags_RepeatRateDefault: default: *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
  7032. }
  7033. }
  7034. // Return value representing the number of presses in the last time period, for the given repeat rate
  7035. // (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
  7036. int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
  7037. {
  7038. ImGuiContext& g = *GImGui;
  7039. const ImGuiKeyData* key_data = GetKeyData(key);
  7040. if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on input ownership)
  7041. return 0;
  7042. const float t = key_data->DownDuration;
  7043. return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
  7044. }
  7045. // Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
  7046. ImVec2 ImGui::GetKeyVector2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
  7047. {
  7048. return ImVec2(
  7049. GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
  7050. GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
  7051. }
  7052. // Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
  7053. // Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
  7054. bool ImGui::IsKeyDown(ImGuiKey key)
  7055. {
  7056. const ImGuiKeyData* key_data = GetKeyData(key);
  7057. if (!key_data->Down)
  7058. return false;
  7059. return true;
  7060. }
  7061. bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
  7062. {
  7063. return IsKeyPressedEx(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
  7064. }
  7065. // Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
  7066. // [Internal] 2022/07: Do not call this directly! It is a temporary entry point which we will soon replace with an overload for IsKeyPressed() when we introduce key ownership.
  7067. bool ImGui::IsKeyPressedEx(ImGuiKey key, ImGuiInputFlags flags)
  7068. {
  7069. const ImGuiKeyData* key_data = GetKeyData(key);
  7070. if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on input ownership)
  7071. return false;
  7072. const float t = key_data->DownDuration;
  7073. if (t < 0.0f)
  7074. return false;
  7075. bool pressed = (t == 0.0f);
  7076. if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
  7077. {
  7078. float repeat_delay, repeat_rate;
  7079. GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
  7080. pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
  7081. }
  7082. if (!pressed)
  7083. return false;
  7084. return true;
  7085. }
  7086. bool ImGui::IsKeyReleased(ImGuiKey key)
  7087. {
  7088. const ImGuiKeyData* key_data = GetKeyData(key);
  7089. if (key_data->DownDurationPrev < 0.0f || key_data->Down)
  7090. return false;
  7091. return true;
  7092. }
  7093. bool ImGui::IsMouseDown(ImGuiMouseButton button)
  7094. {
  7095. ImGuiContext& g = *GImGui;
  7096. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7097. return g.IO.MouseDown[button];
  7098. }
  7099. bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
  7100. {
  7101. ImGuiContext& g = *GImGui;
  7102. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7103. if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on input ownership)
  7104. return false;
  7105. const float t = g.IO.MouseDownDuration[button];
  7106. if (t == 0.0f)
  7107. return true;
  7108. if (repeat && t > g.IO.KeyRepeatDelay)
  7109. return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  7110. return false;
  7111. }
  7112. bool ImGui::IsMouseReleased(ImGuiMouseButton button)
  7113. {
  7114. ImGuiContext& g = *GImGui;
  7115. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7116. return g.IO.MouseReleased[button];
  7117. }
  7118. bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
  7119. {
  7120. ImGuiContext& g = *GImGui;
  7121. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7122. return g.IO.MouseClickedCount[button] == 2;
  7123. }
  7124. int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
  7125. {
  7126. ImGuiContext& g = *GImGui;
  7127. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7128. return g.IO.MouseClickedCount[button];
  7129. }
  7130. // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
  7131. // [Internal] This doesn't test if the button is pressed
  7132. bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
  7133. {
  7134. ImGuiContext& g = *GImGui;
  7135. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7136. if (lock_threshold < 0.0f)
  7137. lock_threshold = g.IO.MouseDragThreshold;
  7138. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  7139. }
  7140. bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
  7141. {
  7142. ImGuiContext& g = *GImGui;
  7143. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7144. if (!g.IO.MouseDown[button])
  7145. return false;
  7146. return IsMouseDragPastThreshold(button, lock_threshold);
  7147. }
  7148. ImVec2 ImGui::GetMousePos()
  7149. {
  7150. ImGuiContext& g = *GImGui;
  7151. return g.IO.MousePos;
  7152. }
  7153. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  7154. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  7155. {
  7156. ImGuiContext& g = *GImGui;
  7157. if (g.BeginPopupStack.Size > 0)
  7158. return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
  7159. return g.IO.MousePos;
  7160. }
  7161. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
  7162. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  7163. {
  7164. // The assert is only to silence a false-positive in XCode Static Analysis.
  7165. // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
  7166. IM_ASSERT(GImGui != NULL);
  7167. const float MOUSE_INVALID = -256000.0f;
  7168. ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
  7169. return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
  7170. }
  7171. // [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
  7172. bool ImGui::IsAnyMouseDown()
  7173. {
  7174. ImGuiContext& g = *GImGui;
  7175. for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
  7176. if (g.IO.MouseDown[n])
  7177. return true;
  7178. return false;
  7179. }
  7180. // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
  7181. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
  7182. // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
  7183. ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
  7184. {
  7185. ImGuiContext& g = *GImGui;
  7186. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7187. if (lock_threshold < 0.0f)
  7188. lock_threshold = g.IO.MouseDragThreshold;
  7189. if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
  7190. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  7191. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
  7192. return g.IO.MousePos - g.IO.MouseClickedPos[button];
  7193. return ImVec2(0.0f, 0.0f);
  7194. }
  7195. void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
  7196. {
  7197. ImGuiContext& g = *GImGui;
  7198. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  7199. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  7200. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  7201. }
  7202. ImGuiMouseCursor ImGui::GetMouseCursor()
  7203. {
  7204. ImGuiContext& g = *GImGui;
  7205. return g.MouseCursor;
  7206. }
  7207. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  7208. {
  7209. ImGuiContext& g = *GImGui;
  7210. g.MouseCursor = cursor_type;
  7211. }
  7212. void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
  7213. {
  7214. ImGuiContext& g = *GImGui;
  7215. g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
  7216. }
  7217. void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
  7218. {
  7219. ImGuiContext& g = *GImGui;
  7220. g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
  7221. }
  7222. #ifndef IMGUI_DISABLE_DEBUG_TOOLS
  7223. static const char* GetInputSourceName(ImGuiInputSource source)
  7224. {
  7225. const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" };
  7226. IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
  7227. return input_source_names[source];
  7228. }
  7229. static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
  7230. {
  7231. ImGuiContext& g = *GImGui;
  7232. if (e->Type == ImGuiInputEventType_MousePos) { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("%s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("%s: MousePos (%.1f, %.1f)\n", prefix, e->MousePos.PosX, e->MousePos.PosY); return; }
  7233. if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("%s: MouseButton %d %s\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up"); return; }
  7234. if (e->Type == ImGuiInputEventType_MouseWheel) { IMGUI_DEBUG_LOG_IO("%s: MouseWheel (%.1f, %.1f)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY); return; }
  7235. if (e->Type == ImGuiInputEventType_Key) { IMGUI_DEBUG_LOG_IO("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
  7236. if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
  7237. if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
  7238. }
  7239. #endif
  7240. // Process input queue
  7241. // We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
  7242. // - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
  7243. // - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
  7244. void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
  7245. {
  7246. ImGuiContext& g = *GImGui;
  7247. ImGuiIO& io = g.IO;
  7248. // Only trickle chars<>key when working with InputText()
  7249. // FIXME: InputText() could parse event trail?
  7250. // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
  7251. const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
  7252. bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
  7253. int mouse_button_changed = 0x00;
  7254. ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
  7255. int event_n = 0;
  7256. for (; event_n < g.InputEventsQueue.Size; event_n++)
  7257. {
  7258. ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
  7259. if (e->Type == ImGuiInputEventType_MousePos)
  7260. {
  7261. // Trickling Rule: Stop processing queued events if we already handled a mouse button change
  7262. ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
  7263. if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
  7264. break;
  7265. io.MousePos = event_pos;
  7266. mouse_moved = true;
  7267. }
  7268. else if (e->Type == ImGuiInputEventType_MouseButton)
  7269. {
  7270. // Trickling Rule: Stop processing queued events if we got multiple action on the same button
  7271. const ImGuiMouseButton button = e->MouseButton.Button;
  7272. IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
  7273. if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
  7274. break;
  7275. io.MouseDown[button] = e->MouseButton.Down;
  7276. mouse_button_changed |= (1 << button);
  7277. }
  7278. else if (e->Type == ImGuiInputEventType_MouseWheel)
  7279. {
  7280. // Trickling Rule: Stop processing queued events if we got multiple action on the event
  7281. if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
  7282. break;
  7283. io.MouseWheelH += e->MouseWheel.WheelX;
  7284. io.MouseWheel += e->MouseWheel.WheelY;
  7285. mouse_wheeled = true;
  7286. }
  7287. else if (e->Type == ImGuiInputEventType_Key)
  7288. {
  7289. // Trickling Rule: Stop processing queued events if we got multiple action on the same button
  7290. ImGuiKey key = e->Key.Key;
  7291. IM_ASSERT(key != ImGuiKey_None);
  7292. ImGuiKeyData* key_data = GetKeyData(key);
  7293. const int key_data_index = (int)(key_data - g.IO.KeysData);
  7294. if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
  7295. break;
  7296. key_data->Down = e->Key.Down;
  7297. key_data->AnalogValue = e->Key.AnalogValue;
  7298. key_changed = true;
  7299. key_changed_mask.SetBit(key_data_index);
  7300. if (key == ImGuiMod_Ctrl || key == ImGuiMod_Shift || key == ImGuiMod_Alt || key == ImGuiMod_Super)
  7301. {
  7302. if (key == ImGuiMod_Ctrl) { io.KeyCtrl = key_data->Down; }
  7303. if (key == ImGuiMod_Shift) { io.KeyShift = key_data->Down; }
  7304. if (key == ImGuiMod_Alt) { io.KeyAlt = key_data->Down; }
  7305. if (key == ImGuiMod_Super) { io.KeySuper = key_data->Down; }
  7306. io.KeyMods = GetMergedModsFromBools();
  7307. }
  7308. // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
  7309. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  7310. io.KeysDown[key_data_index] = key_data->Down;
  7311. if (io.KeyMap[key_data_index] != -1)
  7312. io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
  7313. #endif
  7314. }
  7315. else if (e->Type == ImGuiInputEventType_Text)
  7316. {
  7317. // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
  7318. if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
  7319. break;
  7320. unsigned int c = e->Text.Char;
  7321. io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
  7322. if (trickle_interleaved_keys_and_text)
  7323. text_inputted = true;
  7324. }
  7325. else if (e->Type == ImGuiInputEventType_Focus)
  7326. {
  7327. // We intentionally overwrite this and process in NewFrame(), in order to give a chance
  7328. // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
  7329. const bool focus_lost = !e->AppFocused.Focused;
  7330. io.AppFocusLost = focus_lost;
  7331. }
  7332. else
  7333. {
  7334. IM_ASSERT(0 && "Unknown event!");
  7335. }
  7336. }
  7337. // Record trail (for domain-specific applications wanting to access a precise trail)
  7338. //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
  7339. for (int n = 0; n < event_n; n++)
  7340. g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
  7341. // [DEBUG]
  7342. #ifndef IMGUI_DISABLE_DEBUG_TOOLS
  7343. if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
  7344. for (int n = 0; n < g.InputEventsQueue.Size; n++)
  7345. DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
  7346. #endif
  7347. // Remaining events will be processed on the next frame
  7348. if (event_n == g.InputEventsQueue.Size)
  7349. g.InputEventsQueue.resize(0);
  7350. else
  7351. g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
  7352. // Clear buttons state when focus is lost
  7353. // (this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle)
  7354. if (g.IO.AppFocusLost)
  7355. {
  7356. g.IO.ClearInputKeys();
  7357. g.IO.AppFocusLost = false;
  7358. }
  7359. }
  7360. //-----------------------------------------------------------------------------
  7361. // [SECTION] ERROR CHECKING
  7362. //-----------------------------------------------------------------------------
  7363. // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
  7364. // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
  7365. // If this triggers you have an issue:
  7366. // - Most commonly: mismatched headers and compiled code version.
  7367. // - Or: mismatched configuration #define, compilation settings, packing pragma etc.
  7368. // The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
  7369. // which is way it is required you put them in your imconfig file (and not just before including imgui.h).
  7370. // Otherwise it is possible that different compilation units would see different structure layout
  7371. bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
  7372. {
  7373. bool error = false;
  7374. if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
  7375. if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
  7376. if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
  7377. if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
  7378. if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
  7379. if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
  7380. if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
  7381. return !error;
  7382. }
  7383. // Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
  7384. // This is causing issues and ambiguity and we need to retire that.
  7385. // See https://github.com/ocornut/imgui/issues/5548 for more details.
  7386. // [Scenario 1]
  7387. // Previously this would make the window content size ~200x200:
  7388. // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK
  7389. // Instead, please submit an item:
  7390. // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
  7391. // Alternative:
  7392. // Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
  7393. // [Scenario 2]
  7394. // For reference this is one of the issue what we aim to fix with this change:
  7395. // BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
  7396. // The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
  7397. // While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
  7398. void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
  7399. {
  7400. ImGuiContext& g = *GImGui;
  7401. ImGuiWindow* window = g.CurrentWindow;
  7402. IM_ASSERT(window->DC.IsSetPos);
  7403. window->DC.IsSetPos = false;
  7404. #ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  7405. if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
  7406. return;
  7407. IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
  7408. #else
  7409. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  7410. #endif
  7411. }
  7412. static void ImGui::ErrorCheckNewFrameSanityChecks()
  7413. {
  7414. ImGuiContext& g = *GImGui;
  7415. // Check user IM_ASSERT macro
  7416. // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
  7417. // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
  7418. // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
  7419. // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
  7420. // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
  7421. if (true) IM_ASSERT(1); else IM_ASSERT(0);
  7422. // Check user data
  7423. // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
  7424. IM_ASSERT(g.Initialized);
  7425. IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
  7426. IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
  7427. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
  7428. IM_ASSERT(g.IO.Fonts->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
  7429. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
  7430. IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
  7431. IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
  7432. IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
  7433. IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
  7434. IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
  7435. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
  7436. for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
  7437. IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
  7438. // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
  7439. if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
  7440. IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
  7441. #endif
  7442. // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
  7443. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
  7444. g.IO.ConfigWindowsResizeFromEdges = false;
  7445. }
  7446. static void ImGui::ErrorCheckEndFrameSanityChecks()
  7447. {
  7448. ImGuiContext& g = *GImGui;
  7449. // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
  7450. // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
  7451. // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
  7452. // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
  7453. // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
  7454. // while still correctly asserting on mid-frame key press events.
  7455. const ImGuiKeyChord key_mods = GetMergedModsFromBools();
  7456. IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
  7457. IM_UNUSED(key_mods);
  7458. // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
  7459. //ErrorCheckEndFrameRecover();
  7460. // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
  7461. // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
  7462. if (g.CurrentWindowStack.Size != 1)
  7463. {
  7464. if (g.CurrentWindowStack.Size > 1)
  7465. {
  7466. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
  7467. while (g.CurrentWindowStack.Size > 1)
  7468. End();
  7469. }
  7470. else
  7471. {
  7472. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
  7473. }
  7474. }
  7475. IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
  7476. }
  7477. // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
  7478. // Must be called during or before EndFrame().
  7479. // This is generally flawed as we are not necessarily End/Popping things in the right order.
  7480. // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
  7481. // FIXME: Can't recover from interleaved BeginTabBar/Begin
  7482. void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
  7483. {
  7484. // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
  7485. ImGuiContext& g = *GImGui;
  7486. while (g.CurrentWindowStack.Size > 0) //-V1044
  7487. {
  7488. ErrorCheckEndWindowRecover(log_callback, user_data);
  7489. ImGuiWindow* window = g.CurrentWindow;
  7490. if (g.CurrentWindowStack.Size == 1)
  7491. {
  7492. IM_ASSERT(window->IsFallbackWindow);
  7493. break;
  7494. }
  7495. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  7496. {
  7497. if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
  7498. EndChild();
  7499. }
  7500. else
  7501. {
  7502. if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
  7503. End();
  7504. }
  7505. }
  7506. }
  7507. // Must be called before End()/EndChild()
  7508. void ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
  7509. {
  7510. ImGuiContext& g = *GImGui;
  7511. while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
  7512. {
  7513. if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
  7514. EndTable();
  7515. }
  7516. ImGuiWindow* window = g.CurrentWindow;
  7517. ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
  7518. IM_ASSERT(window != NULL);
  7519. while (g.CurrentTabBar != NULL) //-V1044
  7520. {
  7521. if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
  7522. EndTabBar();
  7523. }
  7524. while (window->DC.TreeDepth > 0)
  7525. {
  7526. if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
  7527. TreePop();
  7528. }
  7529. while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
  7530. {
  7531. if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
  7532. EndGroup();
  7533. }
  7534. while (window->IDStack.Size > 1)
  7535. {
  7536. if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
  7537. PopID();
  7538. }
  7539. while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
  7540. {
  7541. if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
  7542. EndDisabled();
  7543. }
  7544. while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
  7545. {
  7546. if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
  7547. PopStyleColor();
  7548. }
  7549. while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
  7550. {
  7551. if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
  7552. PopItemFlag();
  7553. }
  7554. while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
  7555. {
  7556. if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
  7557. PopStyleVar();
  7558. }
  7559. while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack) //-V1044
  7560. {
  7561. if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
  7562. PopFocusScope();
  7563. }
  7564. }
  7565. // Save current stack sizes for later compare
  7566. void ImGuiStackSizes::SetToCurrentState()
  7567. {
  7568. ImGuiContext& g = *GImGui;
  7569. ImGuiWindow* window = g.CurrentWindow;
  7570. SizeOfIDStack = (short)window->IDStack.Size;
  7571. SizeOfColorStack = (short)g.ColorStack.Size;
  7572. SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
  7573. SizeOfFontStack = (short)g.FontStack.Size;
  7574. SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
  7575. SizeOfGroupStack = (short)g.GroupStack.Size;
  7576. SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
  7577. SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
  7578. SizeOfDisabledStack = (short)g.DisabledStackSize;
  7579. }
  7580. // Compare to detect usage errors
  7581. void ImGuiStackSizes::CompareWithCurrentState()
  7582. {
  7583. ImGuiContext& g = *GImGui;
  7584. ImGuiWindow* window = g.CurrentWindow;
  7585. IM_UNUSED(window);
  7586. // Window stacks
  7587. // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
  7588. IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
  7589. // Global stacks
  7590. // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
  7591. IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
  7592. IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
  7593. IM_ASSERT(SizeOfDisabledStack == g.DisabledStackSize && "BeginDisabled/EndDisabled Mismatch!");
  7594. IM_ASSERT(SizeOfItemFlagsStack >= g.ItemFlagsStack.Size && "PushItemFlag/PopItemFlag Mismatch!");
  7595. IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
  7596. IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
  7597. IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
  7598. IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
  7599. }
  7600. //-----------------------------------------------------------------------------
  7601. // [SECTION] LAYOUT
  7602. //-----------------------------------------------------------------------------
  7603. // - ItemSize()
  7604. // - ItemAdd()
  7605. // - SameLine()
  7606. // - GetCursorScreenPos()
  7607. // - SetCursorScreenPos()
  7608. // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
  7609. // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
  7610. // - GetCursorStartPos()
  7611. // - Indent()
  7612. // - Unindent()
  7613. // - SetNextItemWidth()
  7614. // - PushItemWidth()
  7615. // - PushMultiItemsWidths()
  7616. // - PopItemWidth()
  7617. // - CalcItemWidth()
  7618. // - CalcItemSize()
  7619. // - GetTextLineHeight()
  7620. // - GetTextLineHeightWithSpacing()
  7621. // - GetFrameHeight()
  7622. // - GetFrameHeightWithSpacing()
  7623. // - GetContentRegionMax()
  7624. // - GetContentRegionMaxAbs() [Internal]
  7625. // - GetContentRegionAvail(),
  7626. // - GetWindowContentRegionMin(), GetWindowContentRegionMax()
  7627. // - BeginGroup()
  7628. // - EndGroup()
  7629. // Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
  7630. //-----------------------------------------------------------------------------
  7631. // Advance cursor given item size for layout.
  7632. // Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
  7633. // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
  7634. void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
  7635. {
  7636. ImGuiContext& g = *GImGui;
  7637. ImGuiWindow* window = g.CurrentWindow;
  7638. if (window->SkipItems)
  7639. return;
  7640. // We increase the height in this function to accommodate for baseline offset.
  7641. // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
  7642. // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
  7643. const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
  7644. const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
  7645. const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
  7646. // Always align ourselves on pixel boundaries
  7647. //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]
  7648. window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
  7649. window->DC.CursorPosPrevLine.y = line_y1;
  7650. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
  7651. window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line
  7652. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  7653. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
  7654. //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
  7655. window->DC.PrevLineSize.y = line_height;
  7656. window->DC.CurrLineSize.y = 0.0f;
  7657. window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
  7658. window->DC.CurrLineTextBaseOffset = 0.0f;
  7659. window->DC.IsSameLine = window->DC.IsSetPos = false;
  7660. // Horizontal layout mode
  7661. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  7662. SameLine();
  7663. }
  7664. // Declare item bounding box for clipping and interaction.
  7665. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  7666. // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
  7667. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
  7668. {
  7669. ImGuiContext& g = *GImGui;
  7670. ImGuiWindow* window = g.CurrentWindow;
  7671. // Set item data
  7672. // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
  7673. g.LastItemData.ID = id;
  7674. g.LastItemData.Rect = bb;
  7675. g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
  7676. g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
  7677. g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
  7678. // Directional navigation processing
  7679. if (id != 0)
  7680. {
  7681. KeepAliveID(id);
  7682. // Runs prior to clipping early-out
  7683. // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
  7684. // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
  7685. // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
  7686. // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
  7687. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
  7688. // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
  7689. // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
  7690. // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
  7691. window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
  7692. if (g.NavId == id || g.NavAnyRequest)
  7693. if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
  7694. if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
  7695. NavProcessItem();
  7696. // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
  7697. // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
  7698. // READ THE FAQ: https://dearimgui.org/faq
  7699. IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
  7700. }
  7701. g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
  7702. #ifdef IMGUI_ENABLE_TEST_ENGINE
  7703. if (id != 0)
  7704. IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
  7705. #endif
  7706. // Clipping test
  7707. // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
  7708. //const bool is_clipped = IsClippedEx(bb, id);
  7709. //if (is_clipped)
  7710. // return false;
  7711. const bool is_rect_visible = bb.Overlaps(window->ClipRect);
  7712. if (!is_rect_visible)
  7713. if (id == 0 || (id != g.ActiveId && id != g.NavId))
  7714. if (!g.LogEnabled)
  7715. return false;
  7716. //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
  7717. // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
  7718. if (is_rect_visible)
  7719. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
  7720. if (IsMouseHoveringRect(bb.Min, bb.Max))
  7721. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
  7722. return true;
  7723. }
  7724. // Gets back to previous line and continue with horizontal layout
  7725. // offset_from_start_x == 0 : follow right after previous item
  7726. // offset_from_start_x != 0 : align to specified x position (relative to window/group left)
  7727. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  7728. // spacing_w >= 0 : enforce spacing amount
  7729. void ImGui::SameLine(float offset_from_start_x, float spacing_w)
  7730. {
  7731. ImGuiContext& g = *GImGui;
  7732. ImGuiWindow* window = g.CurrentWindow;
  7733. if (window->SkipItems)
  7734. return;
  7735. if (offset_from_start_x != 0.0f)
  7736. {
  7737. if (spacing_w < 0.0f)
  7738. spacing_w = 0.0f;
  7739. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
  7740. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  7741. }
  7742. else
  7743. {
  7744. if (spacing_w < 0.0f)
  7745. spacing_w = g.Style.ItemSpacing.x;
  7746. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  7747. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  7748. }
  7749. window->DC.CurrLineSize = window->DC.PrevLineSize;
  7750. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  7751. window->DC.IsSameLine = true;
  7752. }
  7753. ImVec2 ImGui::GetCursorScreenPos()
  7754. {
  7755. ImGuiWindow* window = GetCurrentWindowRead();
  7756. return window->DC.CursorPos;
  7757. }
  7758. // 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
  7759. // I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
  7760. // It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
  7761. void ImGui::SetCursorScreenPos(const ImVec2& pos)
  7762. {
  7763. ImGuiWindow* window = GetCurrentWindow();
  7764. window->DC.CursorPos = pos;
  7765. //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  7766. window->DC.IsSetPos = true;
  7767. }
  7768. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  7769. // 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'.
  7770. ImVec2 ImGui::GetCursorPos()
  7771. {
  7772. ImGuiWindow* window = GetCurrentWindowRead();
  7773. return window->DC.CursorPos - window->Pos + window->Scroll;
  7774. }
  7775. float ImGui::GetCursorPosX()
  7776. {
  7777. ImGuiWindow* window = GetCurrentWindowRead();
  7778. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  7779. }
  7780. float ImGui::GetCursorPosY()
  7781. {
  7782. ImGuiWindow* window = GetCurrentWindowRead();
  7783. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  7784. }
  7785. void ImGui::SetCursorPos(const ImVec2& local_pos)
  7786. {
  7787. ImGuiWindow* window = GetCurrentWindow();
  7788. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  7789. //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  7790. window->DC.IsSetPos = true;
  7791. }
  7792. void ImGui::SetCursorPosX(float x)
  7793. {
  7794. ImGuiWindow* window = GetCurrentWindow();
  7795. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  7796. //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  7797. window->DC.IsSetPos = true;
  7798. }
  7799. void ImGui::SetCursorPosY(float y)
  7800. {
  7801. ImGuiWindow* window = GetCurrentWindow();
  7802. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  7803. //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  7804. window->DC.IsSetPos = true;
  7805. }
  7806. ImVec2 ImGui::GetCursorStartPos()
  7807. {
  7808. ImGuiWindow* window = GetCurrentWindowRead();
  7809. return window->DC.CursorStartPos - window->Pos;
  7810. }
  7811. void ImGui::Indent(float indent_w)
  7812. {
  7813. ImGuiContext& g = *GImGui;
  7814. ImGuiWindow* window = GetCurrentWindow();
  7815. window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  7816. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  7817. }
  7818. void ImGui::Unindent(float indent_w)
  7819. {
  7820. ImGuiContext& g = *GImGui;
  7821. ImGuiWindow* window = GetCurrentWindow();
  7822. window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  7823. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  7824. }
  7825. // Affect large frame+labels widgets only.
  7826. void ImGui::SetNextItemWidth(float item_width)
  7827. {
  7828. ImGuiContext& g = *GImGui;
  7829. g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
  7830. g.NextItemData.Width = item_width;
  7831. }
  7832. // FIXME: Remove the == 0.0f behavior?
  7833. void ImGui::PushItemWidth(float item_width)
  7834. {
  7835. ImGuiContext& g = *GImGui;
  7836. ImGuiWindow* window = g.CurrentWindow;
  7837. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
  7838. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  7839. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  7840. }
  7841. void ImGui::PushMultiItemsWidths(int components, float w_full)
  7842. {
  7843. ImGuiContext& g = *GImGui;
  7844. ImGuiWindow* window = g.CurrentWindow;
  7845. const ImGuiStyle& style = g.Style;
  7846. const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
  7847. const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
  7848. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
  7849. window->DC.ItemWidthStack.push_back(w_item_last);
  7850. for (int i = 0; i < components - 2; i++)
  7851. window->DC.ItemWidthStack.push_back(w_item_one);
  7852. window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
  7853. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  7854. }
  7855. void ImGui::PopItemWidth()
  7856. {
  7857. ImGuiWindow* window = GetCurrentWindow();
  7858. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  7859. window->DC.ItemWidthStack.pop_back();
  7860. }
  7861. // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
  7862. // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
  7863. float ImGui::CalcItemWidth()
  7864. {
  7865. ImGuiContext& g = *GImGui;
  7866. ImGuiWindow* window = g.CurrentWindow;
  7867. float w;
  7868. if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
  7869. w = g.NextItemData.Width;
  7870. else
  7871. w = window->DC.ItemWidth;
  7872. if (w < 0.0f)
  7873. {
  7874. float region_max_x = GetContentRegionMaxAbs().x;
  7875. w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
  7876. }
  7877. w = IM_FLOOR(w);
  7878. return w;
  7879. }
  7880. // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
  7881. // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
  7882. // Note that only CalcItemWidth() is publicly exposed.
  7883. // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
  7884. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
  7885. {
  7886. ImGuiContext& g = *GImGui;
  7887. ImGuiWindow* window = g.CurrentWindow;
  7888. ImVec2 region_max;
  7889. if (size.x < 0.0f || size.y < 0.0f)
  7890. region_max = GetContentRegionMaxAbs();
  7891. if (size.x == 0.0f)
  7892. size.x = default_w;
  7893. else if (size.x < 0.0f)
  7894. size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
  7895. if (size.y == 0.0f)
  7896. size.y = default_h;
  7897. else if (size.y < 0.0f)
  7898. size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
  7899. return size;
  7900. }
  7901. float ImGui::GetTextLineHeight()
  7902. {
  7903. ImGuiContext& g = *GImGui;
  7904. return g.FontSize;
  7905. }
  7906. float ImGui::GetTextLineHeightWithSpacing()
  7907. {
  7908. ImGuiContext& g = *GImGui;
  7909. return g.FontSize + g.Style.ItemSpacing.y;
  7910. }
  7911. float ImGui::GetFrameHeight()
  7912. {
  7913. ImGuiContext& g = *GImGui;
  7914. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  7915. }
  7916. float ImGui::GetFrameHeightWithSpacing()
  7917. {
  7918. ImGuiContext& g = *GImGui;
  7919. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  7920. }
  7921. // FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
  7922. // FIXME: This is in window space (not screen space!).
  7923. ImVec2 ImGui::GetContentRegionMax()
  7924. {
  7925. ImGuiContext& g = *GImGui;
  7926. ImGuiWindow* window = g.CurrentWindow;
  7927. ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
  7928. if (window->DC.CurrentColumns || g.CurrentTable)
  7929. mx.x = window->WorkRect.Max.x - window->Pos.x;
  7930. return mx;
  7931. }
  7932. // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
  7933. ImVec2 ImGui::GetContentRegionMaxAbs()
  7934. {
  7935. ImGuiContext& g = *GImGui;
  7936. ImGuiWindow* window = g.CurrentWindow;
  7937. ImVec2 mx = window->ContentRegionRect.Max;
  7938. if (window->DC.CurrentColumns || g.CurrentTable)
  7939. mx.x = window->WorkRect.Max.x;
  7940. return mx;
  7941. }
  7942. ImVec2 ImGui::GetContentRegionAvail()
  7943. {
  7944. ImGuiWindow* window = GImGui->CurrentWindow;
  7945. return GetContentRegionMaxAbs() - window->DC.CursorPos;
  7946. }
  7947. // In window space (not screen space!)
  7948. ImVec2 ImGui::GetWindowContentRegionMin()
  7949. {
  7950. ImGuiWindow* window = GImGui->CurrentWindow;
  7951. return window->ContentRegionRect.Min - window->Pos;
  7952. }
  7953. ImVec2 ImGui::GetWindowContentRegionMax()
  7954. {
  7955. ImGuiWindow* window = GImGui->CurrentWindow;
  7956. return window->ContentRegionRect.Max - window->Pos;
  7957. }
  7958. // 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.)
  7959. // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
  7960. // FIXME-OPT: Could we safely early out on ->SkipItems?
  7961. void ImGui::BeginGroup()
  7962. {
  7963. ImGuiContext& g = *GImGui;
  7964. ImGuiWindow* window = g.CurrentWindow;
  7965. g.GroupStack.resize(g.GroupStack.Size + 1);
  7966. ImGuiGroupData& group_data = g.GroupStack.back();
  7967. group_data.WindowID = window->ID;
  7968. group_data.BackupCursorPos = window->DC.CursorPos;
  7969. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  7970. group_data.BackupIndent = window->DC.Indent;
  7971. group_data.BackupGroupOffset = window->DC.GroupOffset;
  7972. group_data.BackupCurrLineSize = window->DC.CurrLineSize;
  7973. group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
  7974. group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
  7975. group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
  7976. group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
  7977. group_data.EmitItem = true;
  7978. window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
  7979. window->DC.Indent = window->DC.GroupOffset;
  7980. window->DC.CursorMaxPos = window->DC.CursorPos;
  7981. window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
  7982. if (g.LogEnabled)
  7983. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  7984. }
  7985. void ImGui::EndGroup()
  7986. {
  7987. ImGuiContext& g = *GImGui;
  7988. ImGuiWindow* window = g.CurrentWindow;
  7989. IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
  7990. ImGuiGroupData& group_data = g.GroupStack.back();
  7991. IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
  7992. if (window->DC.IsSetPos)
  7993. ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
  7994. ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
  7995. window->DC.CursorPos = group_data.BackupCursorPos;
  7996. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  7997. window->DC.Indent = group_data.BackupIndent;
  7998. window->DC.GroupOffset = group_data.BackupGroupOffset;
  7999. window->DC.CurrLineSize = group_data.BackupCurrLineSize;
  8000. window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
  8001. if (g.LogEnabled)
  8002. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  8003. if (!group_data.EmitItem)
  8004. {
  8005. g.GroupStack.pop_back();
  8006. return;
  8007. }
  8008. window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
  8009. ItemSize(group_bb.GetSize());
  8010. ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
  8011. // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
  8012. // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
  8013. // Also if you grep for LastItemId you'll notice it is only used in that context.
  8014. // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
  8015. const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
  8016. const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
  8017. if (group_contains_curr_active_id)
  8018. g.LastItemData.ID = g.ActiveId;
  8019. else if (group_contains_prev_active_id)
  8020. g.LastItemData.ID = g.ActiveIdPreviousFrame;
  8021. g.LastItemData.Rect = group_bb;
  8022. // Forward Hovered flag
  8023. const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
  8024. if (group_contains_curr_hovered_id)
  8025. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
  8026. // Forward Edited flag
  8027. if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
  8028. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
  8029. // Forward Deactivated flag
  8030. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
  8031. if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
  8032. g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
  8033. g.GroupStack.pop_back();
  8034. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  8035. }
  8036. //-----------------------------------------------------------------------------
  8037. // [SECTION] SCROLLING
  8038. //-----------------------------------------------------------------------------
  8039. // Helper to snap on edges when aiming at an item very close to the edge,
  8040. // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
  8041. // When we refactor the scrolling API this may be configurable with a flag?
  8042. // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
  8043. static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
  8044. {
  8045. if (target <= snap_min + snap_threshold)
  8046. return ImLerp(snap_min, target, center_ratio);
  8047. if (target >= snap_max - snap_threshold)
  8048. return ImLerp(target, snap_max, center_ratio);
  8049. return target;
  8050. }
  8051. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
  8052. {
  8053. ImVec2 scroll = window->Scroll;
  8054. if (window->ScrollTarget.x < FLT_MAX)
  8055. {
  8056. float decoration_total_width = window->ScrollbarSizes.x;
  8057. float center_x_ratio = window->ScrollTargetCenterRatio.x;
  8058. float scroll_target_x = window->ScrollTarget.x;
  8059. if (window->ScrollTargetEdgeSnapDist.x > 0.0f)
  8060. {
  8061. float snap_x_min = 0.0f;
  8062. float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width;
  8063. scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);
  8064. }
  8065. scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width);
  8066. }
  8067. if (window->ScrollTarget.y < FLT_MAX)
  8068. {
  8069. float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y;
  8070. float center_y_ratio = window->ScrollTargetCenterRatio.y;
  8071. float scroll_target_y = window->ScrollTarget.y;
  8072. if (window->ScrollTargetEdgeSnapDist.y > 0.0f)
  8073. {
  8074. float snap_y_min = 0.0f;
  8075. float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height;
  8076. scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);
  8077. }
  8078. scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height);
  8079. }
  8080. scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
  8081. scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
  8082. if (!window->Collapsed && !window->SkipItems)
  8083. {
  8084. scroll.x = ImMin(scroll.x, window->ScrollMax.x);
  8085. scroll.y = ImMin(scroll.y, window->ScrollMax.y);
  8086. }
  8087. return scroll;
  8088. }
  8089. void ImGui::ScrollToItem(ImGuiScrollFlags flags)
  8090. {
  8091. ImGuiContext& g = *GImGui;
  8092. ImGuiWindow* window = g.CurrentWindow;
  8093. ScrollToRectEx(window, g.LastItemData.NavRect, flags);
  8094. }
  8095. void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
  8096. {
  8097. ScrollToRectEx(window, item_rect, flags);
  8098. }
  8099. // Scroll to keep newly navigated item fully into view
  8100. ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
  8101. {
  8102. ImGuiContext& g = *GImGui;
  8103. ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
  8104. //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
  8105. // Check that only one behavior is selected per axis
  8106. IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
  8107. IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
  8108. // Defaults
  8109. ImGuiScrollFlags in_flags = flags;
  8110. if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
  8111. flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
  8112. if ((flags & ImGuiScrollFlags_MaskY_) == 0)
  8113. flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
  8114. const bool fully_visible_x = item_rect.Min.x >= window_rect.Min.x && item_rect.Max.x <= window_rect.Max.x;
  8115. const bool fully_visible_y = item_rect.Min.y >= window_rect.Min.y && item_rect.Max.y <= window_rect.Max.y;
  8116. const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= window_rect.GetWidth();
  8117. const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= window_rect.GetHeight();
  8118. if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
  8119. {
  8120. if (item_rect.Min.x < window_rect.Min.x || !can_be_fully_visible_x)
  8121. SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
  8122. else if (item_rect.Max.x >= window_rect.Max.x)
  8123. SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
  8124. }
  8125. else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
  8126. {
  8127. float target_x = can_be_fully_visible_x ? ImFloor((item_rect.Min.x + item_rect.Max.x - window->InnerRect.GetWidth()) * 0.5f) : item_rect.Min.x;
  8128. SetScrollFromPosX(window, target_x - window->Pos.x, 0.0f);
  8129. }
  8130. if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
  8131. {
  8132. if (item_rect.Min.y < window_rect.Min.y || !can_be_fully_visible_y)
  8133. SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
  8134. else if (item_rect.Max.y >= window_rect.Max.y)
  8135. SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
  8136. }
  8137. else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
  8138. {
  8139. float target_y = can_be_fully_visible_y ? ImFloor((item_rect.Min.y + item_rect.Max.y - window->InnerRect.GetHeight()) * 0.5f) : item_rect.Min.y;
  8140. SetScrollFromPosY(window, target_y - window->Pos.y, 0.0f);
  8141. }
  8142. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  8143. ImVec2 delta_scroll = next_scroll - window->Scroll;
  8144. // Also scroll parent window to keep us into view if necessary
  8145. if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
  8146. {
  8147. // FIXME-SCROLL: May be an option?
  8148. if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
  8149. in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
  8150. if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
  8151. in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
  8152. delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
  8153. }
  8154. return delta_scroll;
  8155. }
  8156. float ImGui::GetScrollX()
  8157. {
  8158. ImGuiWindow* window = GImGui->CurrentWindow;
  8159. return window->Scroll.x;
  8160. }
  8161. float ImGui::GetScrollY()
  8162. {
  8163. ImGuiWindow* window = GImGui->CurrentWindow;
  8164. return window->Scroll.y;
  8165. }
  8166. float ImGui::GetScrollMaxX()
  8167. {
  8168. ImGuiWindow* window = GImGui->CurrentWindow;
  8169. return window->ScrollMax.x;
  8170. }
  8171. float ImGui::GetScrollMaxY()
  8172. {
  8173. ImGuiWindow* window = GImGui->CurrentWindow;
  8174. return window->ScrollMax.y;
  8175. }
  8176. void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
  8177. {
  8178. window->ScrollTarget.x = scroll_x;
  8179. window->ScrollTargetCenterRatio.x = 0.0f;
  8180. window->ScrollTargetEdgeSnapDist.x = 0.0f;
  8181. }
  8182. void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
  8183. {
  8184. window->ScrollTarget.y = scroll_y;
  8185. window->ScrollTargetCenterRatio.y = 0.0f;
  8186. window->ScrollTargetEdgeSnapDist.y = 0.0f;
  8187. }
  8188. void ImGui::SetScrollX(float scroll_x)
  8189. {
  8190. ImGuiContext& g = *GImGui;
  8191. SetScrollX(g.CurrentWindow, scroll_x);
  8192. }
  8193. void ImGui::SetScrollY(float scroll_y)
  8194. {
  8195. ImGuiContext& g = *GImGui;
  8196. SetScrollY(g.CurrentWindow, scroll_y);
  8197. }
  8198. // Note that a local position will vary depending on initial scroll value,
  8199. // This is a little bit confusing so bear with us:
  8200. // - local_pos = (absolution_pos - window->Pos)
  8201. // - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
  8202. // and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
  8203. // - They mostly exist because of legacy API.
  8204. // Following the rules above, when trying to work with scrolling code, consider that:
  8205. // - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
  8206. // - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
  8207. // We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
  8208. void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
  8209. {
  8210. IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
  8211. window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset
  8212. window->ScrollTargetCenterRatio.x = center_x_ratio;
  8213. window->ScrollTargetEdgeSnapDist.x = 0.0f;
  8214. }
  8215. void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
  8216. {
  8217. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  8218. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect;
  8219. local_y -= decoration_up_height;
  8220. window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset
  8221. window->ScrollTargetCenterRatio.y = center_y_ratio;
  8222. window->ScrollTargetEdgeSnapDist.y = 0.0f;
  8223. }
  8224. void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
  8225. {
  8226. ImGuiContext& g = *GImGui;
  8227. SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
  8228. }
  8229. void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
  8230. {
  8231. ImGuiContext& g = *GImGui;
  8232. SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
  8233. }
  8234. // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
  8235. void ImGui::SetScrollHereX(float center_x_ratio)
  8236. {
  8237. ImGuiContext& g = *GImGui;
  8238. ImGuiWindow* window = g.CurrentWindow;
  8239. float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
  8240. float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
  8241. SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
  8242. // Tweak: snap on edges when aiming at an item very close to the edge
  8243. window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
  8244. }
  8245. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  8246. void ImGui::SetScrollHereY(float center_y_ratio)
  8247. {
  8248. ImGuiContext& g = *GImGui;
  8249. ImGuiWindow* window = g.CurrentWindow;
  8250. float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
  8251. float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
  8252. SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
  8253. // Tweak: snap on edges when aiming at an item very close to the edge
  8254. window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
  8255. }
  8256. //-----------------------------------------------------------------------------
  8257. // [SECTION] TOOLTIPS
  8258. //-----------------------------------------------------------------------------
  8259. void ImGui::BeginTooltip()
  8260. {
  8261. BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
  8262. }
  8263. void ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
  8264. {
  8265. ImGuiContext& g = *GImGui;
  8266. if (g.DragDropWithinSource || g.DragDropWithinTarget)
  8267. {
  8268. // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
  8269. // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
  8270. // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
  8271. //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
  8272. ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
  8273. SetNextWindowPos(tooltip_pos);
  8274. SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
  8275. //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
  8276. tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
  8277. }
  8278. char window_name[16];
  8279. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
  8280. if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
  8281. if (ImGuiWindow* window = FindWindowByName(window_name))
  8282. if (window->Active)
  8283. {
  8284. // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
  8285. window->Hidden = true;
  8286. window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
  8287. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
  8288. }
  8289. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
  8290. Begin(window_name, NULL, flags | extra_window_flags);
  8291. }
  8292. void ImGui::EndTooltip()
  8293. {
  8294. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  8295. End();
  8296. }
  8297. void ImGui::SetTooltipV(const char* fmt, va_list args)
  8298. {
  8299. BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);
  8300. TextV(fmt, args);
  8301. EndTooltip();
  8302. }
  8303. void ImGui::SetTooltip(const char* fmt, ...)
  8304. {
  8305. va_list args;
  8306. va_start(args, fmt);
  8307. SetTooltipV(fmt, args);
  8308. va_end(args);
  8309. }
  8310. //-----------------------------------------------------------------------------
  8311. // [SECTION] POPUPS
  8312. //-----------------------------------------------------------------------------
  8313. // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
  8314. bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
  8315. {
  8316. ImGuiContext& g = *GImGui;
  8317. if (popup_flags & ImGuiPopupFlags_AnyPopupId)
  8318. {
  8319. // Return true if any popup is open at the current BeginPopup() level of the popup stack
  8320. // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
  8321. IM_ASSERT(id == 0);
  8322. if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
  8323. return g.OpenPopupStack.Size > 0;
  8324. else
  8325. return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
  8326. }
  8327. else
  8328. {
  8329. if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
  8330. {
  8331. // Return true if the popup is open anywhere in the popup stack
  8332. for (int n = 0; n < g.OpenPopupStack.Size; n++)
  8333. if (g.OpenPopupStack[n].PopupId == id)
  8334. return true;
  8335. return false;
  8336. }
  8337. else
  8338. {
  8339. // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
  8340. return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
  8341. }
  8342. }
  8343. }
  8344. bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
  8345. {
  8346. ImGuiContext& g = *GImGui;
  8347. ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
  8348. if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
  8349. IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
  8350. return IsPopupOpen(id, popup_flags);
  8351. }
  8352. ImGuiWindow* ImGui::GetTopMostPopupModal()
  8353. {
  8354. ImGuiContext& g = *GImGui;
  8355. for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
  8356. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  8357. if (popup->Flags & ImGuiWindowFlags_Modal)
  8358. return popup;
  8359. return NULL;
  8360. }
  8361. ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
  8362. {
  8363. ImGuiContext& g = *GImGui;
  8364. for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
  8365. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  8366. if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
  8367. return popup;
  8368. return NULL;
  8369. }
  8370. void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
  8371. {
  8372. ImGuiContext& g = *GImGui;
  8373. ImGuiID id = g.CurrentWindow->GetID(str_id);
  8374. IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X\n", str_id, id);
  8375. OpenPopupEx(id, popup_flags);
  8376. }
  8377. void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
  8378. {
  8379. OpenPopupEx(id, popup_flags);
  8380. }
  8381. // Mark popup as open (toggle toward open state).
  8382. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  8383. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  8384. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  8385. void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
  8386. {
  8387. ImGuiContext& g = *GImGui;
  8388. ImGuiWindow* parent_window = g.CurrentWindow;
  8389. const int current_stack_size = g.BeginPopupStack.Size;
  8390. if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
  8391. if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
  8392. return;
  8393. ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
  8394. popup_ref.PopupId = id;
  8395. popup_ref.Window = NULL;
  8396. popup_ref.BackupNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type).
  8397. popup_ref.OpenFrameCount = g.FrameCount;
  8398. popup_ref.OpenParentId = parent_window->IDStack.back();
  8399. popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
  8400. popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
  8401. IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
  8402. if (g.OpenPopupStack.Size < current_stack_size + 1)
  8403. {
  8404. g.OpenPopupStack.push_back(popup_ref);
  8405. }
  8406. else
  8407. {
  8408. // 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
  8409. // 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
  8410. // 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.
  8411. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
  8412. {
  8413. g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
  8414. }
  8415. else
  8416. {
  8417. // Close child popups if any, then flag popup for open/reopen
  8418. ClosePopupToLevel(current_stack_size, false);
  8419. g.OpenPopupStack.push_back(popup_ref);
  8420. }
  8421. // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
  8422. // This is equivalent to what ClosePopupToLevel() does.
  8423. //if (g.OpenPopupStack[current_stack_size].PopupId == id)
  8424. // FocusWindow(parent_window);
  8425. }
  8426. }
  8427. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  8428. // This function closes any popups that are over 'ref_window'.
  8429. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
  8430. {
  8431. ImGuiContext& g = *GImGui;
  8432. if (g.OpenPopupStack.Size == 0)
  8433. return;
  8434. // Don't close our own child popup windows.
  8435. int popup_count_to_keep = 0;
  8436. if (ref_window)
  8437. {
  8438. // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
  8439. for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
  8440. {
  8441. ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
  8442. if (!popup.Window)
  8443. continue;
  8444. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  8445. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  8446. continue;
  8447. // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
  8448. // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
  8449. // Window -> Popup1 -> Popup2 -> Popup3
  8450. // - Each popups may contain child windows, which is why we compare ->RootWindow!
  8451. // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
  8452. bool ref_window_is_descendent_of_popup = false;
  8453. for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
  8454. if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
  8455. if (IsWindowWithinBeginStackOf(ref_window, popup_window))
  8456. {
  8457. ref_window_is_descendent_of_popup = true;
  8458. break;
  8459. }
  8460. if (!ref_window_is_descendent_of_popup)
  8461. break;
  8462. }
  8463. }
  8464. if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
  8465. {
  8466. IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
  8467. ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
  8468. }
  8469. }
  8470. void ImGui::ClosePopupsExceptModals()
  8471. {
  8472. ImGuiContext& g = *GImGui;
  8473. int popup_count_to_keep;
  8474. for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
  8475. {
  8476. ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
  8477. if (!window || window->Flags & ImGuiWindowFlags_Modal)
  8478. break;
  8479. }
  8480. if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
  8481. ClosePopupToLevel(popup_count_to_keep, true);
  8482. }
  8483. void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
  8484. {
  8485. ImGuiContext& g = *GImGui;
  8486. IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
  8487. IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
  8488. // Trim open popup stack
  8489. ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
  8490. ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
  8491. g.OpenPopupStack.resize(remaining);
  8492. if (restore_focus_to_window_under_popup)
  8493. {
  8494. ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
  8495. if (focus_window && !focus_window->WasActive && popup_window)
  8496. {
  8497. // Fallback
  8498. FocusTopMostWindowUnderOne(popup_window, NULL);
  8499. }
  8500. else
  8501. {
  8502. if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
  8503. focus_window = NavRestoreLastChildNavWindow(focus_window);
  8504. FocusWindow(focus_window);
  8505. }
  8506. }
  8507. }
  8508. // Close the popup we have begin-ed into.
  8509. void ImGui::CloseCurrentPopup()
  8510. {
  8511. ImGuiContext& g = *GImGui;
  8512. int popup_idx = g.BeginPopupStack.Size - 1;
  8513. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  8514. return;
  8515. // Closing a menu closes its top-most parent popup (unless a modal)
  8516. while (popup_idx > 0)
  8517. {
  8518. ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
  8519. ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
  8520. bool close_parent = false;
  8521. if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
  8522. if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
  8523. close_parent = true;
  8524. if (!close_parent)
  8525. break;
  8526. popup_idx--;
  8527. }
  8528. IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
  8529. ClosePopupToLevel(popup_idx, true);
  8530. // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
  8531. // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
  8532. // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
  8533. if (ImGuiWindow* window = g.NavWindow)
  8534. window->DC.NavHideHighlightOneFrame = true;
  8535. }
  8536. // Attention! BeginPopup() adds default flags which BeginPopupEx()!
  8537. bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
  8538. {
  8539. ImGuiContext& g = *GImGui;
  8540. if (!IsPopupOpen(id, ImGuiPopupFlags_None))
  8541. {
  8542. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  8543. return false;
  8544. }
  8545. char name[20];
  8546. if (flags & ImGuiWindowFlags_ChildMenu)
  8547. ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
  8548. else
  8549. ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
  8550. flags |= ImGuiWindowFlags_Popup;
  8551. bool is_open = Begin(name, NULL, flags);
  8552. if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
  8553. EndPopup();
  8554. return is_open;
  8555. }
  8556. bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
  8557. {
  8558. ImGuiContext& g = *GImGui;
  8559. if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
  8560. {
  8561. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  8562. return false;
  8563. }
  8564. flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
  8565. ImGuiID id = g.CurrentWindow->GetID(str_id);
  8566. return BeginPopupEx(id, flags);
  8567. }
  8568. // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
  8569. // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
  8570. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
  8571. {
  8572. ImGuiContext& g = *GImGui;
  8573. ImGuiWindow* window = g.CurrentWindow;
  8574. const ImGuiID id = window->GetID(name);
  8575. if (!IsPopupOpen(id, ImGuiPopupFlags_None))
  8576. {
  8577. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  8578. return false;
  8579. }
  8580. // Center modal windows by default for increased visibility
  8581. // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
  8582. // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
  8583. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
  8584. {
  8585. const ImGuiViewport* viewport = GetMainViewport();
  8586. SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
  8587. }
  8588. flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
  8589. const bool is_open = Begin(name, p_open, flags);
  8590. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  8591. {
  8592. EndPopup();
  8593. if (is_open)
  8594. ClosePopupToLevel(g.BeginPopupStack.Size, true);
  8595. return false;
  8596. }
  8597. return is_open;
  8598. }
  8599. void ImGui::EndPopup()
  8600. {
  8601. ImGuiContext& g = *GImGui;
  8602. ImGuiWindow* window = g.CurrentWindow;
  8603. IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  8604. IM_ASSERT(g.BeginPopupStack.Size > 0);
  8605. // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
  8606. if (g.NavWindow == window)
  8607. NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
  8608. // Child-popups don't need to be laid out
  8609. IM_ASSERT(g.WithinEndChild == false);
  8610. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  8611. g.WithinEndChild = true;
  8612. End();
  8613. g.WithinEndChild = false;
  8614. }
  8615. // Helper to open a popup if mouse button is released over the item
  8616. // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
  8617. void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
  8618. {
  8619. ImGuiContext& g = *GImGui;
  8620. ImGuiWindow* window = g.CurrentWindow;
  8621. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8622. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8623. {
  8624. ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  8625. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  8626. OpenPopupEx(id, popup_flags);
  8627. }
  8628. }
  8629. // This is a helper to handle the simplest case of associating one named popup to one given widget.
  8630. // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
  8631. // - To create a popup with a specific identifier, pass it in str_id.
  8632. // - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
  8633. // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
  8634. // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
  8635. // This is essentially the same as:
  8636. // id = str_id ? GetID(str_id) : GetItemID();
  8637. // OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
  8638. // return BeginPopup(id);
  8639. // Which is essentially the same as:
  8640. // id = str_id ? GetID(str_id) : GetItemID();
  8641. // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
  8642. // OpenPopup(id);
  8643. // return BeginPopup(id);
  8644. // The main difference being that this is tweaked to avoid computing the ID twice.
  8645. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
  8646. {
  8647. ImGuiContext& g = *GImGui;
  8648. ImGuiWindow* window = g.CurrentWindow;
  8649. if (window->SkipItems)
  8650. return false;
  8651. ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  8652. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  8653. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8654. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8655. OpenPopupEx(id, popup_flags);
  8656. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8657. }
  8658. bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
  8659. {
  8660. ImGuiContext& g = *GImGui;
  8661. ImGuiWindow* window = g.CurrentWindow;
  8662. if (!str_id)
  8663. str_id = "window_context";
  8664. ImGuiID id = window->GetID(str_id);
  8665. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8666. if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8667. if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
  8668. OpenPopupEx(id, popup_flags);
  8669. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8670. }
  8671. bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
  8672. {
  8673. ImGuiContext& g = *GImGui;
  8674. ImGuiWindow* window = g.CurrentWindow;
  8675. if (!str_id)
  8676. str_id = "void_context";
  8677. ImGuiID id = window->GetID(str_id);
  8678. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8679. if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
  8680. if (GetTopMostPopupModal() == NULL)
  8681. OpenPopupEx(id, popup_flags);
  8682. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8683. }
  8684. // 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.)
  8685. // 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.
  8686. // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
  8687. // information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
  8688. // this allows us to have tooltips/popups displayed out of the parent viewport.)
  8689. ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
  8690. {
  8691. ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
  8692. //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
  8693. //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
  8694. // Combo Box policy (we want a connecting edge)
  8695. if (policy == ImGuiPopupPositionPolicy_ComboBox)
  8696. {
  8697. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
  8698. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  8699. {
  8700. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  8701. if (n != -1 && dir == *last_dir) // Already tried this direction?
  8702. continue;
  8703. ImVec2 pos;
  8704. if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
  8705. if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
  8706. if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
  8707. if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
  8708. if (!r_outer.Contains(ImRect(pos, pos + size)))
  8709. continue;
  8710. *last_dir = dir;
  8711. return pos;
  8712. }
  8713. }
  8714. // Tooltip and Default popup policy
  8715. // (Always first try the direction we used on the last frame, if any)
  8716. if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
  8717. {
  8718. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
  8719. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  8720. {
  8721. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  8722. if (n != -1 && dir == *last_dir) // Already tried this direction?
  8723. continue;
  8724. const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
  8725. const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
  8726. // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
  8727. if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
  8728. continue;
  8729. if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
  8730. continue;
  8731. ImVec2 pos;
  8732. pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
  8733. pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
  8734. // Clamp top-left corner of popup
  8735. pos.x = ImMax(pos.x, r_outer.Min.x);
  8736. pos.y = ImMax(pos.y, r_outer.Min.y);
  8737. *last_dir = dir;
  8738. return pos;
  8739. }
  8740. }
  8741. // Fallback when not enough room:
  8742. *last_dir = ImGuiDir_None;
  8743. // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  8744. if (policy == ImGuiPopupPositionPolicy_Tooltip)
  8745. return ref_pos + ImVec2(2, 2);
  8746. // Otherwise try to keep within display
  8747. ImVec2 pos = ref_pos;
  8748. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  8749. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  8750. return pos;
  8751. }
  8752. // Note that this is used for popups, which can overlap the non work-area of individual viewports.
  8753. ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
  8754. {
  8755. ImGuiContext& g = *GImGui;
  8756. IM_UNUSED(window);
  8757. ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();
  8758. ImVec2 padding = g.Style.DisplaySafeAreaPadding;
  8759. r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
  8760. return r_screen;
  8761. }
  8762. ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
  8763. {
  8764. ImGuiContext& g = *GImGui;
  8765. ImRect r_outer = GetPopupAllowedExtentRect(window);
  8766. if (window->Flags & ImGuiWindowFlags_ChildMenu)
  8767. {
  8768. // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
  8769. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  8770. IM_ASSERT(g.CurrentWindow == window);
  8771. ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window;
  8772. float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
  8773. ImRect r_avoid;
  8774. if (parent_window->DC.MenuBarAppending)
  8775. r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
  8776. else
  8777. r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
  8778. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
  8779. }
  8780. if (window->Flags & ImGuiWindowFlags_Popup)
  8781. {
  8782. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
  8783. }
  8784. if (window->Flags & ImGuiWindowFlags_Tooltip)
  8785. {
  8786. // Position tooltip (always follows mouse)
  8787. float sc = g.Style.MouseCursorScale;
  8788. ImVec2 ref_pos = NavCalcPreferredRefPos();
  8789. ImRect r_avoid;
  8790. if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
  8791. r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
  8792. else
  8793. r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
  8794. return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
  8795. }
  8796. IM_ASSERT(0);
  8797. return window->Pos;
  8798. }
  8799. //-----------------------------------------------------------------------------
  8800. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  8801. //-----------------------------------------------------------------------------
  8802. // FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
  8803. // In our terminology those should be interchangeable, yet right now this is super confusing.
  8804. // Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
  8805. void ImGui::SetNavWindow(ImGuiWindow* window)
  8806. {
  8807. ImGuiContext& g = *GImGui;
  8808. if (g.NavWindow != window)
  8809. {
  8810. IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
  8811. g.NavWindow = window;
  8812. }
  8813. g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
  8814. NavUpdateAnyRequestFlag();
  8815. }
  8816. void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
  8817. {
  8818. ImGuiContext& g = *GImGui;
  8819. IM_ASSERT(g.NavWindow != NULL);
  8820. IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
  8821. g.NavId = id;
  8822. g.NavLayer = nav_layer;
  8823. g.NavFocusScopeId = focus_scope_id;
  8824. g.NavWindow->NavLastIds[nav_layer] = id;
  8825. g.NavWindow->NavRectRel[nav_layer] = rect_rel;
  8826. }
  8827. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
  8828. {
  8829. ImGuiContext& g = *GImGui;
  8830. IM_ASSERT(id != 0);
  8831. if (g.NavWindow != window)
  8832. SetNavWindow(window);
  8833. // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
  8834. // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
  8835. const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
  8836. g.NavId = id;
  8837. g.NavLayer = nav_layer;
  8838. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  8839. window->NavLastIds[nav_layer] = id;
  8840. if (g.LastItemData.ID == id)
  8841. window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
  8842. if (g.ActiveIdSource == ImGuiInputSource_Nav)
  8843. g.NavDisableMouseHover = true;
  8844. else
  8845. g.NavDisableHighlight = true;
  8846. }
  8847. ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
  8848. {
  8849. if (ImFabs(dx) > ImFabs(dy))
  8850. return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
  8851. return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
  8852. }
  8853. static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
  8854. {
  8855. if (a1 < b0)
  8856. return a1 - b0;
  8857. if (b1 < a0)
  8858. return a0 - b1;
  8859. return 0.0f;
  8860. }
  8861. static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
  8862. {
  8863. if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
  8864. {
  8865. r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
  8866. r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
  8867. }
  8868. else // FIXME: PageUp/PageDown are leaving move_dir == None
  8869. {
  8870. r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
  8871. r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
  8872. }
  8873. }
  8874. // Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
  8875. static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
  8876. {
  8877. ImGuiContext& g = *GImGui;
  8878. ImGuiWindow* window = g.CurrentWindow;
  8879. if (g.NavLayer != window->DC.NavLayerCurrent)
  8880. return false;
  8881. // FIXME: Those are not good variables names
  8882. ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle
  8883. const ImRect curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
  8884. g.NavScoringDebugCount++;
  8885. // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
  8886. if (window->ParentWindow == g.NavWindow)
  8887. {
  8888. IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
  8889. if (!window->ClipRect.Overlaps(cand))
  8890. return false;
  8891. cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
  8892. }
  8893. // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
  8894. // For example, this ensures that items in one column are not reached when moving vertically from items in another column.
  8895. NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
  8896. // Compute distance between boxes
  8897. // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
  8898. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
  8899. float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
  8900. if (dby != 0.0f && dbx != 0.0f)
  8901. dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
  8902. float dist_box = ImFabs(dbx) + ImFabs(dby);
  8903. // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
  8904. float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
  8905. float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
  8906. float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
  8907. // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
  8908. ImGuiDir quadrant;
  8909. float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
  8910. if (dbx != 0.0f || dby != 0.0f)
  8911. {
  8912. // For non-overlapping boxes, use distance between boxes
  8913. dax = dbx;
  8914. day = dby;
  8915. dist_axial = dist_box;
  8916. quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
  8917. }
  8918. else if (dcx != 0.0f || dcy != 0.0f)
  8919. {
  8920. // For overlapping boxes with different centers, use distance between centers
  8921. dax = dcx;
  8922. day = dcy;
  8923. dist_axial = dist_center;
  8924. quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
  8925. }
  8926. else
  8927. {
  8928. // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
  8929. quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
  8930. }
  8931. #if IMGUI_DEBUG_NAV_SCORING
  8932. char buf[128];
  8933. if (IsMouseHoveringRect(cand.Min, cand.Max))
  8934. {
  8935. ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
  8936. ImDrawList* draw_list = GetForegroundDrawList(window);
  8937. draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
  8938. draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
  8939. draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
  8940. draw_list->AddText(cand.Max, ~0U, buf);
  8941. }
  8942. else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
  8943. {
  8944. if (quadrant == g.NavMoveDir)
  8945. {
  8946. ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
  8947. ImDrawList* draw_list = GetForegroundDrawList(window);
  8948. draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
  8949. draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
  8950. }
  8951. }
  8952. #endif
  8953. // Is it in the quadrant we're interested in moving to?
  8954. bool new_best = false;
  8955. const ImGuiDir move_dir = g.NavMoveDir;
  8956. if (quadrant == move_dir)
  8957. {
  8958. // Does it beat the current best candidate?
  8959. if (dist_box < result->DistBox)
  8960. {
  8961. result->DistBox = dist_box;
  8962. result->DistCenter = dist_center;
  8963. return true;
  8964. }
  8965. if (dist_box == result->DistBox)
  8966. {
  8967. // Try using distance between center points to break ties
  8968. if (dist_center < result->DistCenter)
  8969. {
  8970. result->DistCenter = dist_center;
  8971. new_best = true;
  8972. }
  8973. else if (dist_center == result->DistCenter)
  8974. {
  8975. // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
  8976. // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
  8977. // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
  8978. if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
  8979. new_best = true;
  8980. }
  8981. }
  8982. }
  8983. // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
  8984. // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
  8985. // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
  8986. // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
  8987. // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
  8988. if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
  8989. if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
  8990. if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
  8991. {
  8992. result->DistAxial = dist_axial;
  8993. new_best = true;
  8994. }
  8995. return new_best;
  8996. }
  8997. static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
  8998. {
  8999. ImGuiContext& g = *GImGui;
  9000. ImGuiWindow* window = g.CurrentWindow;
  9001. result->Window = window;
  9002. result->ID = g.LastItemData.ID;
  9003. result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
  9004. result->InFlags = g.LastItemData.InFlags;
  9005. result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
  9006. }
  9007. // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
  9008. // This is called after LastItemData is set.
  9009. static void ImGui::NavProcessItem()
  9010. {
  9011. ImGuiContext& g = *GImGui;
  9012. ImGuiWindow* window = g.CurrentWindow;
  9013. const ImGuiID id = g.LastItemData.ID;
  9014. const ImRect nav_bb = g.LastItemData.NavRect;
  9015. const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
  9016. // Process Init Request
  9017. if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
  9018. {
  9019. // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
  9020. const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
  9021. if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
  9022. {
  9023. g.NavInitResultId = id;
  9024. g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
  9025. }
  9026. if (candidate_for_nav_default_focus)
  9027. {
  9028. g.NavInitRequest = false; // Found a match, clear request
  9029. NavUpdateAnyRequestFlag();
  9030. }
  9031. }
  9032. // Process Move Request (scoring for navigation)
  9033. // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
  9034. if (g.NavMoveScoringItems)
  9035. {
  9036. const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
  9037. const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
  9038. if (is_tabbing)
  9039. {
  9040. if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi))
  9041. NavProcessItemForTabbingRequest(id);
  9042. }
  9043. else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))
  9044. {
  9045. ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  9046. if (!is_tabbing)
  9047. {
  9048. if (NavScoreItem(result))
  9049. NavApplyItemToResult(result);
  9050. // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
  9051. const float VISIBLE_RATIO = 0.70f;
  9052. if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
  9053. if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
  9054. if (NavScoreItem(&g.NavMoveResultLocalVisible))
  9055. NavApplyItemToResult(&g.NavMoveResultLocalVisible);
  9056. }
  9057. }
  9058. }
  9059. // Update window-relative bounding box of navigated item
  9060. if (g.NavId == id)
  9061. {
  9062. if (g.NavWindow != window)
  9063. SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
  9064. g.NavLayer = window->DC.NavLayerCurrent;
  9065. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  9066. g.NavIdIsAlive = true;
  9067. window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
  9068. }
  9069. }
  9070. // Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
  9071. // Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
  9072. // - Case 1: no nav/active id: set result to first eligible item, stop storing.
  9073. // - Case 2: tab forward: on ref id set counter, on counter elapse store result
  9074. // - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
  9075. // - Case 4: tab backward: store all results, on ref id pick prev, stop storing
  9076. // - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
  9077. void ImGui::NavProcessItemForTabbingRequest(ImGuiID id)
  9078. {
  9079. ImGuiContext& g = *GImGui;
  9080. // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
  9081. ImGuiNavItemData* result = &g.NavMoveResultLocal;
  9082. if (g.NavTabbingDir == +1)
  9083. {
  9084. // Tab Forward or SetKeyboardFocusHere() with >= 0
  9085. if (g.NavTabbingResultFirst.ID == 0)
  9086. NavApplyItemToResult(&g.NavTabbingResultFirst);
  9087. if (--g.NavTabbingCounter == 0)
  9088. NavMoveRequestResolveWithLastItem(result);
  9089. else if (g.NavId == id)
  9090. g.NavTabbingCounter = 1;
  9091. }
  9092. else if (g.NavTabbingDir == -1)
  9093. {
  9094. // Tab Backward
  9095. if (g.NavId == id)
  9096. {
  9097. if (result->ID)
  9098. {
  9099. g.NavMoveScoringItems = false;
  9100. NavUpdateAnyRequestFlag();
  9101. }
  9102. }
  9103. else
  9104. {
  9105. NavApplyItemToResult(result);
  9106. }
  9107. }
  9108. else if (g.NavTabbingDir == 0)
  9109. {
  9110. // Tab Init
  9111. if (g.NavTabbingResultFirst.ID == 0)
  9112. NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst);
  9113. }
  9114. }
  9115. bool ImGui::NavMoveRequestButNoResultYet()
  9116. {
  9117. ImGuiContext& g = *GImGui;
  9118. return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
  9119. }
  9120. // FIXME: ScoringRect is not set
  9121. void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
  9122. {
  9123. ImGuiContext& g = *GImGui;
  9124. IM_ASSERT(g.NavWindow != NULL);
  9125. if (move_flags & ImGuiNavMoveFlags_Tabbing)
  9126. move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
  9127. g.NavMoveSubmitted = g.NavMoveScoringItems = true;
  9128. g.NavMoveDir = move_dir;
  9129. g.NavMoveDirForDebug = move_dir;
  9130. g.NavMoveClipDir = clip_dir;
  9131. g.NavMoveFlags = move_flags;
  9132. g.NavMoveScrollFlags = scroll_flags;
  9133. g.NavMoveForwardToNextFrame = false;
  9134. g.NavMoveKeyMods = g.IO.KeyMods;
  9135. g.NavMoveResultLocal.Clear();
  9136. g.NavMoveResultLocalVisible.Clear();
  9137. g.NavMoveResultOther.Clear();
  9138. g.NavTabbingCounter = 0;
  9139. g.NavTabbingResultFirst.Clear();
  9140. NavUpdateAnyRequestFlag();
  9141. }
  9142. void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
  9143. {
  9144. ImGuiContext& g = *GImGui;
  9145. g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
  9146. NavApplyItemToResult(result);
  9147. NavUpdateAnyRequestFlag();
  9148. }
  9149. void ImGui::NavMoveRequestCancel()
  9150. {
  9151. ImGuiContext& g = *GImGui;
  9152. g.NavMoveSubmitted = g.NavMoveScoringItems = false;
  9153. NavUpdateAnyRequestFlag();
  9154. }
  9155. // Forward will reuse the move request again on the next frame (generally with modifications done to it)
  9156. void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
  9157. {
  9158. ImGuiContext& g = *GImGui;
  9159. IM_ASSERT(g.NavMoveForwardToNextFrame == false);
  9160. NavMoveRequestCancel();
  9161. g.NavMoveForwardToNextFrame = true;
  9162. g.NavMoveDir = move_dir;
  9163. g.NavMoveClipDir = clip_dir;
  9164. g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
  9165. g.NavMoveScrollFlags = scroll_flags;
  9166. }
  9167. // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
  9168. // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
  9169. void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
  9170. {
  9171. ImGuiContext& g = *GImGui;
  9172. IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
  9173. // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
  9174. if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
  9175. g.NavMoveFlags |= wrap_flags;
  9176. }
  9177. // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
  9178. // This way we could find the last focused window among our children. It would be much less confusing this way?
  9179. static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
  9180. {
  9181. ImGuiWindow* parent = nav_window;
  9182. while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  9183. parent = parent->ParentWindow;
  9184. if (parent && parent != nav_window)
  9185. parent->NavLastChildNavWindow = nav_window;
  9186. }
  9187. // Restore the last focused child.
  9188. // Call when we are expected to land on the Main Layer (0) after FocusWindow()
  9189. static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
  9190. {
  9191. if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
  9192. return window->NavLastChildNavWindow;
  9193. return window;
  9194. }
  9195. void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
  9196. {
  9197. ImGuiContext& g = *GImGui;
  9198. if (layer == ImGuiNavLayer_Main)
  9199. {
  9200. ImGuiWindow* prev_nav_window = g.NavWindow;
  9201. g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); // FIXME-NAV: Should clear ongoing nav requests?
  9202. if (prev_nav_window)
  9203. IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
  9204. }
  9205. ImGuiWindow* window = g.NavWindow;
  9206. if (window->NavLastIds[layer] != 0)
  9207. {
  9208. SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
  9209. }
  9210. else
  9211. {
  9212. g.NavLayer = layer;
  9213. NavInitWindow(window, true);
  9214. }
  9215. }
  9216. void ImGui::NavRestoreHighlightAfterMove()
  9217. {
  9218. ImGuiContext& g = *GImGui;
  9219. g.NavDisableHighlight = false;
  9220. g.NavDisableMouseHover = g.NavMousePosDirty = true;
  9221. }
  9222. static inline void ImGui::NavUpdateAnyRequestFlag()
  9223. {
  9224. ImGuiContext& g = *GImGui;
  9225. g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
  9226. if (g.NavAnyRequest)
  9227. IM_ASSERT(g.NavWindow != NULL);
  9228. }
  9229. // This needs to be called before we submit any widget (aka in or before Begin)
  9230. void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
  9231. {
  9232. ImGuiContext& g = *GImGui;
  9233. IM_ASSERT(window == g.NavWindow);
  9234. if (window->Flags & ImGuiWindowFlags_NoNavInputs)
  9235. {
  9236. g.NavId = g.NavFocusScopeId = 0;
  9237. return;
  9238. }
  9239. bool init_for_nav = false;
  9240. if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
  9241. init_for_nav = true;
  9242. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
  9243. if (init_for_nav)
  9244. {
  9245. SetNavID(0, g.NavLayer, 0, ImRect());
  9246. g.NavInitRequest = true;
  9247. g.NavInitRequestFromMove = false;
  9248. g.NavInitResultId = 0;
  9249. g.NavInitResultRectRel = ImRect();
  9250. NavUpdateAnyRequestFlag();
  9251. }
  9252. else
  9253. {
  9254. g.NavId = window->NavLastIds[0];
  9255. g.NavFocusScopeId = 0;
  9256. }
  9257. }
  9258. static ImVec2 ImGui::NavCalcPreferredRefPos()
  9259. {
  9260. ImGuiContext& g = *GImGui;
  9261. ImGuiWindow* window = g.NavWindow;
  9262. if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
  9263. {
  9264. // Mouse (we need a fallback in case the mouse becomes invalid after being used)
  9265. // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
  9266. // In theory we could move that +1.0f offset in OpenPopupEx()
  9267. ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
  9268. return ImVec2(p.x + 1.0f, p.y);
  9269. }
  9270. else
  9271. {
  9272. // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
  9273. // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
  9274. ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
  9275. if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
  9276. {
  9277. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  9278. rect_rel.Translate(window->Scroll - next_scroll);
  9279. }
  9280. ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
  9281. ImGuiViewport* viewport = GetMainViewport();
  9282. return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
  9283. }
  9284. }
  9285. float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
  9286. {
  9287. ImGuiContext& g = *GImGui;
  9288. float repeat_delay, repeat_rate;
  9289. GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
  9290. ImGuiKey key_less, key_more;
  9291. if (g.NavInputSource == ImGuiInputSource_Gamepad)
  9292. {
  9293. key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
  9294. key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
  9295. }
  9296. else
  9297. {
  9298. key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
  9299. key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
  9300. }
  9301. float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
  9302. if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
  9303. amount = 0.0f;
  9304. return amount;
  9305. }
  9306. static void ImGui::NavUpdate()
  9307. {
  9308. ImGuiContext& g = *GImGui;
  9309. ImGuiIO& io = g.IO;
  9310. io.WantSetMousePos = false;
  9311. //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
  9312. // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
  9313. // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
  9314. const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  9315. const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
  9316. if (nav_gamepad_active)
  9317. for (ImGuiKey key : nav_gamepad_keys_to_change_source)
  9318. if (IsKeyDown(key))
  9319. g.NavInputSource = ImGuiInputSource_Gamepad;
  9320. const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  9321. const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
  9322. if (nav_keyboard_active)
  9323. for (ImGuiKey key : nav_keyboard_keys_to_change_source)
  9324. if (IsKeyDown(key))
  9325. g.NavInputSource = ImGuiInputSource_Keyboard;
  9326. // Process navigation init request (select first/default focus)
  9327. if (g.NavInitResultId != 0)
  9328. NavInitRequestApplyResult();
  9329. g.NavInitRequest = false;
  9330. g.NavInitRequestFromMove = false;
  9331. g.NavInitResultId = 0;
  9332. g.NavJustMovedToId = 0;
  9333. // Process navigation move request
  9334. if (g.NavMoveSubmitted)
  9335. NavMoveRequestApplyResult();
  9336. g.NavTabbingCounter = 0;
  9337. g.NavMoveSubmitted = g.NavMoveScoringItems = false;
  9338. // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
  9339. bool set_mouse_pos = false;
  9340. if (g.NavMousePosDirty && g.NavIdIsAlive)
  9341. if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
  9342. set_mouse_pos = true;
  9343. g.NavMousePosDirty = false;
  9344. IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
  9345. // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
  9346. if (g.NavWindow)
  9347. NavSaveLastChildNavWindowIntoParent(g.NavWindow);
  9348. if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
  9349. g.NavWindow->NavLastChildNavWindow = NULL;
  9350. // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
  9351. NavUpdateWindowing();
  9352. // Set output flags for user application
  9353. io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
  9354. io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
  9355. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  9356. NavUpdateCancelRequest();
  9357. // Process manual activation request
  9358. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;
  9359. g.NavActivateFlags = ImGuiActivateFlags_None;
  9360. if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  9361. {
  9362. const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
  9363. const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
  9364. const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
  9365. const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
  9366. if (g.ActiveId == 0 && activate_pressed)
  9367. {
  9368. g.NavActivateId = g.NavId;
  9369. g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
  9370. }
  9371. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
  9372. {
  9373. g.NavActivateInputId = g.NavId;
  9374. g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
  9375. }
  9376. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
  9377. g.NavActivateDownId = g.NavId;
  9378. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
  9379. g.NavActivatePressedId = g.NavId;
  9380. }
  9381. if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  9382. g.NavDisableHighlight = true;
  9383. if (g.NavActivateId != 0)
  9384. IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
  9385. // Process programmatic activation request
  9386. // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
  9387. if (g.NavNextActivateId != 0)
  9388. {
  9389. if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)
  9390. g.NavActivateInputId = g.NavNextActivateId;
  9391. else
  9392. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
  9393. g.NavActivateFlags = g.NavNextActivateFlags;
  9394. }
  9395. g.NavNextActivateId = 0;
  9396. // Process move requests
  9397. NavUpdateCreateMoveRequest();
  9398. if (g.NavMoveDir == ImGuiDir_None)
  9399. NavUpdateCreateTabbingRequest();
  9400. NavUpdateAnyRequestFlag();
  9401. g.NavIdIsAlive = false;
  9402. // Scrolling
  9403. if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
  9404. {
  9405. // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
  9406. ImGuiWindow* window = g.NavWindow;
  9407. const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
  9408. const ImGuiDir move_dir = g.NavMoveDir;
  9409. if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
  9410. {
  9411. if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
  9412. SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
  9413. if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
  9414. SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
  9415. }
  9416. // *Normal* Manual scroll with LStick
  9417. // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
  9418. if (nav_gamepad_active)
  9419. {
  9420. const ImVec2 scroll_dir = GetKeyVector2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
  9421. const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
  9422. if (scroll_dir.x != 0.0f && window->ScrollbarX)
  9423. SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
  9424. if (scroll_dir.y != 0.0f)
  9425. SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
  9426. }
  9427. }
  9428. // Always prioritize mouse highlight if navigation is disabled
  9429. if (!nav_keyboard_active && !nav_gamepad_active)
  9430. {
  9431. g.NavDisableHighlight = true;
  9432. g.NavDisableMouseHover = set_mouse_pos = false;
  9433. }
  9434. // Update mouse position if requested
  9435. // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
  9436. if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
  9437. {
  9438. io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
  9439. io.WantSetMousePos = true;
  9440. //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
  9441. }
  9442. // [DEBUG]
  9443. g.NavScoringDebugCount = 0;
  9444. #if IMGUI_DEBUG_NAV_RECTS
  9445. if (g.NavWindow)
  9446. {
  9447. ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
  9448. if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]
  9449. if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
  9450. }
  9451. #endif
  9452. }
  9453. void ImGui::NavInitRequestApplyResult()
  9454. {
  9455. // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
  9456. ImGuiContext& g = *GImGui;
  9457. if (!g.NavWindow)
  9458. return;
  9459. // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
  9460. // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
  9461. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
  9462. SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
  9463. g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
  9464. if (g.NavInitRequestFromMove)
  9465. NavRestoreHighlightAfterMove();
  9466. }
  9467. void ImGui::NavUpdateCreateMoveRequest()
  9468. {
  9469. ImGuiContext& g = *GImGui;
  9470. ImGuiIO& io = g.IO;
  9471. ImGuiWindow* window = g.NavWindow;
  9472. const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  9473. const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  9474. if (g.NavMoveForwardToNextFrame && window != NULL)
  9475. {
  9476. // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
  9477. // (preserve most state, which were already set by the NavMoveRequestForward() function)
  9478. IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
  9479. IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
  9480. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
  9481. }
  9482. else
  9483. {
  9484. // Initiate directional inputs request
  9485. g.NavMoveDir = ImGuiDir_None;
  9486. g.NavMoveFlags = ImGuiNavMoveFlags_None;
  9487. g.NavMoveScrollFlags = ImGuiScrollFlags_None;
  9488. if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
  9489. {
  9490. const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateNavMove;
  9491. if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && ((nav_gamepad_active && IsKeyPressedEx(ImGuiKey_GamepadDpadLeft, repeat_mode)) || (nav_keyboard_active && IsKeyPressedEx(ImGuiKey_LeftArrow, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
  9492. if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressedEx(ImGuiKey_GamepadDpadRight, repeat_mode)) || (nav_keyboard_active && IsKeyPressedEx(ImGuiKey_RightArrow, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
  9493. if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && ((nav_gamepad_active && IsKeyPressedEx(ImGuiKey_GamepadDpadUp, repeat_mode)) || (nav_keyboard_active && IsKeyPressedEx(ImGuiKey_UpArrow, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
  9494. if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && ((nav_gamepad_active && IsKeyPressedEx(ImGuiKey_GamepadDpadDown, repeat_mode)) || (nav_keyboard_active && IsKeyPressedEx(ImGuiKey_DownArrow, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
  9495. }
  9496. g.NavMoveClipDir = g.NavMoveDir;
  9497. g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
  9498. }
  9499. // Update PageUp/PageDown/Home/End scroll
  9500. // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
  9501. float scoring_rect_offset_y = 0.0f;
  9502. if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
  9503. scoring_rect_offset_y = NavUpdatePageUpPageDown();
  9504. if (scoring_rect_offset_y != 0.0f)
  9505. {
  9506. g.NavScoringNoClipRect = window->InnerRect;
  9507. g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
  9508. }
  9509. // [DEBUG] Always send a request
  9510. #if IMGUI_DEBUG_NAV_SCORING
  9511. if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
  9512. g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
  9513. if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
  9514. {
  9515. g.NavMoveDir = g.NavMoveDirForDebug;
  9516. g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
  9517. }
  9518. #endif
  9519. // Submit
  9520. g.NavMoveForwardToNextFrame = false;
  9521. if (g.NavMoveDir != ImGuiDir_None)
  9522. NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
  9523. // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
  9524. if (g.NavMoveSubmitted && g.NavId == 0)
  9525. {
  9526. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
  9527. g.NavInitRequest = g.NavInitRequestFromMove = true;
  9528. g.NavInitResultId = 0;
  9529. g.NavDisableHighlight = false;
  9530. }
  9531. // When using gamepad, we project the reference nav bounding box into window visible area.
  9532. // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad all movements are relative
  9533. // (can't focus a visible object like we can with the mouse).
  9534. if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
  9535. {
  9536. bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
  9537. bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
  9538. ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
  9539. if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
  9540. {
  9541. //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
  9542. float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
  9543. float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
  9544. inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
  9545. inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
  9546. inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
  9547. inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
  9548. window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
  9549. g.NavId = g.NavFocusScopeId = 0;
  9550. }
  9551. }
  9552. // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
  9553. ImRect scoring_rect;
  9554. if (window != NULL)
  9555. {
  9556. ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
  9557. scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
  9558. scoring_rect.TranslateY(scoring_rect_offset_y);
  9559. scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
  9560. scoring_rect.Max.x = scoring_rect.Min.x;
  9561. IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
  9562. //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
  9563. //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
  9564. }
  9565. g.NavScoringRect = scoring_rect;
  9566. g.NavScoringNoClipRect.Add(scoring_rect);
  9567. }
  9568. void ImGui::NavUpdateCreateTabbingRequest()
  9569. {
  9570. ImGuiContext& g = *GImGui;
  9571. ImGuiWindow* window = g.NavWindow;
  9572. IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
  9573. if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
  9574. return;
  9575. const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, true) && !IsActiveIdUsingKey(ImGuiKey_Tab) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
  9576. if (!tab_pressed)
  9577. return;
  9578. // Initiate tabbing request
  9579. // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
  9580. // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
  9581. // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
  9582. //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything
  9583. g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
  9584. ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
  9585. ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
  9586. NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
  9587. g.NavTabbingCounter = -1;
  9588. }
  9589. // Apply result from previous frame navigation directional move request. Always called from NavUpdate()
  9590. void ImGui::NavMoveRequestApplyResult()
  9591. {
  9592. ImGuiContext& g = *GImGui;
  9593. #if IMGUI_DEBUG_NAV_SCORING
  9594. if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
  9595. return;
  9596. #endif
  9597. // Select which result to use
  9598. ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
  9599. // Tabbing forward wrap
  9600. if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
  9601. if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
  9602. result = &g.NavTabbingResultFirst;
  9603. // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
  9604. if (result == NULL)
  9605. {
  9606. if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
  9607. g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
  9608. if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
  9609. NavRestoreHighlightAfterMove();
  9610. return;
  9611. }
  9612. // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
  9613. if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
  9614. if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
  9615. result = &g.NavMoveResultLocalVisible;
  9616. // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
  9617. if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
  9618. if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
  9619. result = &g.NavMoveResultOther;
  9620. IM_ASSERT(g.NavWindow && result->Window);
  9621. // Scroll to keep newly navigated item fully into view.
  9622. if (g.NavLayer == ImGuiNavLayer_Main)
  9623. {
  9624. if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
  9625. {
  9626. // FIXME: Should remove this
  9627. float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
  9628. SetScrollY(result->Window, scroll_target);
  9629. }
  9630. else
  9631. {
  9632. ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
  9633. ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
  9634. }
  9635. }
  9636. if (g.NavWindow != result->Window)
  9637. {
  9638. IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
  9639. g.NavWindow = result->Window;
  9640. }
  9641. if (g.ActiveId != result->ID)
  9642. ClearActiveID();
  9643. if (g.NavId != result->ID)
  9644. {
  9645. // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
  9646. g.NavJustMovedToId = result->ID;
  9647. g.NavJustMovedToFocusScopeId = result->FocusScopeId;
  9648. g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
  9649. }
  9650. // Focus
  9651. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
  9652. SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
  9653. // Tabbing: Activates Inputable or Focus non-Inputable
  9654. if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
  9655. {
  9656. g.NavNextActivateId = result->ID;
  9657. g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
  9658. g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
  9659. }
  9660. // Activate
  9661. if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
  9662. {
  9663. g.NavNextActivateId = result->ID;
  9664. g.NavNextActivateFlags = ImGuiActivateFlags_None;
  9665. }
  9666. // Enable nav highlight
  9667. if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
  9668. NavRestoreHighlightAfterMove();
  9669. }
  9670. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  9671. // FIXME: In order to support e.g. Escape to clear a selection we'll need:
  9672. // - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
  9673. // - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
  9674. static void ImGui::NavUpdateCancelRequest()
  9675. {
  9676. ImGuiContext& g = *GImGui;
  9677. const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  9678. const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  9679. if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, false)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, false)))
  9680. return;
  9681. IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
  9682. if (g.ActiveId != 0)
  9683. {
  9684. if (!IsActiveIdUsingKey(ImGuiKey_Escape) && !IsActiveIdUsingKey(ImGuiKey_NavGamepadCancel))
  9685. ClearActiveID();
  9686. }
  9687. else if (g.NavLayer != ImGuiNavLayer_Main)
  9688. {
  9689. // Leave the "menu" layer
  9690. NavRestoreLayer(ImGuiNavLayer_Main);
  9691. NavRestoreHighlightAfterMove();
  9692. }
  9693. else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
  9694. {
  9695. // Exit child window
  9696. ImGuiWindow* child_window = g.NavWindow;
  9697. ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
  9698. IM_ASSERT(child_window->ChildId != 0);
  9699. ImRect child_rect = child_window->Rect();
  9700. FocusWindow(parent_window);
  9701. SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
  9702. NavRestoreHighlightAfterMove();
  9703. }
  9704. else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
  9705. {
  9706. // Close open popup/menu
  9707. ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
  9708. }
  9709. else
  9710. {
  9711. // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
  9712. if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
  9713. g.NavWindow->NavLastIds[0] = 0;
  9714. g.NavId = g.NavFocusScopeId = 0;
  9715. }
  9716. }
  9717. // Handle PageUp/PageDown/Home/End keys
  9718. // Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
  9719. // FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
  9720. // FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
  9721. static float ImGui::NavUpdatePageUpPageDown()
  9722. {
  9723. ImGuiContext& g = *GImGui;
  9724. ImGuiWindow* window = g.NavWindow;
  9725. if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
  9726. return 0.0f;
  9727. const bool page_up_held = IsKeyDown(ImGuiKey_PageUp) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
  9728. const bool page_down_held = IsKeyDown(ImGuiKey_PageDown) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
  9729. const bool home_pressed = IsKeyPressed(ImGuiKey_Home) && !IsActiveIdUsingKey(ImGuiKey_Home);
  9730. const bool end_pressed = IsKeyPressed(ImGuiKey_End) && !IsActiveIdUsingKey(ImGuiKey_End);
  9731. if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
  9732. return 0.0f;
  9733. if (g.NavLayer != ImGuiNavLayer_Main)
  9734. NavRestoreLayer(ImGuiNavLayer_Main);
  9735. if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
  9736. {
  9737. // Fallback manual-scroll when window has no navigable item
  9738. if (IsKeyPressed(ImGuiKey_PageUp, true))
  9739. SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
  9740. else if (IsKeyPressed(ImGuiKey_PageDown, true))
  9741. SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
  9742. else if (home_pressed)
  9743. SetScrollY(window, 0.0f);
  9744. else if (end_pressed)
  9745. SetScrollY(window, window->ScrollMax.y);
  9746. }
  9747. else
  9748. {
  9749. ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
  9750. const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
  9751. float nav_scoring_rect_offset_y = 0.0f;
  9752. if (IsKeyPressed(ImGuiKey_PageUp, true))
  9753. {
  9754. nav_scoring_rect_offset_y = -page_offset_y;
  9755. g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
  9756. g.NavMoveClipDir = ImGuiDir_Up;
  9757. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  9758. }
  9759. else if (IsKeyPressed(ImGuiKey_PageDown, true))
  9760. {
  9761. nav_scoring_rect_offset_y = +page_offset_y;
  9762. g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
  9763. g.NavMoveClipDir = ImGuiDir_Down;
  9764. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  9765. }
  9766. else if (home_pressed)
  9767. {
  9768. // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
  9769. // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
  9770. // Preserve current horizontal position if we have any.
  9771. nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
  9772. if (nav_rect_rel.IsInverted())
  9773. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  9774. g.NavMoveDir = ImGuiDir_Down;
  9775. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
  9776. // FIXME-NAV: MoveClipDir left to _None, intentional?
  9777. }
  9778. else if (end_pressed)
  9779. {
  9780. nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
  9781. if (nav_rect_rel.IsInverted())
  9782. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  9783. g.NavMoveDir = ImGuiDir_Up;
  9784. g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
  9785. // FIXME-NAV: MoveClipDir left to _None, intentional?
  9786. }
  9787. return nav_scoring_rect_offset_y;
  9788. }
  9789. return 0.0f;
  9790. }
  9791. static void ImGui::NavEndFrame()
  9792. {
  9793. ImGuiContext& g = *GImGui;
  9794. // Show CTRL+TAB list window
  9795. if (g.NavWindowingTarget != NULL)
  9796. NavUpdateWindowingOverlay();
  9797. // Perform wrap-around in menus
  9798. // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
  9799. // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
  9800. const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
  9801. if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
  9802. NavUpdateCreateWrappingRequest();
  9803. }
  9804. static void ImGui::NavUpdateCreateWrappingRequest()
  9805. {
  9806. ImGuiContext& g = *GImGui;
  9807. ImGuiWindow* window = g.NavWindow;
  9808. bool do_forward = false;
  9809. ImRect bb_rel = window->NavRectRel[g.NavLayer];
  9810. ImGuiDir clip_dir = g.NavMoveDir;
  9811. const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
  9812. if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  9813. {
  9814. bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
  9815. if (move_flags & ImGuiNavMoveFlags_WrapX)
  9816. {
  9817. bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
  9818. clip_dir = ImGuiDir_Up;
  9819. }
  9820. do_forward = true;
  9821. }
  9822. if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  9823. {
  9824. bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
  9825. if (move_flags & ImGuiNavMoveFlags_WrapX)
  9826. {
  9827. bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
  9828. clip_dir = ImGuiDir_Down;
  9829. }
  9830. do_forward = true;
  9831. }
  9832. if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  9833. {
  9834. bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
  9835. if (move_flags & ImGuiNavMoveFlags_WrapY)
  9836. {
  9837. bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
  9838. clip_dir = ImGuiDir_Left;
  9839. }
  9840. do_forward = true;
  9841. }
  9842. if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  9843. {
  9844. bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
  9845. if (move_flags & ImGuiNavMoveFlags_WrapY)
  9846. {
  9847. bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
  9848. clip_dir = ImGuiDir_Right;
  9849. }
  9850. do_forward = true;
  9851. }
  9852. if (!do_forward)
  9853. return;
  9854. window->NavRectRel[g.NavLayer] = bb_rel;
  9855. NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
  9856. }
  9857. static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
  9858. {
  9859. ImGuiContext& g = *GImGui;
  9860. IM_UNUSED(g);
  9861. int order = window->FocusOrder;
  9862. IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
  9863. IM_ASSERT(g.WindowsFocusOrder[order] == window);
  9864. return order;
  9865. }
  9866. static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
  9867. {
  9868. ImGuiContext& g = *GImGui;
  9869. for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
  9870. if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
  9871. return g.WindowsFocusOrder[i];
  9872. return NULL;
  9873. }
  9874. static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
  9875. {
  9876. ImGuiContext& g = *GImGui;
  9877. IM_ASSERT(g.NavWindowingTarget);
  9878. if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
  9879. return;
  9880. const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
  9881. ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
  9882. if (!window_target)
  9883. window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
  9884. if (window_target) // Don't reset windowing target if there's a single window in the list
  9885. {
  9886. g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
  9887. g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
  9888. }
  9889. g.NavWindowingToggleLayer = false;
  9890. }
  9891. // Windowing management mode
  9892. // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
  9893. // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
  9894. static void ImGui::NavUpdateWindowing()
  9895. {
  9896. ImGuiContext& g = *GImGui;
  9897. ImGuiIO& io = g.IO;
  9898. ImGuiWindow* apply_focus_window = NULL;
  9899. bool apply_toggle_layer = false;
  9900. ImGuiWindow* modal_window = GetTopMostPopupModal();
  9901. bool allow_windowing = (modal_window == NULL);
  9902. if (!allow_windowing)
  9903. g.NavWindowingTarget = NULL;
  9904. // Fade out
  9905. if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
  9906. {
  9907. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
  9908. if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
  9909. g.NavWindowingTargetAnim = NULL;
  9910. }
  9911. // Start CTRL+Tab or Square+L/R window selection
  9912. const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  9913. const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  9914. const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, false);
  9915. const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && io.KeyCtrl && IsKeyPressed(ImGuiKey_Tab, false); // Note: enabled even without NavEnableKeyboard!
  9916. if (start_windowing_with_gamepad || start_windowing_with_keyboard)
  9917. if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
  9918. {
  9919. g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
  9920. g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
  9921. g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
  9922. g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
  9923. g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
  9924. }
  9925. // Gamepad update
  9926. g.NavWindowingTimer += io.DeltaTime;
  9927. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
  9928. {
  9929. // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
  9930. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
  9931. // Select window to focus
  9932. const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
  9933. if (focus_change_dir != 0)
  9934. {
  9935. NavUpdateWindowingHighlightWindow(focus_change_dir);
  9936. g.NavWindowingHighlightAlpha = 1.0f;
  9937. }
  9938. // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
  9939. if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
  9940. {
  9941. g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
  9942. if (g.NavWindowingToggleLayer && g.NavWindow)
  9943. apply_toggle_layer = true;
  9944. else if (!g.NavWindowingToggleLayer)
  9945. apply_focus_window = g.NavWindowingTarget;
  9946. g.NavWindowingTarget = NULL;
  9947. }
  9948. }
  9949. // Keyboard: Focus
  9950. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
  9951. {
  9952. // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
  9953. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
  9954. if (IsKeyPressed(ImGuiKey_Tab, true))
  9955. NavUpdateWindowingHighlightWindow(io.KeyShift ? +1 : -1);
  9956. if (!io.KeyCtrl)
  9957. apply_focus_window = g.NavWindowingTarget;
  9958. }
  9959. // Keyboard: Press and Release ALT to toggle menu layer
  9960. // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
  9961. // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
  9962. if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt))
  9963. {
  9964. g.NavWindowingToggleLayer = true;
  9965. g.NavInputSource = ImGuiInputSource_Keyboard;
  9966. }
  9967. if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
  9968. {
  9969. // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
  9970. // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
  9971. if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
  9972. g.NavWindowingToggleLayer = false;
  9973. // Apply layer toggle on release
  9974. // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
  9975. if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
  9976. if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
  9977. if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
  9978. apply_toggle_layer = true;
  9979. if (!IsKeyDown(ImGuiMod_Alt))
  9980. g.NavWindowingToggleLayer = false;
  9981. }
  9982. // Move window
  9983. if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
  9984. {
  9985. ImVec2 nav_move_dir;
  9986. if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
  9987. nav_move_dir = GetKeyVector2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
  9988. if (g.NavInputSource == ImGuiInputSource_Gamepad)
  9989. nav_move_dir = GetKeyVector2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
  9990. if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
  9991. {
  9992. const float NAV_MOVE_SPEED = 800.0f;
  9993. const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
  9994. g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
  9995. g.NavDisableMouseHover = true;
  9996. ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
  9997. if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
  9998. {
  9999. ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
  10000. SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
  10001. g.NavWindowingAccumDeltaPos -= accum_floored;
  10002. }
  10003. }
  10004. }
  10005. // Apply final focus
  10006. if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
  10007. {
  10008. ClearActiveID();
  10009. NavRestoreHighlightAfterMove();
  10010. apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
  10011. ClosePopupsOverWindow(apply_focus_window, false);
  10012. FocusWindow(apply_focus_window);
  10013. if (apply_focus_window->NavLastIds[0] == 0)
  10014. NavInitWindow(apply_focus_window, false);
  10015. // If the window has ONLY a menu layer (no main layer), select it directly
  10016. // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
  10017. // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
  10018. // the target window as already been previewed once.
  10019. // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
  10020. // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
  10021. // won't be valid.
  10022. if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
  10023. g.NavLayer = ImGuiNavLayer_Menu;
  10024. }
  10025. if (apply_focus_window)
  10026. g.NavWindowingTarget = NULL;
  10027. // Apply menu/layer toggle
  10028. if (apply_toggle_layer && g.NavWindow)
  10029. {
  10030. ClearActiveID();
  10031. // Move to parent menu if necessary
  10032. ImGuiWindow* new_nav_window = g.NavWindow;
  10033. while (new_nav_window->ParentWindow
  10034. && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
  10035. && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
  10036. && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  10037. new_nav_window = new_nav_window->ParentWindow;
  10038. if (new_nav_window != g.NavWindow)
  10039. {
  10040. ImGuiWindow* old_nav_window = g.NavWindow;
  10041. FocusWindow(new_nav_window);
  10042. new_nav_window->NavLastChildNavWindow = old_nav_window;
  10043. }
  10044. // Toggle layer
  10045. const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
  10046. if (new_nav_layer != g.NavLayer)
  10047. {
  10048. // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
  10049. if (new_nav_layer == ImGuiNavLayer_Menu)
  10050. g.NavWindow->NavLastIds[new_nav_layer] = 0;
  10051. NavRestoreLayer(new_nav_layer);
  10052. NavRestoreHighlightAfterMove();
  10053. }
  10054. }
  10055. }
  10056. // Window has already passed the IsWindowNavFocusable()
  10057. static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
  10058. {
  10059. if (window->Flags & ImGuiWindowFlags_Popup)
  10060. return "(Popup)";
  10061. if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
  10062. return "(Main menu bar)";
  10063. return "(Untitled)";
  10064. }
  10065. // Overlay displayed when using CTRL+TAB. Called by EndFrame().
  10066. void ImGui::NavUpdateWindowingOverlay()
  10067. {
  10068. ImGuiContext& g = *GImGui;
  10069. IM_ASSERT(g.NavWindowingTarget != NULL);
  10070. if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
  10071. return;
  10072. if (g.NavWindowingListWindow == NULL)
  10073. g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
  10074. const ImGuiViewport* viewport = GetMainViewport();
  10075. SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
  10076. SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
  10077. PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
  10078. Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
  10079. for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
  10080. {
  10081. ImGuiWindow* window = g.WindowsFocusOrder[n];
  10082. IM_ASSERT(window != NULL); // Fix static analyzers
  10083. if (!IsWindowNavFocusable(window))
  10084. continue;
  10085. const char* label = window->Name;
  10086. if (label == FindRenderedTextEnd(label))
  10087. label = GetFallbackWindowNameForWindowingList(window);
  10088. Selectable(label, g.NavWindowingTarget == window);
  10089. }
  10090. End();
  10091. PopStyleVar();
  10092. }
  10093. //-----------------------------------------------------------------------------
  10094. // [SECTION] DRAG AND DROP
  10095. //-----------------------------------------------------------------------------
  10096. bool ImGui::IsDragDropActive()
  10097. {
  10098. ImGuiContext& g = *GImGui;
  10099. return g.DragDropActive;
  10100. }
  10101. void ImGui::ClearDragDrop()
  10102. {
  10103. ImGuiContext& g = *GImGui;
  10104. g.DragDropActive = false;
  10105. g.DragDropPayload.Clear();
  10106. g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
  10107. g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
  10108. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  10109. g.DragDropAcceptFrameCount = -1;
  10110. g.DragDropPayloadBufHeap.clear();
  10111. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  10112. }
  10113. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
  10114. // If the item has an identifier:
  10115. // - This assume/require the item to be activated (typically via ButtonBehavior).
  10116. // - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
  10117. // - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
  10118. // If the item has no identifier:
  10119. // - Currently always assume left mouse button.
  10120. bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
  10121. {
  10122. ImGuiContext& g = *GImGui;
  10123. ImGuiWindow* window = g.CurrentWindow;
  10124. // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
  10125. // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
  10126. ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
  10127. bool source_drag_active = false;
  10128. ImGuiID source_id = 0;
  10129. ImGuiID source_parent_id = 0;
  10130. if (!(flags & ImGuiDragDropFlags_SourceExtern))
  10131. {
  10132. source_id = g.LastItemData.ID;
  10133. if (source_id != 0)
  10134. {
  10135. // Common path: items with ID
  10136. if (g.ActiveId != source_id)
  10137. return false;
  10138. if (g.ActiveIdMouseButton != -1)
  10139. mouse_button = g.ActiveIdMouseButton;
  10140. if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
  10141. return false;
  10142. g.ActiveIdAllowOverlap = false;
  10143. }
  10144. else
  10145. {
  10146. // Uncommon path: items without ID
  10147. if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
  10148. return false;
  10149. if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
  10150. return false;
  10151. // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
  10152. // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
  10153. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
  10154. {
  10155. IM_ASSERT(0);
  10156. return false;
  10157. }
  10158. // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
  10159. // We build a throwaway ID based on current ID stack + relative AABB of items in window.
  10160. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
  10161. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
  10162. // Rely on keeping other window->LastItemXXX fields intact.
  10163. source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
  10164. KeepAliveID(source_id);
  10165. bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
  10166. if (is_hovered && g.IO.MouseClicked[mouse_button])
  10167. {
  10168. SetActiveID(source_id, window);
  10169. FocusWindow(window);
  10170. }
  10171. if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
  10172. g.ActiveIdAllowOverlap = is_hovered;
  10173. }
  10174. if (g.ActiveId != source_id)
  10175. return false;
  10176. source_parent_id = window->IDStack.back();
  10177. source_drag_active = IsMouseDragging(mouse_button);
  10178. // Disable navigation and key inputs while dragging + cancel existing request if any
  10179. SetActiveIdUsingAllKeyboardKeys();
  10180. }
  10181. else
  10182. {
  10183. window = NULL;
  10184. source_id = ImHashStr("#SourceExtern");
  10185. source_drag_active = true;
  10186. }
  10187. if (source_drag_active)
  10188. {
  10189. if (!g.DragDropActive)
  10190. {
  10191. IM_ASSERT(source_id != 0);
  10192. ClearDragDrop();
  10193. ImGuiPayload& payload = g.DragDropPayload;
  10194. payload.SourceId = source_id;
  10195. payload.SourceParentId = source_parent_id;
  10196. g.DragDropActive = true;
  10197. g.DragDropSourceFlags = flags;
  10198. g.DragDropMouseButton = mouse_button;
  10199. if (payload.SourceId == g.ActiveId)
  10200. g.ActiveIdNoClearOnFocusLoss = true;
  10201. }
  10202. g.DragDropSourceFrameCount = g.FrameCount;
  10203. g.DragDropWithinSource = true;
  10204. if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  10205. {
  10206. // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
  10207. // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
  10208. BeginTooltip();
  10209. if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
  10210. {
  10211. ImGuiWindow* tooltip_window = g.CurrentWindow;
  10212. tooltip_window->Hidden = tooltip_window->SkipItems = true;
  10213. tooltip_window->HiddenFramesCanSkipItems = 1;
  10214. }
  10215. }
  10216. if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
  10217. g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
  10218. return true;
  10219. }
  10220. return false;
  10221. }
  10222. void ImGui::EndDragDropSource()
  10223. {
  10224. ImGuiContext& g = *GImGui;
  10225. IM_ASSERT(g.DragDropActive);
  10226. IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
  10227. if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  10228. EndTooltip();
  10229. // Discard the drag if have not called SetDragDropPayload()
  10230. if (g.DragDropPayload.DataFrameCount == -1)
  10231. ClearDragDrop();
  10232. g.DragDropWithinSource = false;
  10233. }
  10234. // Use 'cond' to choose to submit payload on drag start or every frame
  10235. bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
  10236. {
  10237. ImGuiContext& g = *GImGui;
  10238. ImGuiPayload& payload = g.DragDropPayload;
  10239. if (cond == 0)
  10240. cond = ImGuiCond_Always;
  10241. IM_ASSERT(type != NULL);
  10242. IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
  10243. IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
  10244. IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
  10245. IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
  10246. if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
  10247. {
  10248. // Copy payload
  10249. ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
  10250. g.DragDropPayloadBufHeap.resize(0);
  10251. if (data_size > sizeof(g.DragDropPayloadBufLocal))
  10252. {
  10253. // Store in heap
  10254. g.DragDropPayloadBufHeap.resize((int)data_size);
  10255. payload.Data = g.DragDropPayloadBufHeap.Data;
  10256. memcpy(payload.Data, data, data_size);
  10257. }
  10258. else if (data_size > 0)
  10259. {
  10260. // Store locally
  10261. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  10262. payload.Data = g.DragDropPayloadBufLocal;
  10263. memcpy(payload.Data, data, data_size);
  10264. }
  10265. else
  10266. {
  10267. payload.Data = NULL;
  10268. }
  10269. payload.DataSize = (int)data_size;
  10270. }
  10271. payload.DataFrameCount = g.FrameCount;
  10272. // Return whether the payload has been accepted
  10273. return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
  10274. }
  10275. bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
  10276. {
  10277. ImGuiContext& g = *GImGui;
  10278. if (!g.DragDropActive)
  10279. return false;
  10280. ImGuiWindow* window = g.CurrentWindow;
  10281. ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
  10282. if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
  10283. return false;
  10284. IM_ASSERT(id != 0);
  10285. if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
  10286. return false;
  10287. if (window->SkipItems)
  10288. return false;
  10289. IM_ASSERT(g.DragDropWithinTarget == false);
  10290. g.DragDropTargetRect = bb;
  10291. g.DragDropTargetId = id;
  10292. g.DragDropWithinTarget = true;
  10293. return true;
  10294. }
  10295. // We don't use BeginDragDropTargetCustom() and duplicate its code because:
  10296. // 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
  10297. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
  10298. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
  10299. bool ImGui::BeginDragDropTarget()
  10300. {
  10301. ImGuiContext& g = *GImGui;
  10302. if (!g.DragDropActive)
  10303. return false;
  10304. ImGuiWindow* window = g.CurrentWindow;
  10305. if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
  10306. return false;
  10307. ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
  10308. if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems)
  10309. return false;
  10310. const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
  10311. ImGuiID id = g.LastItemData.ID;
  10312. if (id == 0)
  10313. {
  10314. id = window->GetIDFromRectangle(display_rect);
  10315. KeepAliveID(id);
  10316. }
  10317. if (g.DragDropPayload.SourceId == id)
  10318. return false;
  10319. IM_ASSERT(g.DragDropWithinTarget == false);
  10320. g.DragDropTargetRect = display_rect;
  10321. g.DragDropTargetId = id;
  10322. g.DragDropWithinTarget = true;
  10323. return true;
  10324. }
  10325. bool ImGui::IsDragDropPayloadBeingAccepted()
  10326. {
  10327. ImGuiContext& g = *GImGui;
  10328. return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
  10329. }
  10330. const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
  10331. {
  10332. ImGuiContext& g = *GImGui;
  10333. ImGuiWindow* window = g.CurrentWindow;
  10334. ImGuiPayload& payload = g.DragDropPayload;
  10335. IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
  10336. IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
  10337. if (type != NULL && !payload.IsDataType(type))
  10338. return NULL;
  10339. // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
  10340. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
  10341. const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
  10342. ImRect r = g.DragDropTargetRect;
  10343. float r_surface = r.GetWidth() * r.GetHeight();
  10344. if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
  10345. {
  10346. g.DragDropAcceptFlags = flags;
  10347. g.DragDropAcceptIdCurr = g.DragDropTargetId;
  10348. g.DragDropAcceptIdCurrRectSurface = r_surface;
  10349. }
  10350. // Render default drop visuals
  10351. // FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
  10352. payload.Preview = was_accepted_previously;
  10353. flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
  10354. if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
  10355. window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
  10356. g.DragDropAcceptFrameCount = g.FrameCount;
  10357. 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()
  10358. if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
  10359. return NULL;
  10360. return &payload;
  10361. }
  10362. const ImGuiPayload* ImGui::GetDragDropPayload()
  10363. {
  10364. ImGuiContext& g = *GImGui;
  10365. return g.DragDropActive ? &g.DragDropPayload : NULL;
  10366. }
  10367. // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
  10368. void ImGui::EndDragDropTarget()
  10369. {
  10370. ImGuiContext& g = *GImGui;
  10371. IM_ASSERT(g.DragDropActive);
  10372. IM_ASSERT(g.DragDropWithinTarget);
  10373. g.DragDropWithinTarget = false;
  10374. }
  10375. //-----------------------------------------------------------------------------
  10376. // [SECTION] LOGGING/CAPTURING
  10377. //-----------------------------------------------------------------------------
  10378. // All text output from the interface can be captured into tty/file/clipboard.
  10379. // By default, tree nodes are automatically opened during logging.
  10380. //-----------------------------------------------------------------------------
  10381. // Pass text data straight to log (without being displayed)
  10382. static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
  10383. {
  10384. if (g.LogFile)
  10385. {
  10386. g.LogBuffer.Buf.resize(0);
  10387. g.LogBuffer.appendfv(fmt, args);
  10388. ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
  10389. }
  10390. else
  10391. {
  10392. g.LogBuffer.appendfv(fmt, args);
  10393. }
  10394. }
  10395. void ImGui::LogText(const char* fmt, ...)
  10396. {
  10397. ImGuiContext& g = *GImGui;
  10398. if (!g.LogEnabled)
  10399. return;
  10400. va_list args;
  10401. va_start(args, fmt);
  10402. LogTextV(g, fmt, args);
  10403. va_end(args);
  10404. }
  10405. void ImGui::LogTextV(const char* fmt, va_list args)
  10406. {
  10407. ImGuiContext& g = *GImGui;
  10408. if (!g.LogEnabled)
  10409. return;
  10410. LogTextV(g, fmt, args);
  10411. }
  10412. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  10413. // We split text into individual lines to add current tree level padding
  10414. // FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
  10415. void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
  10416. {
  10417. ImGuiContext& g = *GImGui;
  10418. ImGuiWindow* window = g.CurrentWindow;
  10419. const char* prefix = g.LogNextPrefix;
  10420. const char* suffix = g.LogNextSuffix;
  10421. g.LogNextPrefix = g.LogNextSuffix = NULL;
  10422. if (!text_end)
  10423. text_end = FindRenderedTextEnd(text, text_end);
  10424. const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
  10425. if (ref_pos)
  10426. g.LogLinePosY = ref_pos->y;
  10427. if (log_new_line)
  10428. {
  10429. LogText(IM_NEWLINE);
  10430. g.LogLineFirstItem = true;
  10431. }
  10432. if (prefix)
  10433. LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
  10434. // Re-adjust padding if we have popped out of our starting depth
  10435. if (g.LogDepthRef > window->DC.TreeDepth)
  10436. g.LogDepthRef = window->DC.TreeDepth;
  10437. const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
  10438. const char* text_remaining = text;
  10439. for (;;)
  10440. {
  10441. // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
  10442. // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
  10443. const char* line_start = text_remaining;
  10444. const char* line_end = ImStreolRange(line_start, text_end);
  10445. const bool is_last_line = (line_end == text_end);
  10446. if (line_start != line_end || !is_last_line)
  10447. {
  10448. const int line_length = (int)(line_end - line_start);
  10449. const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
  10450. LogText("%*s%.*s", indentation, "", line_length, line_start);
  10451. g.LogLineFirstItem = false;
  10452. if (*line_end == '\n')
  10453. {
  10454. LogText(IM_NEWLINE);
  10455. g.LogLineFirstItem = true;
  10456. }
  10457. }
  10458. if (is_last_line)
  10459. break;
  10460. text_remaining = line_end + 1;
  10461. }
  10462. if (suffix)
  10463. LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
  10464. }
  10465. // Start logging/capturing text output
  10466. void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
  10467. {
  10468. ImGuiContext& g = *GImGui;
  10469. ImGuiWindow* window = g.CurrentWindow;
  10470. IM_ASSERT(g.LogEnabled == false);
  10471. IM_ASSERT(g.LogFile == NULL);
  10472. IM_ASSERT(g.LogBuffer.empty());
  10473. g.LogEnabled = true;
  10474. g.LogType = type;
  10475. g.LogNextPrefix = g.LogNextSuffix = NULL;
  10476. g.LogDepthRef = window->DC.TreeDepth;
  10477. g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
  10478. g.LogLinePosY = FLT_MAX;
  10479. g.LogLineFirstItem = true;
  10480. }
  10481. // Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
  10482. void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
  10483. {
  10484. ImGuiContext& g = *GImGui;
  10485. g.LogNextPrefix = prefix;
  10486. g.LogNextSuffix = suffix;
  10487. }
  10488. void ImGui::LogToTTY(int auto_open_depth)
  10489. {
  10490. ImGuiContext& g = *GImGui;
  10491. if (g.LogEnabled)
  10492. return;
  10493. IM_UNUSED(auto_open_depth);
  10494. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  10495. LogBegin(ImGuiLogType_TTY, auto_open_depth);
  10496. g.LogFile = stdout;
  10497. #endif
  10498. }
  10499. // Start logging/capturing text output to given file
  10500. void ImGui::LogToFile(int auto_open_depth, const char* filename)
  10501. {
  10502. ImGuiContext& g = *GImGui;
  10503. if (g.LogEnabled)
  10504. return;
  10505. // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
  10506. // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
  10507. // By opening the file in binary mode "ab" we have consistent output everywhere.
  10508. if (!filename)
  10509. filename = g.IO.LogFilename;
  10510. if (!filename || !filename[0])
  10511. return;
  10512. ImFileHandle f = ImFileOpen(filename, "ab");
  10513. if (!f)
  10514. {
  10515. IM_ASSERT(0);
  10516. return;
  10517. }
  10518. LogBegin(ImGuiLogType_File, auto_open_depth);
  10519. g.LogFile = f;
  10520. }
  10521. // Start logging/capturing text output to clipboard
  10522. void ImGui::LogToClipboard(int auto_open_depth)
  10523. {
  10524. ImGuiContext& g = *GImGui;
  10525. if (g.LogEnabled)
  10526. return;
  10527. LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
  10528. }
  10529. void ImGui::LogToBuffer(int auto_open_depth)
  10530. {
  10531. ImGuiContext& g = *GImGui;
  10532. if (g.LogEnabled)
  10533. return;
  10534. LogBegin(ImGuiLogType_Buffer, auto_open_depth);
  10535. }
  10536. void ImGui::LogFinish()
  10537. {
  10538. ImGuiContext& g = *GImGui;
  10539. if (!g.LogEnabled)
  10540. return;
  10541. LogText(IM_NEWLINE);
  10542. switch (g.LogType)
  10543. {
  10544. case ImGuiLogType_TTY:
  10545. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  10546. fflush(g.LogFile);
  10547. #endif
  10548. break;
  10549. case ImGuiLogType_File:
  10550. ImFileClose(g.LogFile);
  10551. break;
  10552. case ImGuiLogType_Buffer:
  10553. break;
  10554. case ImGuiLogType_Clipboard:
  10555. if (!g.LogBuffer.empty())
  10556. SetClipboardText(g.LogBuffer.begin());
  10557. break;
  10558. case ImGuiLogType_None:
  10559. IM_ASSERT(0);
  10560. break;
  10561. }
  10562. g.LogEnabled = false;
  10563. g.LogType = ImGuiLogType_None;
  10564. g.LogFile = NULL;
  10565. g.LogBuffer.clear();
  10566. }
  10567. // Helper to display logging buttons
  10568. // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
  10569. void ImGui::LogButtons()
  10570. {
  10571. ImGuiContext& g = *GImGui;
  10572. PushID("LogButtons");
  10573. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  10574. const bool log_to_tty = Button("Log To TTY"); SameLine();
  10575. #else
  10576. const bool log_to_tty = false;
  10577. #endif
  10578. const bool log_to_file = Button("Log To File"); SameLine();
  10579. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  10580. PushAllowKeyboardFocus(false);
  10581. SetNextItemWidth(80.0f);
  10582. SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
  10583. PopAllowKeyboardFocus();
  10584. PopID();
  10585. // Start logging at the end of the function so that the buttons don't appear in the log
  10586. if (log_to_tty)
  10587. LogToTTY();
  10588. if (log_to_file)
  10589. LogToFile();
  10590. if (log_to_clipboard)
  10591. LogToClipboard();
  10592. }
  10593. //-----------------------------------------------------------------------------
  10594. // [SECTION] SETTINGS
  10595. //-----------------------------------------------------------------------------
  10596. // - UpdateSettings() [Internal]
  10597. // - MarkIniSettingsDirty() [Internal]
  10598. // - CreateNewWindowSettings() [Internal]
  10599. // - FindWindowSettings() [Internal]
  10600. // - FindOrCreateWindowSettings() [Internal]
  10601. // - FindSettingsHandler() [Internal]
  10602. // - ClearIniSettings() [Internal]
  10603. // - LoadIniSettingsFromDisk()
  10604. // - LoadIniSettingsFromMemory()
  10605. // - SaveIniSettingsToDisk()
  10606. // - SaveIniSettingsToMemory()
  10607. // - WindowSettingsHandler_***() [Internal]
  10608. //-----------------------------------------------------------------------------
  10609. // Called by NewFrame()
  10610. void ImGui::UpdateSettings()
  10611. {
  10612. // Load settings on first frame (if not explicitly loaded manually before)
  10613. ImGuiContext& g = *GImGui;
  10614. if (!g.SettingsLoaded)
  10615. {
  10616. IM_ASSERT(g.SettingsWindows.empty());
  10617. if (g.IO.IniFilename)
  10618. LoadIniSettingsFromDisk(g.IO.IniFilename);
  10619. g.SettingsLoaded = true;
  10620. }
  10621. // Save settings (with a delay after the last modification, so we don't spam disk too much)
  10622. if (g.SettingsDirtyTimer > 0.0f)
  10623. {
  10624. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  10625. if (g.SettingsDirtyTimer <= 0.0f)
  10626. {
  10627. if (g.IO.IniFilename != NULL)
  10628. SaveIniSettingsToDisk(g.IO.IniFilename);
  10629. else
  10630. g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
  10631. g.SettingsDirtyTimer = 0.0f;
  10632. }
  10633. }
  10634. }
  10635. void ImGui::MarkIniSettingsDirty()
  10636. {
  10637. ImGuiContext& g = *GImGui;
  10638. if (g.SettingsDirtyTimer <= 0.0f)
  10639. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  10640. }
  10641. void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
  10642. {
  10643. ImGuiContext& g = *GImGui;
  10644. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  10645. if (g.SettingsDirtyTimer <= 0.0f)
  10646. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  10647. }
  10648. ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
  10649. {
  10650. ImGuiContext& g = *GImGui;
  10651. #if !IMGUI_DEBUG_INI_SETTINGS
  10652. // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  10653. // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
  10654. if (const char* p = strstr(name, "###"))
  10655. name = p;
  10656. #endif
  10657. const size_t name_len = strlen(name);
  10658. // Allocate chunk
  10659. const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
  10660. ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
  10661. IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
  10662. settings->ID = ImHashStr(name, name_len);
  10663. memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
  10664. return settings;
  10665. }
  10666. ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
  10667. {
  10668. ImGuiContext& g = *GImGui;
  10669. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10670. if (settings->ID == id)
  10671. return settings;
  10672. return NULL;
  10673. }
  10674. ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
  10675. {
  10676. if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
  10677. return settings;
  10678. return CreateNewWindowSettings(name);
  10679. }
  10680. void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
  10681. {
  10682. ImGuiContext& g = *GImGui;
  10683. IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
  10684. g.SettingsHandlers.push_back(*handler);
  10685. }
  10686. void ImGui::RemoveSettingsHandler(const char* type_name)
  10687. {
  10688. ImGuiContext& g = *GImGui;
  10689. if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
  10690. g.SettingsHandlers.erase(handler);
  10691. }
  10692. ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
  10693. {
  10694. ImGuiContext& g = *GImGui;
  10695. const ImGuiID type_hash = ImHashStr(type_name);
  10696. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10697. if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
  10698. return &g.SettingsHandlers[handler_n];
  10699. return NULL;
  10700. }
  10701. void ImGui::ClearIniSettings()
  10702. {
  10703. ImGuiContext& g = *GImGui;
  10704. g.SettingsIniData.clear();
  10705. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10706. if (g.SettingsHandlers[handler_n].ClearAllFn)
  10707. g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
  10708. }
  10709. void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
  10710. {
  10711. size_t file_data_size = 0;
  10712. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
  10713. if (!file_data)
  10714. return;
  10715. if (file_data_size > 0)
  10716. LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
  10717. IM_FREE(file_data);
  10718. }
  10719. // Zero-tolerance, no error reporting, cheap .ini parsing
  10720. void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
  10721. {
  10722. ImGuiContext& g = *GImGui;
  10723. IM_ASSERT(g.Initialized);
  10724. //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
  10725. //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
  10726. // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
  10727. // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
  10728. if (ini_size == 0)
  10729. ini_size = strlen(ini_data);
  10730. g.SettingsIniData.Buf.resize((int)ini_size + 1);
  10731. char* const buf = g.SettingsIniData.Buf.Data;
  10732. char* const buf_end = buf + ini_size;
  10733. memcpy(buf, ini_data, ini_size);
  10734. buf_end[0] = 0;
  10735. // Call pre-read handlers
  10736. // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
  10737. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10738. if (g.SettingsHandlers[handler_n].ReadInitFn)
  10739. g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
  10740. void* entry_data = NULL;
  10741. ImGuiSettingsHandler* entry_handler = NULL;
  10742. char* line_end = NULL;
  10743. for (char* line = buf; line < buf_end; line = line_end + 1)
  10744. {
  10745. // Skip new lines markers, then find end of the line
  10746. while (*line == '\n' || *line == '\r')
  10747. line++;
  10748. line_end = line;
  10749. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  10750. line_end++;
  10751. line_end[0] = 0;
  10752. if (line[0] == ';')
  10753. continue;
  10754. if (line[0] == '[' && line_end > line && line_end[-1] == ']')
  10755. {
  10756. // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
  10757. line_end[-1] = 0;
  10758. const char* name_end = line_end - 1;
  10759. const char* type_start = line + 1;
  10760. char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
  10761. const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
  10762. if (!type_end || !name_start)
  10763. continue;
  10764. *type_end = 0; // Overwrite first ']'
  10765. name_start++; // Skip second '['
  10766. entry_handler = FindSettingsHandler(type_start);
  10767. entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
  10768. }
  10769. else if (entry_handler != NULL && entry_data != NULL)
  10770. {
  10771. // Let type handler parse the line
  10772. entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
  10773. }
  10774. }
  10775. g.SettingsLoaded = true;
  10776. // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
  10777. memcpy(buf, ini_data, ini_size);
  10778. // Call post-read handlers
  10779. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10780. if (g.SettingsHandlers[handler_n].ApplyAllFn)
  10781. g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
  10782. }
  10783. void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
  10784. {
  10785. ImGuiContext& g = *GImGui;
  10786. g.SettingsDirtyTimer = 0.0f;
  10787. if (!ini_filename)
  10788. return;
  10789. size_t ini_data_size = 0;
  10790. const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
  10791. ImFileHandle f = ImFileOpen(ini_filename, "wt");
  10792. if (!f)
  10793. return;
  10794. ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
  10795. ImFileClose(f);
  10796. }
  10797. // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
  10798. const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
  10799. {
  10800. ImGuiContext& g = *GImGui;
  10801. g.SettingsDirtyTimer = 0.0f;
  10802. g.SettingsIniData.Buf.resize(0);
  10803. g.SettingsIniData.Buf.push_back(0);
  10804. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  10805. {
  10806. ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
  10807. handler->WriteAllFn(&g, handler, &g.SettingsIniData);
  10808. }
  10809. if (out_size)
  10810. *out_size = (size_t)g.SettingsIniData.size();
  10811. return g.SettingsIniData.c_str();
  10812. }
  10813. static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  10814. {
  10815. ImGuiContext& g = *ctx;
  10816. for (int i = 0; i != g.Windows.Size; i++)
  10817. g.Windows[i]->SettingsOffset = -1;
  10818. g.SettingsWindows.clear();
  10819. }
  10820. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  10821. {
  10822. ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
  10823. ImGuiID id = settings->ID;
  10824. *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
  10825. settings->ID = id;
  10826. settings->WantApply = true;
  10827. return (void*)settings;
  10828. }
  10829. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  10830. {
  10831. ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
  10832. int x, y;
  10833. int i;
  10834. if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
  10835. else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
  10836. else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
  10837. }
  10838. // Apply to existing windows (if any)
  10839. static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  10840. {
  10841. ImGuiContext& g = *ctx;
  10842. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10843. if (settings->WantApply)
  10844. {
  10845. if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
  10846. ApplyWindowSettings(window, settings);
  10847. settings->WantApply = false;
  10848. }
  10849. }
  10850. static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  10851. {
  10852. // Gather data from windows that were active during this session
  10853. // (if a window wasn't opened in this session we preserve its settings)
  10854. ImGuiContext& g = *ctx;
  10855. for (int i = 0; i != g.Windows.Size; i++)
  10856. {
  10857. ImGuiWindow* window = g.Windows[i];
  10858. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  10859. continue;
  10860. ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
  10861. if (!settings)
  10862. {
  10863. settings = ImGui::CreateNewWindowSettings(window->Name);
  10864. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  10865. }
  10866. IM_ASSERT(settings->ID == window->ID);
  10867. settings->Pos = ImVec2ih(window->Pos);
  10868. settings->Size = ImVec2ih(window->SizeFull);
  10869. settings->Collapsed = window->Collapsed;
  10870. }
  10871. // Write to text buffer
  10872. buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
  10873. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10874. {
  10875. const char* settings_name = settings->GetName();
  10876. buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
  10877. buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
  10878. buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
  10879. buf->appendf("Collapsed=%d\n", settings->Collapsed);
  10880. buf->append("\n");
  10881. }
  10882. }
  10883. //-----------------------------------------------------------------------------
  10884. // [SECTION] VIEWPORTS, PLATFORM WINDOWS
  10885. //-----------------------------------------------------------------------------
  10886. // - GetMainViewport()
  10887. // - SetWindowViewport() [Internal]
  10888. // - UpdateViewportsNewFrame() [Internal]
  10889. // (this section is more complete in the 'docking' branch)
  10890. //-----------------------------------------------------------------------------
  10891. ImGuiViewport* ImGui::GetMainViewport()
  10892. {
  10893. ImGuiContext& g = *GImGui;
  10894. return g.Viewports[0];
  10895. }
  10896. void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
  10897. {
  10898. window->Viewport = viewport;
  10899. }
  10900. // Update viewports and monitor infos
  10901. static void ImGui::UpdateViewportsNewFrame()
  10902. {
  10903. ImGuiContext& g = *GImGui;
  10904. IM_ASSERT(g.Viewports.Size == 1);
  10905. // Update main viewport with current platform position.
  10906. // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
  10907. ImGuiViewportP* main_viewport = g.Viewports[0];
  10908. main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;
  10909. main_viewport->Pos = ImVec2(0.0f, 0.0f);
  10910. main_viewport->Size = g.IO.DisplaySize;
  10911. for (int n = 0; n < g.Viewports.Size; n++)
  10912. {
  10913. ImGuiViewportP* viewport = g.Viewports[n];
  10914. // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again.
  10915. viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
  10916. viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
  10917. viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
  10918. viewport->UpdateWorkRect();
  10919. }
  10920. }
  10921. //-----------------------------------------------------------------------------
  10922. // [SECTION] DOCKING
  10923. //-----------------------------------------------------------------------------
  10924. // (this section is filled in the 'docking' branch)
  10925. //-----------------------------------------------------------------------------
  10926. // [SECTION] PLATFORM DEPENDENT HELPERS
  10927. //-----------------------------------------------------------------------------
  10928. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
  10929. #ifdef _MSC_VER
  10930. #pragma comment(lib, "user32")
  10931. #pragma comment(lib, "kernel32")
  10932. #endif
  10933. // Win32 clipboard implementation
  10934. // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
  10935. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10936. {
  10937. ImGuiContext& g = *GImGui;
  10938. g.ClipboardHandlerData.clear();
  10939. if (!::OpenClipboard(NULL))
  10940. return NULL;
  10941. HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
  10942. if (wbuf_handle == NULL)
  10943. {
  10944. ::CloseClipboard();
  10945. return NULL;
  10946. }
  10947. if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
  10948. {
  10949. int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
  10950. g.ClipboardHandlerData.resize(buf_len);
  10951. ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
  10952. }
  10953. ::GlobalUnlock(wbuf_handle);
  10954. ::CloseClipboard();
  10955. return g.ClipboardHandlerData.Data;
  10956. }
  10957. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10958. {
  10959. if (!::OpenClipboard(NULL))
  10960. return;
  10961. const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
  10962. HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
  10963. if (wbuf_handle == NULL)
  10964. {
  10965. ::CloseClipboard();
  10966. return;
  10967. }
  10968. WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
  10969. ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
  10970. ::GlobalUnlock(wbuf_handle);
  10971. ::EmptyClipboard();
  10972. if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
  10973. ::GlobalFree(wbuf_handle);
  10974. ::CloseClipboard();
  10975. }
  10976. #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
  10977. #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
  10978. static PasteboardRef main_clipboard = 0;
  10979. // OSX clipboard implementation
  10980. // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
  10981. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10982. {
  10983. if (!main_clipboard)
  10984. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  10985. PasteboardClear(main_clipboard);
  10986. CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
  10987. if (cf_data)
  10988. {
  10989. PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
  10990. CFRelease(cf_data);
  10991. }
  10992. }
  10993. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10994. {
  10995. if (!main_clipboard)
  10996. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  10997. PasteboardSynchronize(main_clipboard);
  10998. ItemCount item_count = 0;
  10999. PasteboardGetItemCount(main_clipboard, &item_count);
  11000. for (ItemCount i = 0; i < item_count; i++)
  11001. {
  11002. PasteboardItemID item_id = 0;
  11003. PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
  11004. CFArrayRef flavor_type_array = 0;
  11005. PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
  11006. for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
  11007. {
  11008. CFDataRef cf_data;
  11009. if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
  11010. {
  11011. ImGuiContext& g = *GImGui;
  11012. g.ClipboardHandlerData.clear();
  11013. int length = (int)CFDataGetLength(cf_data);
  11014. g.ClipboardHandlerData.resize(length + 1);
  11015. CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
  11016. g.ClipboardHandlerData[length] = 0;
  11017. CFRelease(cf_data);
  11018. return g.ClipboardHandlerData.Data;
  11019. }
  11020. }
  11021. }
  11022. return NULL;
  11023. }
  11024. #else
  11025. // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
  11026. static const char* GetClipboardTextFn_DefaultImpl(void*)
  11027. {
  11028. ImGuiContext& g = *GImGui;
  11029. return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
  11030. }
  11031. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  11032. {
  11033. ImGuiContext& g = *GImGui;
  11034. g.ClipboardHandlerData.clear();
  11035. const char* text_end = text + strlen(text);
  11036. g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
  11037. memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
  11038. g.ClipboardHandlerData[(int)(text_end - text)] = 0;
  11039. }
  11040. #endif
  11041. // Win32 API IME support (for Asian languages, etc.)
  11042. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  11043. #include <imm.h>
  11044. #ifdef _MSC_VER
  11045. #pragma comment(lib, "imm32")
  11046. #endif
  11047. static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
  11048. {
  11049. // Notify OS Input Method Editor of text input position
  11050. HWND hwnd = (HWND)viewport->PlatformHandleRaw;
  11051. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  11052. if (hwnd == 0)
  11053. hwnd = (HWND)ImGui::GetIO().ImeWindowHandle;
  11054. #endif
  11055. if (hwnd == 0)
  11056. return;
  11057. //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
  11058. if (HIMC himc = ::ImmGetContext(hwnd))
  11059. {
  11060. COMPOSITIONFORM composition_form = {};
  11061. composition_form.ptCurrentPos.x = (LONG)data->InputPos.x;
  11062. composition_form.ptCurrentPos.y = (LONG)data->InputPos.y;
  11063. composition_form.dwStyle = CFS_FORCE_POSITION;
  11064. ::ImmSetCompositionWindow(himc, &composition_form);
  11065. CANDIDATEFORM candidate_form = {};
  11066. candidate_form.dwStyle = CFS_CANDIDATEPOS;
  11067. candidate_form.ptCurrentPos.x = (LONG)data->InputPos.x;
  11068. candidate_form.ptCurrentPos.y = (LONG)data->InputPos.y;
  11069. ::ImmSetCandidateWindow(himc, &candidate_form);
  11070. ::ImmReleaseContext(hwnd, himc);
  11071. }
  11072. }
  11073. #else
  11074. static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
  11075. #endif
  11076. //-----------------------------------------------------------------------------
  11077. // [SECTION] METRICS/DEBUGGER WINDOW
  11078. //-----------------------------------------------------------------------------
  11079. // - RenderViewportThumbnail() [Internal]
  11080. // - RenderViewportsThumbnails() [Internal]
  11081. // - DebugTextEncoding()
  11082. // - MetricsHelpMarker() [Internal]
  11083. // - ShowFontAtlas() [Internal]
  11084. // - ShowMetricsWindow()
  11085. // - DebugNodeColumns() [Internal]
  11086. // - DebugNodeDrawList() [Internal]
  11087. // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
  11088. // - DebugNodeFont() [Internal]
  11089. // - DebugNodeFontGlyph() [Internal]
  11090. // - DebugNodeStorage() [Internal]
  11091. // - DebugNodeTabBar() [Internal]
  11092. // - DebugNodeViewport() [Internal]
  11093. // - DebugNodeWindow() [Internal]
  11094. // - DebugNodeWindowSettings() [Internal]
  11095. // - DebugNodeWindowsList() [Internal]
  11096. // - DebugNodeWindowsListByBeginStackParent() [Internal]
  11097. //-----------------------------------------------------------------------------
  11098. #ifndef IMGUI_DISABLE_DEBUG_TOOLS
  11099. void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
  11100. {
  11101. ImGuiContext& g = *GImGui;
  11102. ImGuiWindow* window = g.CurrentWindow;
  11103. ImVec2 scale = bb.GetSize() / viewport->Size;
  11104. ImVec2 off = bb.Min - viewport->Pos * scale;
  11105. float alpha_mul = 1.0f;
  11106. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
  11107. for (int i = 0; i != g.Windows.Size; i++)
  11108. {
  11109. ImGuiWindow* thumb_window = g.Windows[i];
  11110. if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
  11111. continue;
  11112. ImRect thumb_r = thumb_window->Rect();
  11113. ImRect title_r = thumb_window->TitleBarRect();
  11114. thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale));
  11115. title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off + ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
  11116. thumb_r.ClipWithFull(bb);
  11117. title_r.ClipWithFull(bb);
  11118. const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
  11119. window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
  11120. window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
  11121. window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
  11122. window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
  11123. }
  11124. draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
  11125. }
  11126. static void RenderViewportsThumbnails()
  11127. {
  11128. ImGuiContext& g = *GImGui;
  11129. ImGuiWindow* window = g.CurrentWindow;
  11130. // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
  11131. float SCALE = 1.0f / 8.0f;
  11132. ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  11133. for (int n = 0; n < g.Viewports.Size; n++)
  11134. bb_full.Add(g.Viewports[n]->GetMainRect());
  11135. ImVec2 p = window->DC.CursorPos;
  11136. ImVec2 off = p - bb_full.Min * SCALE;
  11137. for (int n = 0; n < g.Viewports.Size; n++)
  11138. {
  11139. ImGuiViewportP* viewport = g.Viewports[n];
  11140. ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
  11141. ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
  11142. }
  11143. ImGui::Dummy(bb_full.GetSize() * SCALE);
  11144. }
  11145. // Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
  11146. void ImGui::DebugTextEncoding(const char* str)
  11147. {
  11148. Text("Text: \"%s\"", str);
  11149. if (!BeginTable("list", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit))
  11150. return;
  11151. TableSetupColumn("Offset");
  11152. TableSetupColumn("UTF-8");
  11153. TableSetupColumn("Glyph");
  11154. TableSetupColumn("Codepoint");
  11155. TableHeadersRow();
  11156. for (const char* p = str; *p != 0; )
  11157. {
  11158. unsigned int c;
  11159. const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
  11160. TableNextColumn();
  11161. Text("%d", (int)(p - str));
  11162. TableNextColumn();
  11163. for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
  11164. {
  11165. if (byte_index > 0)
  11166. SameLine();
  11167. Text("0x%02X", (int)(unsigned char)p[byte_index]);
  11168. }
  11169. TableNextColumn();
  11170. if (GetFont()->FindGlyphNoFallback((ImWchar)c))
  11171. TextUnformatted(p, p + c_utf8_len);
  11172. else
  11173. TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
  11174. TableNextColumn();
  11175. Text("U+%04X", (int)c);
  11176. p += c_utf8_len;
  11177. }
  11178. EndTable();
  11179. }
  11180. // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
  11181. static void MetricsHelpMarker(const char* desc)
  11182. {
  11183. ImGui::TextDisabled("(?)");
  11184. if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort))
  11185. {
  11186. ImGui::BeginTooltip();
  11187. ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
  11188. ImGui::TextUnformatted(desc);
  11189. ImGui::PopTextWrapPos();
  11190. ImGui::EndTooltip();
  11191. }
  11192. }
  11193. // [DEBUG] List fonts in a font atlas and display its texture
  11194. void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
  11195. {
  11196. for (int i = 0; i < atlas->Fonts.Size; i++)
  11197. {
  11198. ImFont* font = atlas->Fonts[i];
  11199. PushID(font);
  11200. DebugNodeFont(font);
  11201. PopID();
  11202. }
  11203. if (TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
  11204. {
  11205. ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
  11206. ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
  11207. Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
  11208. TreePop();
  11209. }
  11210. }
  11211. void ImGui::ShowMetricsWindow(bool* p_open)
  11212. {
  11213. ImGuiContext& g = *GImGui;
  11214. ImGuiIO& io = g.IO;
  11215. ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
  11216. if (cfg->ShowDebugLog)
  11217. ShowDebugLogWindow(&cfg->ShowDebugLog);
  11218. if (cfg->ShowStackTool)
  11219. ShowStackToolWindow(&cfg->ShowStackTool);
  11220. if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
  11221. {
  11222. End();
  11223. return;
  11224. }
  11225. // Basic info
  11226. Text("Dear ImGui %s", GetVersion());
  11227. Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  11228. Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
  11229. Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
  11230. //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
  11231. Separator();
  11232. // Debugging enums
  11233. enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
  11234. const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
  11235. enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
  11236. const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
  11237. if (cfg->ShowWindowsRectsType < 0)
  11238. cfg->ShowWindowsRectsType = WRT_WorkRect;
  11239. if (cfg->ShowTablesRectsType < 0)
  11240. cfg->ShowTablesRectsType = TRT_WorkRect;
  11241. struct Funcs
  11242. {
  11243. static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
  11244. {
  11245. ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
  11246. if (rect_type == TRT_OuterRect) { return table->OuterRect; }
  11247. else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
  11248. else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
  11249. else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
  11250. else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
  11251. else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
  11252. else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
  11253. else if (rect_type == TRT_ColumnsWorkRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
  11254. else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
  11255. else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
  11256. else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
  11257. else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
  11258. else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
  11259. IM_ASSERT(0);
  11260. return ImRect();
  11261. }
  11262. static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
  11263. {
  11264. if (rect_type == WRT_OuterRect) { return window->Rect(); }
  11265. else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
  11266. else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
  11267. else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
  11268. else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
  11269. else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
  11270. else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
  11271. else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
  11272. IM_ASSERT(0);
  11273. return ImRect();
  11274. }
  11275. };
  11276. // Tools
  11277. if (TreeNode("Tools"))
  11278. {
  11279. bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
  11280. SameLine();
  11281. MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
  11282. if (show_encoding_viewer)
  11283. {
  11284. static char buf[100] = "";
  11285. SetNextItemWidth(-FLT_MIN);
  11286. InputText("##Text", buf, IM_ARRAYSIZE(buf));
  11287. if (buf[0] != 0)
  11288. DebugTextEncoding(buf);
  11289. TreePop();
  11290. }
  11291. // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
  11292. if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
  11293. DebugStartItemPicker();
  11294. SameLine();
  11295. MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
  11296. // Stack Tool is your best friend!
  11297. Checkbox("Show Debug Log", &cfg->ShowDebugLog);
  11298. SameLine();
  11299. MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
  11300. // Stack Tool is your best friend!
  11301. Checkbox("Show Stack Tool", &cfg->ShowStackTool);
  11302. SameLine();
  11303. MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
  11304. Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
  11305. Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
  11306. SameLine();
  11307. SetNextItemWidth(GetFontSize() * 12);
  11308. cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
  11309. if (cfg->ShowWindowsRects && g.NavWindow != NULL)
  11310. {
  11311. BulletText("'%s':", g.NavWindow->Name);
  11312. Indent();
  11313. for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
  11314. {
  11315. ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
  11316. Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
  11317. }
  11318. Unindent();
  11319. }
  11320. Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
  11321. SameLine();
  11322. SetNextItemWidth(GetFontSize() * 12);
  11323. cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
  11324. if (cfg->ShowTablesRects && g.NavWindow != NULL)
  11325. {
  11326. for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
  11327. {
  11328. ImGuiTable* table = g.Tables.TryGetMapData(table_n);
  11329. if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
  11330. continue;
  11331. BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
  11332. if (IsItemHovered())
  11333. GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
  11334. Indent();
  11335. char buf[128];
  11336. for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
  11337. {
  11338. if (rect_n >= TRT_ColumnsRect)
  11339. {
  11340. if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
  11341. continue;
  11342. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  11343. {
  11344. ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
  11345. ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
  11346. Selectable(buf);
  11347. if (IsItemHovered())
  11348. GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
  11349. }
  11350. }
  11351. else
  11352. {
  11353. ImRect r = Funcs::GetTableRect(table, rect_n, -1);
  11354. ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
  11355. Selectable(buf);
  11356. if (IsItemHovered())
  11357. GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
  11358. }
  11359. }
  11360. Unindent();
  11361. }
  11362. }
  11363. TreePop();
  11364. }
  11365. // Windows
  11366. if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
  11367. {
  11368. //SetNextItemOpen(true, ImGuiCond_Once);
  11369. DebugNodeWindowsList(&g.Windows, "By display order");
  11370. DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
  11371. if (TreeNode("By submission order (begin stack)"))
  11372. {
  11373. // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
  11374. ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
  11375. temp_buffer.resize(0);
  11376. for (int i = 0; i < g.Windows.Size; i++)
  11377. if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
  11378. temp_buffer.push_back(g.Windows[i]);
  11379. struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
  11380. ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
  11381. DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
  11382. TreePop();
  11383. }
  11384. TreePop();
  11385. }
  11386. // DrawLists
  11387. int drawlist_count = 0;
  11388. for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
  11389. drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
  11390. if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
  11391. {
  11392. Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
  11393. Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
  11394. for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
  11395. {
  11396. ImGuiViewportP* viewport = g.Viewports[viewport_i];
  11397. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  11398. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  11399. DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  11400. }
  11401. TreePop();
  11402. }
  11403. // Viewports
  11404. if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
  11405. {
  11406. Indent(GetTreeNodeToLabelSpacing());
  11407. RenderViewportsThumbnails();
  11408. Unindent(GetTreeNodeToLabelSpacing());
  11409. for (int i = 0; i < g.Viewports.Size; i++)
  11410. DebugNodeViewport(g.Viewports[i]);
  11411. TreePop();
  11412. }
  11413. // Details for Popups
  11414. if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
  11415. {
  11416. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  11417. {
  11418. // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
  11419. const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
  11420. ImGuiWindow* window = popup_data->Window;
  11421. BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
  11422. popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
  11423. popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
  11424. }
  11425. TreePop();
  11426. }
  11427. // Details for TabBars
  11428. if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
  11429. {
  11430. for (int n = 0; n < g.TabBars.GetMapSize(); n++)
  11431. if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
  11432. {
  11433. PushID(tab_bar);
  11434. DebugNodeTabBar(tab_bar, "TabBar");
  11435. PopID();
  11436. }
  11437. TreePop();
  11438. }
  11439. // Details for Tables
  11440. if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
  11441. {
  11442. for (int n = 0; n < g.Tables.GetMapSize(); n++)
  11443. if (ImGuiTable* table = g.Tables.TryGetMapData(n))
  11444. DebugNodeTable(table);
  11445. TreePop();
  11446. }
  11447. // Details for Fonts
  11448. ImFontAtlas* atlas = g.IO.Fonts;
  11449. if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
  11450. {
  11451. ShowFontAtlas(atlas);
  11452. TreePop();
  11453. }
  11454. // Details for InputText
  11455. if (TreeNode("InputText"))
  11456. {
  11457. DebugNodeInputTextState(&g.InputTextState);
  11458. TreePop();
  11459. }
  11460. // Details for Docking
  11461. #ifdef IMGUI_HAS_DOCK
  11462. if (TreeNode("Docking"))
  11463. {
  11464. TreePop();
  11465. }
  11466. #endif // #ifdef IMGUI_HAS_DOCK
  11467. // Settings
  11468. if (TreeNode("Settings"))
  11469. {
  11470. if (SmallButton("Clear"))
  11471. ClearIniSettings();
  11472. SameLine();
  11473. if (SmallButton("Save to memory"))
  11474. SaveIniSettingsToMemory();
  11475. SameLine();
  11476. if (SmallButton("Save to disk"))
  11477. SaveIniSettingsToDisk(g.IO.IniFilename);
  11478. SameLine();
  11479. if (g.IO.IniFilename)
  11480. Text("\"%s\"", g.IO.IniFilename);
  11481. else
  11482. TextUnformatted("<NULL>");
  11483. Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
  11484. if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
  11485. {
  11486. for (int n = 0; n < g.SettingsHandlers.Size; n++)
  11487. BulletText("%s", g.SettingsHandlers[n].TypeName);
  11488. TreePop();
  11489. }
  11490. if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
  11491. {
  11492. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  11493. DebugNodeWindowSettings(settings);
  11494. TreePop();
  11495. }
  11496. if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
  11497. {
  11498. for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
  11499. DebugNodeTableSettings(settings);
  11500. TreePop();
  11501. }
  11502. #ifdef IMGUI_HAS_DOCK
  11503. #endif // #ifdef IMGUI_HAS_DOCK
  11504. if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
  11505. {
  11506. InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
  11507. TreePop();
  11508. }
  11509. TreePop();
  11510. }
  11511. // Misc Details
  11512. if (TreeNode("Internal state"))
  11513. {
  11514. Text("WINDOWING");
  11515. Indent();
  11516. Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  11517. Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL");
  11518. Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
  11519. Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
  11520. Unindent();
  11521. Text("ITEMS");
  11522. Indent();
  11523. Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
  11524. Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  11525. int active_id_using_key_input_count = 0;
  11526. for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
  11527. active_id_using_key_input_count += g.ActiveIdUsingKeyInputMask[n] ? 1 : 0;
  11528. Text("ActiveIdUsing: NavDirMask: %X, KeyInputMask: %d key(s)", g.ActiveIdUsingNavDirMask, active_id_using_key_input_count);
  11529. Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
  11530. Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
  11531. Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
  11532. Unindent();
  11533. Text("NAV,FOCUS");
  11534. Indent();
  11535. Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  11536. Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
  11537. Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
  11538. Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
  11539. Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);
  11540. Text("NavActivateFlags: %04X", g.NavActivateFlags);
  11541. Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
  11542. Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
  11543. Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
  11544. Unindent();
  11545. TreePop();
  11546. }
  11547. // Overlay: Display windows Rectangles and Begin Order
  11548. if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
  11549. {
  11550. for (int n = 0; n < g.Windows.Size; n++)
  11551. {
  11552. ImGuiWindow* window = g.Windows[n];
  11553. if (!window->WasActive)
  11554. continue;
  11555. ImDrawList* draw_list = GetForegroundDrawList(window);
  11556. if (cfg->ShowWindowsRects)
  11557. {
  11558. ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
  11559. draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
  11560. }
  11561. if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
  11562. {
  11563. char buf[32];
  11564. ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
  11565. float font_size = GetFontSize();
  11566. draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
  11567. draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
  11568. }
  11569. }
  11570. }
  11571. // Overlay: Display Tables Rectangles
  11572. if (cfg->ShowTablesRects)
  11573. {
  11574. for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
  11575. {
  11576. ImGuiTable* table = g.Tables.TryGetMapData(table_n);
  11577. if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
  11578. continue;
  11579. ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
  11580. if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
  11581. {
  11582. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  11583. {
  11584. ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
  11585. ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
  11586. float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
  11587. draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
  11588. }
  11589. }
  11590. else
  11591. {
  11592. ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
  11593. draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
  11594. }
  11595. }
  11596. }
  11597. #ifdef IMGUI_HAS_DOCK
  11598. // Overlay: Display Docking info
  11599. if (show_docking_nodes && g.IO.KeyCtrl)
  11600. {
  11601. }
  11602. #endif // #ifdef IMGUI_HAS_DOCK
  11603. End();
  11604. }
  11605. // [DEBUG] Display contents of Columns
  11606. void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
  11607. {
  11608. if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
  11609. return;
  11610. BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
  11611. for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
  11612. BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
  11613. TreePop();
  11614. }
  11615. // [DEBUG] Display contents of ImDrawList
  11616. void ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label)
  11617. {
  11618. ImGuiContext& g = *GImGui;
  11619. ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
  11620. int cmd_count = draw_list->CmdBuffer.Size;
  11621. if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
  11622. cmd_count--;
  11623. bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
  11624. if (draw_list == GetWindowDrawList())
  11625. {
  11626. SameLine();
  11627. TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  11628. if (node_open)
  11629. TreePop();
  11630. return;
  11631. }
  11632. ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
  11633. if (window && IsItemHovered() && fg_draw_list)
  11634. fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  11635. if (!node_open)
  11636. return;
  11637. if (window && !window->WasActive)
  11638. TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
  11639. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
  11640. {
  11641. if (pcmd->UserCallback)
  11642. {
  11643. BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  11644. continue;
  11645. }
  11646. char buf[300];
  11647. ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
  11648. pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
  11649. pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  11650. bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
  11651. if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
  11652. DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
  11653. if (!pcmd_node_open)
  11654. continue;
  11655. // Calculate approximate coverage area (touched pixel count)
  11656. // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
  11657. const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  11658. const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
  11659. float total_area = 0.0f;
  11660. for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
  11661. {
  11662. ImVec2 triangle[3];
  11663. for (int n = 0; n < 3; n++, idx_n++)
  11664. triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
  11665. total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
  11666. }
  11667. // Display vertex information summary. Hover to get all triangles drawn in wire-frame
  11668. ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
  11669. Selectable(buf);
  11670. if (IsItemHovered() && fg_draw_list)
  11671. DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
  11672. // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
  11673. ImGuiListClipper clipper;
  11674. clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  11675. while (clipper.Step())
  11676. for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
  11677. {
  11678. char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
  11679. ImVec2 triangle[3];
  11680. for (int n = 0; n < 3; n++, idx_i++)
  11681. {
  11682. const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
  11683. triangle[n] = v.pos;
  11684. buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
  11685. (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  11686. }
  11687. Selectable(buf, false);
  11688. if (fg_draw_list && IsItemHovered())
  11689. {
  11690. ImDrawListFlags backup_flags = fg_draw_list->Flags;
  11691. fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  11692. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
  11693. fg_draw_list->Flags = backup_flags;
  11694. }
  11695. }
  11696. TreePop();
  11697. }
  11698. TreePop();
  11699. }
  11700. // [DEBUG] Display mesh/aabb of a ImDrawCmd
  11701. void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
  11702. {
  11703. IM_ASSERT(show_mesh || show_aabb);
  11704. // Draw wire-frame version of all triangles
  11705. ImRect clip_rect = draw_cmd->ClipRect;
  11706. ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  11707. ImDrawListFlags backup_flags = out_draw_list->Flags;
  11708. out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  11709. for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
  11710. {
  11711. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
  11712. ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
  11713. ImVec2 triangle[3];
  11714. for (int n = 0; n < 3; n++, idx_n++)
  11715. vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
  11716. if (show_mesh)
  11717. out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
  11718. }
  11719. // Draw bounding boxes
  11720. if (show_aabb)
  11721. {
  11722. out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
  11723. out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
  11724. }
  11725. out_draw_list->Flags = backup_flags;
  11726. }
  11727. // [DEBUG] Display details for a single font, called by ShowStyleEditor().
  11728. void ImGui::DebugNodeFont(ImFont* font)
  11729. {
  11730. bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
  11731. font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
  11732. SameLine();
  11733. if (SmallButton("Set as default"))
  11734. GetIO().FontDefault = font;
  11735. if (!opened)
  11736. return;
  11737. // Display preview text
  11738. PushFont(font);
  11739. Text("The quick brown fox jumps over the lazy dog");
  11740. PopFont();
  11741. // Display details
  11742. SetNextItemWidth(GetFontSize() * 8);
  11743. DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
  11744. SameLine(); MetricsHelpMarker(
  11745. "Note than the default embedded font is NOT meant to be scaled.\n\n"
  11746. "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
  11747. "You may oversample them to get some flexibility with scaling. "
  11748. "You can also render at multiple sizes and select which one to use at runtime.\n\n"
  11749. "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
  11750. Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
  11751. char c_str[5];
  11752. Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
  11753. Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
  11754. const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
  11755. Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
  11756. for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
  11757. if (font->ConfigData)
  11758. if (const ImFontConfig* cfg = &font->ConfigData[config_i])
  11759. BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
  11760. config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
  11761. // Display all glyphs of the fonts in separate pages of 256 characters
  11762. if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
  11763. {
  11764. ImDrawList* draw_list = GetWindowDrawList();
  11765. const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
  11766. const float cell_size = font->FontSize * 1;
  11767. const float cell_spacing = GetStyle().ItemSpacing.y;
  11768. for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
  11769. {
  11770. // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
  11771. // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
  11772. // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
  11773. if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
  11774. {
  11775. base += 4096 - 256;
  11776. continue;
  11777. }
  11778. int count = 0;
  11779. for (unsigned int n = 0; n < 256; n++)
  11780. if (font->FindGlyphNoFallback((ImWchar)(base + n)))
  11781. count++;
  11782. if (count <= 0)
  11783. continue;
  11784. if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
  11785. continue;
  11786. // Draw a 16x16 grid of glyphs
  11787. ImVec2 base_pos = GetCursorScreenPos();
  11788. for (unsigned int n = 0; n < 256; n++)
  11789. {
  11790. // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
  11791. // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
  11792. ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
  11793. ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
  11794. const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
  11795. draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
  11796. if (!glyph)
  11797. continue;
  11798. font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
  11799. if (IsMouseHoveringRect(cell_p1, cell_p2))
  11800. {
  11801. BeginTooltip();
  11802. DebugNodeFontGlyph(font, glyph);
  11803. EndTooltip();
  11804. }
  11805. }
  11806. Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
  11807. TreePop();
  11808. }
  11809. TreePop();
  11810. }
  11811. TreePop();
  11812. }
  11813. void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
  11814. {
  11815. Text("Codepoint: U+%04X", glyph->Codepoint);
  11816. Separator();
  11817. Text("Visible: %d", glyph->Visible);
  11818. Text("AdvanceX: %.1f", glyph->AdvanceX);
  11819. Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
  11820. Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
  11821. }
  11822. // [DEBUG] Display contents of ImGuiStorage
  11823. void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
  11824. {
  11825. if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
  11826. return;
  11827. for (int n = 0; n < storage->Data.Size; n++)
  11828. {
  11829. const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
  11830. BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
  11831. }
  11832. TreePop();
  11833. }
  11834. // [DEBUG] Display contents of ImGuiTabBar
  11835. void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
  11836. {
  11837. // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
  11838. char buf[256];
  11839. char* p = buf;
  11840. const char* buf_end = buf + IM_ARRAYSIZE(buf);
  11841. const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
  11842. p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
  11843. p += ImFormatString(p, buf_end - p, " { ");
  11844. for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
  11845. {
  11846. ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  11847. p += ImFormatString(p, buf_end - p, "%s'%s'",
  11848. tab_n > 0 ? ", " : "", (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???");
  11849. }
  11850. p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
  11851. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  11852. bool open = TreeNode(label, "%s", buf);
  11853. if (!is_active) { PopStyleColor(); }
  11854. if (is_active && IsItemHovered())
  11855. {
  11856. ImDrawList* draw_list = GetForegroundDrawList();
  11857. draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
  11858. draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
  11859. draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
  11860. }
  11861. if (open)
  11862. {
  11863. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
  11864. {
  11865. const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  11866. PushID(tab);
  11867. if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
  11868. if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
  11869. Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
  11870. tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth);
  11871. PopID();
  11872. }
  11873. TreePop();
  11874. }
  11875. }
  11876. void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
  11877. {
  11878. SetNextItemOpen(true, ImGuiCond_Once);
  11879. if (TreeNode("viewport0", "Viewport #%d", 0))
  11880. {
  11881. ImGuiWindowFlags flags = viewport->Flags;
  11882. BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f",
  11883. viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
  11884. viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y);
  11885. BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags,
  11886. (flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "",
  11887. (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
  11888. (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "");
  11889. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  11890. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  11891. DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  11892. TreePop();
  11893. }
  11894. }
  11895. void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
  11896. {
  11897. if (window == NULL)
  11898. {
  11899. BulletText("%s: NULL", label);
  11900. return;
  11901. }
  11902. ImGuiContext& g = *GImGui;
  11903. const bool is_active = window->WasActive;
  11904. ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
  11905. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  11906. const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
  11907. if (!is_active) { PopStyleColor(); }
  11908. if (IsItemHovered() && is_active)
  11909. GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  11910. if (!open)
  11911. return;
  11912. if (window->MemoryCompacted)
  11913. TextDisabled("Note: some memory buffers have been compacted/freed.");
  11914. ImGuiWindowFlags flags = window->Flags;
  11915. DebugNodeDrawList(window, window->DrawList, "DrawList");
  11916. BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
  11917. BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
  11918. (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
  11919. (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
  11920. (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
  11921. BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
  11922. BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
  11923. BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
  11924. for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
  11925. {
  11926. ImRect r = window->NavRectRel[layer];
  11927. if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
  11928. {
  11929. BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
  11930. continue;
  11931. }
  11932. BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
  11933. if (IsItemHovered())
  11934. GetForegroundDrawList(window)->AddRect(r.Min + window->Pos, r.Max + window->Pos, IM_COL32(255, 255, 0, 255));
  11935. }
  11936. BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
  11937. if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
  11938. if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
  11939. if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
  11940. if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
  11941. {
  11942. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  11943. DebugNodeColumns(&window->ColumnsStorage[n]);
  11944. TreePop();
  11945. }
  11946. DebugNodeStorage(&window->StateStorage, "Storage");
  11947. TreePop();
  11948. }
  11949. void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
  11950. {
  11951. Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
  11952. settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
  11953. }
  11954. void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
  11955. {
  11956. if (!TreeNode(label, "%s (%d)", label, windows->Size))
  11957. return;
  11958. for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
  11959. {
  11960. PushID((*windows)[i]);
  11961. DebugNodeWindow((*windows)[i], "Window");
  11962. PopID();
  11963. }
  11964. TreePop();
  11965. }
  11966. // FIXME-OPT: This is technically suboptimal, but it is simpler this way.
  11967. void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
  11968. {
  11969. for (int i = 0; i < windows_size; i++)
  11970. {
  11971. ImGuiWindow* window = windows[i];
  11972. if (window->ParentWindowInBeginStack != parent_in_begin_stack)
  11973. continue;
  11974. char buf[20];
  11975. ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
  11976. //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
  11977. DebugNodeWindow(window, buf);
  11978. Indent();
  11979. DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
  11980. Unindent();
  11981. }
  11982. }
  11983. //-----------------------------------------------------------------------------
  11984. // [SECTION] DEBUG LOG WINDOW
  11985. //-----------------------------------------------------------------------------
  11986. void ImGui::DebugLog(const char* fmt, ...)
  11987. {
  11988. va_list args;
  11989. va_start(args, fmt);
  11990. DebugLogV(fmt, args);
  11991. va_end(args);
  11992. }
  11993. void ImGui::DebugLogV(const char* fmt, va_list args)
  11994. {
  11995. ImGuiContext& g = *GImGui;
  11996. const int old_size = g.DebugLogBuf.size();
  11997. g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
  11998. g.DebugLogBuf.appendfv(fmt, args);
  11999. if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
  12000. IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
  12001. }
  12002. void ImGui::ShowDebugLogWindow(bool* p_open)
  12003. {
  12004. ImGuiContext& g = *GImGui;
  12005. if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
  12006. SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
  12007. if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
  12008. {
  12009. End();
  12010. return;
  12011. }
  12012. AlignTextToFramePadding();
  12013. Text("Log events:");
  12014. SameLine(); CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
  12015. SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
  12016. SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
  12017. SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
  12018. SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
  12019. SameLine(); CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper);
  12020. SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
  12021. if (SmallButton("Clear"))
  12022. g.DebugLogBuf.clear();
  12023. SameLine();
  12024. if (SmallButton("Copy"))
  12025. SetClipboardText(g.DebugLogBuf.c_str());
  12026. BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
  12027. TextUnformatted(g.DebugLogBuf.begin(), g.DebugLogBuf.end()); // FIXME-OPT: Could use a line index, but TextUnformatted() has a semi-decent fast path for large text.
  12028. if (GetScrollY() >= GetScrollMaxY())
  12029. SetScrollHereY(1.0f);
  12030. EndChild();
  12031. End();
  12032. }
  12033. //-----------------------------------------------------------------------------
  12034. // [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
  12035. //-----------------------------------------------------------------------------
  12036. // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
  12037. void ImGui::UpdateDebugToolItemPicker()
  12038. {
  12039. ImGuiContext& g = *GImGui;
  12040. g.DebugItemPickerBreakId = 0;
  12041. if (!g.DebugItemPickerActive)
  12042. return;
  12043. const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
  12044. SetMouseCursor(ImGuiMouseCursor_Hand);
  12045. if (IsKeyPressed(ImGuiKey_Escape))
  12046. g.DebugItemPickerActive = false;
  12047. const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
  12048. if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
  12049. {
  12050. g.DebugItemPickerBreakId = hovered_id;
  12051. g.DebugItemPickerActive = false;
  12052. }
  12053. for (int mouse_button = 0; mouse_button < 3; mouse_button++)
  12054. if (change_mapping && IsMouseClicked(mouse_button))
  12055. g.DebugItemPickerMouseButton = (ImU8)mouse_button;
  12056. SetNextWindowBgAlpha(0.70f);
  12057. BeginTooltip();
  12058. Text("HoveredId: 0x%08X", hovered_id);
  12059. Text("Press ESC to abort picking.");
  12060. const char* mouse_button_names[] = { "Left", "Right", "Middle" };
  12061. if (change_mapping)
  12062. Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
  12063. else
  12064. TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
  12065. EndTooltip();
  12066. }
  12067. // [DEBUG] Stack Tool: update queries. Called by NewFrame()
  12068. void ImGui::UpdateDebugToolStackQueries()
  12069. {
  12070. ImGuiContext& g = *GImGui;
  12071. ImGuiStackTool* tool = &g.DebugStackTool;
  12072. // Clear hook when stack tool is not visible
  12073. g.DebugHookIdInfo = 0;
  12074. if (g.FrameCount != tool->LastActiveFrame + 1)
  12075. return;
  12076. // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
  12077. // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
  12078. const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
  12079. if (tool->QueryId != query_id)
  12080. {
  12081. tool->QueryId = query_id;
  12082. tool->StackLevel = -1;
  12083. tool->Results.resize(0);
  12084. }
  12085. if (query_id == 0)
  12086. return;
  12087. // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
  12088. int stack_level = tool->StackLevel;
  12089. if (stack_level >= 0 && stack_level < tool->Results.Size)
  12090. if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
  12091. tool->StackLevel++;
  12092. // Update hook
  12093. stack_level = tool->StackLevel;
  12094. if (stack_level == -1)
  12095. g.DebugHookIdInfo = query_id;
  12096. if (stack_level >= 0 && stack_level < tool->Results.Size)
  12097. {
  12098. g.DebugHookIdInfo = tool->Results[stack_level].ID;
  12099. tool->Results[stack_level].QueryFrameCount++;
  12100. }
  12101. }
  12102. // [DEBUG] Stack tool: hooks called by GetID() family functions
  12103. void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
  12104. {
  12105. ImGuiContext& g = *GImGui;
  12106. ImGuiWindow* window = g.CurrentWindow;
  12107. ImGuiStackTool* tool = &g.DebugStackTool;
  12108. // Step 0: stack query
  12109. // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
  12110. if (tool->StackLevel == -1)
  12111. {
  12112. tool->StackLevel++;
  12113. tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
  12114. for (int n = 0; n < window->IDStack.Size + 1; n++)
  12115. tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
  12116. return;
  12117. }
  12118. // Step 1+: query for individual level
  12119. IM_ASSERT(tool->StackLevel >= 0);
  12120. if (tool->StackLevel != window->IDStack.Size)
  12121. return;
  12122. ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
  12123. IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
  12124. switch (data_type)
  12125. {
  12126. case ImGuiDataType_S32:
  12127. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
  12128. break;
  12129. case ImGuiDataType_String:
  12130. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
  12131. break;
  12132. case ImGuiDataType_Pointer:
  12133. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
  12134. break;
  12135. case ImGuiDataType_ID:
  12136. if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
  12137. return;
  12138. ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
  12139. break;
  12140. default:
  12141. IM_ASSERT(0);
  12142. }
  12143. info->QuerySuccess = true;
  12144. info->DataType = data_type;
  12145. }
  12146. static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
  12147. {
  12148. ImGuiStackLevelInfo* info = &tool->Results[n];
  12149. ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
  12150. if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
  12151. return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
  12152. if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
  12153. return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
  12154. if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
  12155. return (*buf = 0);
  12156. #ifdef IMGUI_ENABLE_TEST_ENGINE
  12157. if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo()
  12158. return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
  12159. #endif
  12160. return ImFormatString(buf, buf_size, "???");
  12161. }
  12162. // Stack Tool: Display UI
  12163. void ImGui::ShowStackToolWindow(bool* p_open)
  12164. {
  12165. ImGuiContext& g = *GImGui;
  12166. if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
  12167. SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
  12168. if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
  12169. {
  12170. End();
  12171. return;
  12172. }
  12173. // Display hovered/active status
  12174. ImGuiStackTool* tool = &g.DebugStackTool;
  12175. const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
  12176. const ImGuiID active_id = g.ActiveId;
  12177. #ifdef IMGUI_ENABLE_TEST_ENGINE
  12178. Text("HoveredId: 0x%08X (\"%s\"), ActiveId: 0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
  12179. #else
  12180. Text("HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id);
  12181. #endif
  12182. SameLine();
  12183. MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
  12184. // CTRL+C to copy path
  12185. const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
  12186. Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
  12187. SameLine();
  12188. TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
  12189. if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
  12190. {
  12191. tool->CopyToClipboardLastTime = (float)g.Time;
  12192. char* p = g.TempBuffer.Data;
  12193. char* p_end = p + g.TempBuffer.Size;
  12194. for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
  12195. {
  12196. *p++ = '/';
  12197. char level_desc[256];
  12198. StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
  12199. for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
  12200. {
  12201. if (level_desc[n] == '/')
  12202. *p++ = '\\';
  12203. *p++ = level_desc[n];
  12204. }
  12205. }
  12206. *p = '\0';
  12207. SetClipboardText(g.TempBuffer.Data);
  12208. }
  12209. // Display decorated stack
  12210. tool->LastActiveFrame = g.FrameCount;
  12211. if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
  12212. {
  12213. const float id_width = CalcTextSize("0xDDDDDDDD").x;
  12214. TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
  12215. TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
  12216. TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
  12217. TableHeadersRow();
  12218. for (int n = 0; n < tool->Results.Size; n++)
  12219. {
  12220. ImGuiStackLevelInfo* info = &tool->Results[n];
  12221. TableNextColumn();
  12222. Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
  12223. TableNextColumn();
  12224. StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
  12225. TextUnformatted(g.TempBuffer.Data);
  12226. TableNextColumn();
  12227. Text("0x%08X", info->ID);
  12228. if (n == tool->Results.Size - 1)
  12229. TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
  12230. }
  12231. EndTable();
  12232. }
  12233. End();
  12234. }
  12235. #else
  12236. void ImGui::ShowMetricsWindow(bool*) {}
  12237. void ImGui::ShowFontAtlas(ImFontAtlas*) {}
  12238. void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
  12239. void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {}
  12240. void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
  12241. void ImGui::DebugNodeFont(ImFont*) {}
  12242. void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
  12243. void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
  12244. void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
  12245. void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
  12246. void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
  12247. void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
  12248. void ImGui::DebugLog(const char*, ...) {}
  12249. void ImGui::DebugLogV(const char*, va_list) {}
  12250. void ImGui::ShowDebugLogWindow(bool*) {}
  12251. void ImGui::ShowStackToolWindow(bool*) {}
  12252. void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
  12253. void ImGui::UpdateDebugToolItemPicker() {}
  12254. void ImGui::UpdateDebugToolStackQueries() {}
  12255. #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
  12256. //-----------------------------------------------------------------------------
  12257. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  12258. // 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.
  12259. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  12260. #include "imgui_user.inl"
  12261. #endif
  12262. //-----------------------------------------------------------------------------
  12263. #endif // #ifndef IMGUI_DISABLE