imgui.cpp 827 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959
  1. // dear imgui, v1.83 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/3793 (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. // - Discussions https://github.com/ocornut/imgui/discussions
  17. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  18. // See LICENSE.txt for copyright and licensing details (standard MIT License).
  19. // This library is free but needs your support to sustain development and maintenance.
  20. // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
  21. // Individuals: you can support continued development via donations. See docs/README or web page.
  22. // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
  23. // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
  24. // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
  25. // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
  26. // to a better solution or official support for them.
  27. /*
  28. Index of this file:
  29. DOCUMENTATION
  30. - MISSION STATEMENT
  31. - END-USER GUIDE
  32. - PROGRAMMER GUIDE
  33. - READ FIRST
  34. - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  35. - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  36. - HOW A SIMPLE APPLICATION MAY LOOK LIKE
  37. - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  38. - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  39. - API BREAKING CHANGES (read me when you update!)
  40. - FREQUENTLY ASKED QUESTIONS (FAQ)
  41. - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
  42. CODE
  43. (search for "[SECTION]" in the code to find them)
  44. // [SECTION] INCLUDES
  45. // [SECTION] FORWARD DECLARATIONS
  46. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  47. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  48. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  49. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  50. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  51. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  52. // [SECTION] MISC HELPERS/UTILITIES (Color functions)
  53. // [SECTION] ImGuiStorage
  54. // [SECTION] ImGuiTextFilter
  55. // [SECTION] ImGuiTextBuffer
  56. // [SECTION] ImGuiListClipper
  57. // [SECTION] STYLING
  58. // [SECTION] RENDER HELPERS
  59. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  60. // [SECTION] ERROR CHECKING
  61. // [SECTION] LAYOUT
  62. // [SECTION] SCROLLING
  63. // [SECTION] TOOLTIPS
  64. // [SECTION] POPUPS
  65. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  66. // [SECTION] DRAG AND DROP
  67. // [SECTION] LOGGING/CAPTURING
  68. // [SECTION] SETTINGS
  69. // [SECTION] VIEWPORTS, PLATFORM WINDOWS
  70. // [SECTION] DOCKING
  71. // [SECTION] PLATFORM DEPENDENT HELPERS
  72. // [SECTION] METRICS/DEBUGGER WINDOW
  73. */
  74. //-----------------------------------------------------------------------------
  75. // DOCUMENTATION
  76. //-----------------------------------------------------------------------------
  77. /*
  78. MISSION STATEMENT
  79. =================
  80. - Easy to use to create code-driven and data-driven tools.
  81. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
  82. - Easy to hack and improve.
  83. - Minimize setup and maintenance.
  84. - Minimize state storage on user side.
  85. - Portable, minimize dependencies, run on target (consoles, phones, etc.).
  86. - Efficient runtime and memory consumption.
  87. Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
  88. - Doesn't look fancy, doesn't animate.
  89. - Limited layout features, intricate layouts are typically crafted in code.
  90. END-USER GUIDE
  91. ==============
  92. - Double-click on title bar to collapse window.
  93. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
  94. - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
  95. - Click and drag on any empty space to move window.
  96. - TAB/SHIFT+TAB to cycle through keyboard editable fields.
  97. - CTRL+Click on a slider or drag box to input value as text.
  98. - Use mouse wheel to scroll.
  99. - Text editor:
  100. - Hold SHIFT or use mouse to select text.
  101. - CTRL+Left/Right to word jump.
  102. - CTRL+Shift+Left/Right to select words.
  103. - CTRL+A our Double-Click to select all.
  104. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
  105. - CTRL+Z,CTRL+Y to undo/redo.
  106. - ESCAPE to revert text to its original value.
  107. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  108. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  109. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
  110. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://dearimgui.org/controls_sheets
  111. PROGRAMMER GUIDE
  112. ================
  113. READ FIRST
  114. ----------
  115. - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
  116. - 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
  117. destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
  118. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
  119. - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
  120. - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
  121. You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
  122. - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
  123. 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,
  124. where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
  125. - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
  126. - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
  127. - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
  128. If you get an assert, read the messages and comments around the assert.
  129. - 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.
  130. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
  131. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
  132. However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
  133. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
  134. HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  135. ----------------------------------------------
  136. - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
  137. - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
  138. - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
  139. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  140. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
  141. from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
  142. likely be a comment about it. Please report any issue to the GitHub page!
  143. - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
  144. - Try to keep your copy of Dear ImGui reasonably up to date.
  145. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  146. ---------------------------------------------------------------
  147. - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
  148. - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
  149. - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
  150. It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
  151. - 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.
  152. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
  153. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
  154. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
  155. phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
  156. - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
  157. - 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.
  158. HOW A SIMPLE APPLICATION MAY LOOK LIKE
  159. --------------------------------------
  160. EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
  161. The sub-folders in examples/ contain examples applications following this structure.
  162. // Application init: create a dear imgui context, setup some options, load fonts
  163. ImGui::CreateContext();
  164. ImGuiIO& io = ImGui::GetIO();
  165. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  166. // TODO: Fill optional fields of the io structure later.
  167. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  168. // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
  169. ImGui_ImplWin32_Init(hwnd);
  170. ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
  171. // Application main loop
  172. while (true)
  173. {
  174. // Feed inputs to dear imgui, start new frame
  175. ImGui_ImplDX11_NewFrame();
  176. ImGui_ImplWin32_NewFrame();
  177. ImGui::NewFrame();
  178. // Any application code here
  179. ImGui::Text("Hello, world!");
  180. // Render dear imgui into screen
  181. ImGui::Render();
  182. ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
  183. g_pSwapChain->Present(1, 0);
  184. }
  185. // Shutdown
  186. ImGui_ImplDX11_Shutdown();
  187. ImGui_ImplWin32_Shutdown();
  188. ImGui::DestroyContext();
  189. EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
  190. // Application init: create a dear imgui context, setup some options, load fonts
  191. ImGui::CreateContext();
  192. ImGuiIO& io = ImGui::GetIO();
  193. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  194. // TODO: Fill optional fields of the io structure later.
  195. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  196. // Build and load the texture atlas into a texture
  197. // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
  198. int width, height;
  199. unsigned char* pixels = NULL;
  200. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  201. // At this point you've got the texture data and you need to upload that to your graphic system:
  202. // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
  203. // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
  204. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
  205. io.Fonts->SetTexID((void*)texture);
  206. // Application main loop
  207. while (true)
  208. {
  209. // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
  210. // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
  211. io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
  212. io.DisplaySize.x = 1920.0f; // set the current display width
  213. io.DisplaySize.y = 1280.0f; // set the current display height here
  214. io.MousePos = my_mouse_pos; // set the mouse position
  215. io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
  216. io.MouseDown[1] = my_mouse_buttons[1];
  217. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  218. // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
  219. ImGui::NewFrame();
  220. // Most of your application code here
  221. ImGui::Text("Hello, world!");
  222. MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  223. MyGameRender(); // may use any Dear ImGui functions as well!
  224. // Render dear imgui, swap buffers
  225. // (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)
  226. ImGui::EndFrame();
  227. ImGui::Render();
  228. ImDrawData* draw_data = ImGui::GetDrawData();
  229. MyImGuiRenderFunction(draw_data);
  230. SwapBuffers();
  231. }
  232. // Shutdown
  233. ImGui::DestroyContext();
  234. To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
  235. you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
  236. Please read the FAQ and example applications for details about this!
  237. HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  238. ---------------------------------------------
  239. The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
  240. void void MyImGuiRenderFunction(ImDrawData* draw_data)
  241. {
  242. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  243. // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  244. // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  245. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  246. for (int n = 0; n < draw_data->CmdListsCount; n++)
  247. {
  248. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  249. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
  250. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
  251. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  252. {
  253. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  254. if (pcmd->UserCallback)
  255. {
  256. pcmd->UserCallback(cmd_list, pcmd);
  257. }
  258. else
  259. {
  260. // The texture for the draw call is specified by pcmd->GetTexID().
  261. // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
  262. MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
  263. // We are using scissoring to clip some objects. All low-level graphics API should support it.
  264. // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
  265. // (some elements visible outside their bounds) but you can fix that once everything else works!
  266. // - Clipping coordinates are provided in imgui coordinates space:
  267. // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
  268. // - 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.
  269. // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
  270. // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
  271. // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
  272. ImVec2 pos = draw_data->DisplayPos;
  273. MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
  274. // Render 'pcmd->ElemCount/3' indexed triangles.
  275. // 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.
  276. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
  277. }
  278. idx_buffer += pcmd->ElemCount;
  279. }
  280. }
  281. }
  282. USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  283. ------------------------------------------
  284. - The gamepad/keyboard navigation is fairly functional and keeps being improved.
  285. - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
  286. - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
  287. - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
  288. - Keyboard:
  289. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
  290. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
  291. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
  292. will be set. For more advanced uses, you may want to read from:
  293. - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
  294. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
  295. - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
  296. Please reach out if you think the game vs navigation input sharing could be improved.
  297. - Gamepad:
  298. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
  299. - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
  300. Note that io.NavInputs[] is cleared by EndFrame().
  301. - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
  302. 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
  303. - We use a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
  304. Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
  305. - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
  306. - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
  307. to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
  308. - Mouse:
  309. - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
  310. - 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.
  311. - 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.
  312. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
  313. 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.
  314. 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.
  315. (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!)
  316. (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
  317. to set a boolean to ignore your other external mouse positions until the external source is moved again.)
  318. API BREAKING CHANGES
  319. ====================
  320. Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
  321. 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.
  322. 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.
  323. You can read releases logs https://github.com/ocornut/imgui/releases for more details.
  324. (Docking/Viewport Branch)
  325. - 2021/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
  326. - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
  327. you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
  328. - likewise io.MousePos and GetMousePos() will use OS coordinates.
  329. If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
  330. - 2021/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api.
  331. - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
  332. - if you are using official backends from the source tree: you have nothing to do.
  333. - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
  334. - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
  335. - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
  336. - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
  337. - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
  338. flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
  339. breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
  340. - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
  341. - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
  342. - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
  343. - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
  344. this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
  345. 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.
  346. 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).
  347. - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
  348. - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
  349. - 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.
  350. - 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.
  351. - 2021/02/22 (1.82) - 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'.
  352. - 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.
  353. - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
  354. - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
  355. - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
  356. - 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.
  357. - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
  358. - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
  359. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
  360. - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
  361. - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
  362. - ImGuiInputTextCallback -> use ImGuiTextEditCallback
  363. - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
  364. - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
  365. - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
  366. - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
  367. - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
  368. - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
  369. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
  370. - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
  371. - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
  372. - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
  373. - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
  374. - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
  375. - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
  376. - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
  377. - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
  378. - 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).
  379. - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
  380. - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
  381. - 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.
  382. - 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.
  383. - 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!
  384. - 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().
  385. replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
  386. worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
  387. - if you omitted the 'power' parameter (likely!), you are not affected.
  388. - 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.
  389. - 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.
  390. see https://github.com/ocornut/imgui/issues/3361 for all details.
  391. 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.
  392. for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
  393. - 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.
  394. - 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.
  395. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
  396. - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
  397. - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
  398. - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
  399. - 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.
  400. - 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.
  401. - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
  402. - ShowTestWindow() -> use ShowDemoWindow()
  403. - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
  404. - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
  405. - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
  406. - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
  407. - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
  408. - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
  409. - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
  410. - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
  411. - 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.
  412. - 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).
  413. - 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.
  414. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
  415. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
  416. - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
  417. - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
  418. - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
  419. - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
  420. - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
  421. - ImFont::Glyph -> use ImFontGlyph
  422. - 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.
  423. 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.
  424. 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).
  425. If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
  426. - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
  427. - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
  428. - 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.
  429. - 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
  430. 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.
  431. 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.
  432. Please reach out if you are affected.
  433. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
  434. - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
  435. - 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.
  436. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
  437. - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
  438. - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
  439. - 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!
  440. - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
  441. - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
  442. - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
  443. - 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.
  444. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
  445. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
  446. - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
  447. - 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.
  448. If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
  449. - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
  450. - 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.
  451. NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
  452. Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
  453. - 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).
  454. - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
  455. - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
  456. - 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.
  457. - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
  458. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
  459. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
  460. - 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.).
  461. old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
  462. when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
  463. in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
  464. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
  465. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
  466. - 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.
  467. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
  468. 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.
  469. 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.
  470. - 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",
  471. consistent with other functions. Kept redirection functions (will obsolete).
  472. - 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.
  473. - 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).
  474. - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
  475. - 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.
  476. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
  477. - 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.
  478. - 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.
  479. - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
  480. - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
  481. - removed Shutdown() function, as DestroyContext() serve this purpose.
  482. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
  483. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
  484. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
  485. - 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.
  486. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
  487. - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
  488. - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
  489. - 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.
  490. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
  491. - 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
  492. - 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.
  493. - 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.
  494. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
  495. - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
  496. - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
  497. - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
  498. - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
  499. - 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.
  500. - 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.
  501. 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.
  502. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
  503. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
  504. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
  505. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
  506. - 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.
  507. - 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.
  508. - 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.
  509. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
  510. IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
  511. IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
  512. IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
  513. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
  514. - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
  515. - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
  516. - 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).
  517. - 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)".
  518. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
  519. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  520. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  521. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  522. - 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.
  523. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
  524. - 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.
  525. - 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).
  526. - 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).
  527. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  528. - 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.
  529. - 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.
  530. - 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))'
  531. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  532. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  533. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  534. - 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().
  535. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  536. - 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.
  537. - 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.
  538. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  539. 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.
  540. 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:
  541. 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); }
  542. 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.
  543. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  544. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  545. - 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).
  546. - 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.
  547. - 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).
  548. - 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)
  549. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  550. - 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.
  551. - 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.
  552. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  553. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  554. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  555. 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.
  556. 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!
  557. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  558. - 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.
  559. - 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
  560. - 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.
  561. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  562. - 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.
  563. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  564. - 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.
  565. - the signature of the io.RenderDrawListsFn handler has changed!
  566. old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  567. new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  568. parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
  569. ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
  570. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
  571. - 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.
  572. - 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!
  573. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  574. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  575. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  576. - 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.
  577. - 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
  578. - 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!
  579. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  580. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  581. - 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.
  582. - 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.
  583. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  584. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  585. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  586. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  587. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  588. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  589. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  590. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  591. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  592. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  593. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  594. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  595. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  596. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  597. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  598. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  599. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  600. - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  601. - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
  602. - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
  603. 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.
  604. - 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()
  605. - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  606. - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  607. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  608. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  609. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  610. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  611. - 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)
  612. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  613. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  614. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  615. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  616. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  617. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  618. FREQUENTLY ASKED QUESTIONS (FAQ)
  619. ================================
  620. Read all answers online:
  621. https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
  622. Read all answers locally (with a text editor or ideally a Markdown viewer):
  623. docs/FAQ.md
  624. Some answers are copied down here to facilitate searching in code.
  625. Q&A: Basics
  626. ===========
  627. Q: Where is the documentation?
  628. A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
  629. - Run the examples/ and explore them.
  630. - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
  631. - The demo covers most features of Dear ImGui, so you can read the code and see its output.
  632. - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
  633. - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
  634. examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
  635. - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
  636. - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
  637. - Your programming IDE is your friend, find the type or function declaration to find comments
  638. associated with it.
  639. Q: What is this library called?
  640. Q: Which version should I get?
  641. >> This library is called "Dear ImGui", please don't call it "ImGui" :)
  642. >> See https://www.dearimgui.org/faq for details.
  643. Q&A: Integration
  644. ================
  645. Q: How to get started?
  646. A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
  647. Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
  648. A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
  649. >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
  650. Q. How can I enable keyboard controls?
  651. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
  652. Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
  653. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
  654. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
  655. >> See https://www.dearimgui.org/faq
  656. Q&A: Usage
  657. ----------
  658. Q: Why is my widget not reacting when I click on it?
  659. Q: How can I have widgets with an empty label?
  660. Q: How can I have multiple widgets with the same label?
  661. Q: How can I display an image? What is ImTextureID, how does it works?
  662. Q: How can I use my own math types instead of ImVec2/ImVec4?
  663. Q: How can I interact with standard C++ types (such as std::string and std::vector)?
  664. Q: How can I display custom shapes? (using low-level ImDrawList API)
  665. >> See https://www.dearimgui.org/faq
  666. Q&A: Fonts, Text
  667. ================
  668. Q: How should I handle DPI in my application?
  669. Q: How can I load a different font than the default?
  670. Q: How can I easily use icons in my application?
  671. Q: How can I load multiple fonts?
  672. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  673. >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
  674. Q&A: Concerns
  675. =============
  676. Q: Who uses Dear ImGui?
  677. Q: Can you create elaborate/serious tools with Dear ImGui?
  678. Q: Can you reskin the look of Dear ImGui?
  679. Q: Why using C++ (as opposed to C)?
  680. >> See https://www.dearimgui.org/faq
  681. Q&A: Community
  682. ==============
  683. Q: How can I help?
  684. A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
  685. We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
  686. 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.
  687. - Individuals: you can support continued development via PayPal donations. See README.
  688. - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
  689. and see how you want to help and can help!
  690. - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
  691. You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
  692. But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
  693. - 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).
  694. */
  695. //-------------------------------------------------------------------------
  696. // [SECTION] INCLUDES
  697. //-------------------------------------------------------------------------
  698. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  699. #define _CRT_SECURE_NO_WARNINGS
  700. #endif
  701. #include "imgui.h"
  702. #ifndef IMGUI_DISABLE
  703. #ifndef IMGUI_DEFINE_MATH_OPERATORS
  704. #define IMGUI_DEFINE_MATH_OPERATORS
  705. #endif
  706. #include "imgui_internal.h"
  707. // System includes
  708. #include <ctype.h> // toupper
  709. #include <stdio.h> // vsnprintf, sscanf, printf
  710. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  711. #include <stddef.h> // intptr_t
  712. #else
  713. #include <stdint.h> // intptr_t
  714. #endif
  715. // [Windows] OS specific includes (optional)
  716. #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)
  717. #define IMGUI_DISABLE_WIN32_FUNCTIONS
  718. #endif
  719. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
  720. #ifndef WIN32_LEAN_AND_MEAN
  721. #define WIN32_LEAN_AND_MEAN
  722. #endif
  723. #ifndef NOMINMAX
  724. #define NOMINMAX
  725. #endif
  726. #ifndef __MINGW32__
  727. #include <Windows.h> // _wfopen, OpenClipboard
  728. #else
  729. #include <windows.h>
  730. #endif
  731. #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
  732. #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
  733. #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
  734. #endif
  735. #endif
  736. // [Apple] OS specific includes
  737. #if defined(__APPLE__)
  738. #include <TargetConditionals.h>
  739. #endif
  740. // Visual Studio warnings
  741. #ifdef _MSC_VER
  742. #pragma warning (disable: 4127) // condition expression is constant
  743. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  744. #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
  745. #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
  746. #endif
  747. #pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
  748. #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
  749. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  750. #endif
  751. // Clang/GCC warnings with -Weverything
  752. #if defined(__clang__)
  753. #if __has_warning("-Wunknown-warning-option")
  754. #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!
  755. #endif
  756. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
  757. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
  758. #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.
  759. #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.
  760. #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.
  761. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
  762. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  763. #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.
  764. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
  765. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
  766. #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.
  767. #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
  768. #elif defined(__GNUC__)
  769. // We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
  770. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  771. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  772. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  773. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  774. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  775. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  776. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  777. #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
  778. #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
  779. #endif
  780. // Debug options
  781. #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
  782. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
  783. #define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
  784. // 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.
  785. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
  786. static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
  787. // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
  788. static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
  789. static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
  790. static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
  791. // Docking
  792. static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
  793. static const float DOCKING_SPLITTER_SIZE = 2.0f;
  794. //-------------------------------------------------------------------------
  795. // [SECTION] FORWARD DECLARATIONS
  796. //-------------------------------------------------------------------------
  797. static void SetCurrentWindow(ImGuiWindow* window);
  798. static void FindHoveredWindow();
  799. static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
  800. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
  801. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
  802. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
  803. // Settings
  804. static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
  805. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
  806. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
  807. static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
  808. static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
  809. // Platform Dependents default implementation for IO functions
  810. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  811. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  812. namespace ImGui
  813. {
  814. // Navigation
  815. static void NavUpdate();
  816. static void NavUpdateWindowing();
  817. static void NavUpdateWindowingOverlay();
  818. static void NavUpdateMoveResult();
  819. static void NavUpdateInitResult();
  820. static float NavUpdatePageUpPageDown();
  821. static inline void NavUpdateAnyRequestFlag();
  822. static void NavEndFrame();
  823. static bool NavScoreItem(ImGuiNavItemData* result, ImRect cand);
  824. static void NavApplyItemToResult(ImGuiNavItemData* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel);
  825. static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
  826. static ImVec2 NavCalcPreferredRefPos();
  827. static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
  828. static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
  829. static void NavRestoreLayer(ImGuiNavLayer layer);
  830. static int FindWindowFocusIndex(ImGuiWindow* window);
  831. // Error Checking
  832. static void ErrorCheckNewFrameSanityChecks();
  833. static void ErrorCheckEndFrameSanityChecks();
  834. // Misc
  835. static void UpdateSettings();
  836. static void UpdateMouseInputs();
  837. static void UpdateMouseWheel();
  838. static void UpdateTabFocus();
  839. static void UpdateDebugToolItemPicker();
  840. 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);
  841. static void RenderWindowOuterBorders(ImGuiWindow* window);
  842. static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
  843. static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
  844. static void EndFrameDrawDimmedBackgrounds();
  845. // Viewports
  846. const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
  847. static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
  848. static void UpdateViewportsNewFrame();
  849. static void UpdateViewportsEndFrame();
  850. static void UpdateSelectWindowViewport(ImGuiWindow* window);
  851. static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
  852. static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
  853. static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
  854. static int FindPlatformMonitorForPos(const ImVec2& pos);
  855. static int FindPlatformMonitorForRect(const ImRect& r);
  856. static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
  857. }
  858. //-----------------------------------------------------------------------------
  859. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  860. //-----------------------------------------------------------------------------
  861. // DLL users:
  862. // - Heaps and globals are not shared across DLL boundaries!
  863. // - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
  864. // - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
  865. // - 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.
  866. // - 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).
  867. // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
  868. // - ImGui::CreateContext() will automatically set this pointer if it is NULL.
  869. // Change to a different context by calling ImGui::SetCurrentContext().
  870. // - Important: Dear ImGui functions are not thread-safe because of this pointer.
  871. // If you want thread-safety to allow N threads to access N different contexts:
  872. // - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
  873. // struct ImGuiContext;
  874. // extern thread_local ImGuiContext* MyImGuiTLS;
  875. // #define GImGui MyImGuiTLS
  876. // 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.
  877. // - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  878. // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
  879. // - DLL users: read comments above.
  880. #ifndef GImGui
  881. ImGuiContext* GImGui = NULL;
  882. #endif
  883. // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
  884. // - 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.
  885. // - DLL users: read comments above.
  886. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
  887. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
  888. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
  889. #else
  890. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
  891. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
  892. #endif
  893. static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
  894. static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
  895. static void* GImAllocatorUserData = NULL;
  896. //-----------------------------------------------------------------------------
  897. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  898. //-----------------------------------------------------------------------------
  899. ImGuiStyle::ImGuiStyle()
  900. {
  901. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  902. WindowPadding = ImVec2(8,8); // Padding within a window
  903. 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.
  904. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  905. WindowMinSize = ImVec2(32,32); // Minimum window size
  906. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  907. WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
  908. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  909. ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  910. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
  911. PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  912. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  913. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  914. FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
  915. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  916. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  917. CellPadding = ImVec2(4,2); // Padding within a table cell
  918. 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!
  919. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  920. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
  921. ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  922. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  923. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  924. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  925. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
  926. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
  927. TabBorderSize = 0.0f; // Thickness of border around tabs.
  928. TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
  929. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
  930. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  931. 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.
  932. 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.
  933. 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.
  934. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
  935. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
  936. AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering.
  937. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
  938. 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.
  939. 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.
  940. // Default theme
  941. ImGui::StyleColorsDark(this);
  942. }
  943. // 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.
  944. // 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.
  945. void ImGuiStyle::ScaleAllSizes(float scale_factor)
  946. {
  947. WindowPadding = ImFloor(WindowPadding * scale_factor);
  948. WindowRounding = ImFloor(WindowRounding * scale_factor);
  949. WindowMinSize = ImFloor(WindowMinSize * scale_factor);
  950. ChildRounding = ImFloor(ChildRounding * scale_factor);
  951. PopupRounding = ImFloor(PopupRounding * scale_factor);
  952. FramePadding = ImFloor(FramePadding * scale_factor);
  953. FrameRounding = ImFloor(FrameRounding * scale_factor);
  954. ItemSpacing = ImFloor(ItemSpacing * scale_factor);
  955. ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
  956. CellPadding = ImFloor(CellPadding * scale_factor);
  957. TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
  958. IndentSpacing = ImFloor(IndentSpacing * scale_factor);
  959. ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
  960. ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
  961. ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
  962. GrabMinSize = ImFloor(GrabMinSize * scale_factor);
  963. GrabRounding = ImFloor(GrabRounding * scale_factor);
  964. LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
  965. TabRounding = ImFloor(TabRounding * scale_factor);
  966. TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
  967. DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
  968. DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
  969. MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
  970. }
  971. ImGuiIO::ImGuiIO()
  972. {
  973. // Most fields are initialized with zero
  974. memset(this, 0, sizeof(*this));
  975. IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
  976. // Settings
  977. ConfigFlags = ImGuiConfigFlags_None;
  978. BackendFlags = ImGuiBackendFlags_None;
  979. DisplaySize = ImVec2(-1.0f, -1.0f);
  980. DeltaTime = 1.0f / 60.0f;
  981. IniSavingRate = 5.0f;
  982. IniFilename = "imgui.ini";
  983. LogFilename = "imgui_log.txt";
  984. MouseDoubleClickTime = 0.30f;
  985. MouseDoubleClickMaxDist = 6.0f;
  986. for (int i = 0; i < ImGuiKey_COUNT; i++)
  987. KeyMap[i] = -1;
  988. KeyRepeatDelay = 0.275f;
  989. KeyRepeatRate = 0.050f;
  990. UserData = NULL;
  991. Fonts = NULL;
  992. FontGlobalScale = 1.0f;
  993. FontDefault = NULL;
  994. FontAllowUserScaling = false;
  995. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  996. // Docking options (when ImGuiConfigFlags_DockingEnable is set)
  997. ConfigDockingNoSplit = false;
  998. ConfigDockingAlwaysTabBar = false;
  999. ConfigDockingTransparentPayload = false;
  1000. // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
  1001. ConfigViewportsNoAutoMerge = false;
  1002. ConfigViewportsNoTaskBarIcon = false;
  1003. ConfigViewportsNoDecoration = true;
  1004. ConfigViewportsNoDefaultParent = false;
  1005. // Miscellaneous options
  1006. MouseDrawCursor = false;
  1007. #ifdef __APPLE__
  1008. ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
  1009. #else
  1010. ConfigMacOSXBehaviors = false;
  1011. #endif
  1012. ConfigInputTextCursorBlink = true;
  1013. ConfigWindowsResizeFromEdges = true;
  1014. ConfigWindowsMoveFromTitleBarOnly = false;
  1015. ConfigMemoryCompactTimer = 60.0f;
  1016. // Platform Functions
  1017. BackendPlatformName = BackendRendererName = NULL;
  1018. BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
  1019. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  1020. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  1021. ClipboardUserData = NULL;
  1022. // Input (NB: we already have memset zero the entire structure!)
  1023. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  1024. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  1025. MouseDragThreshold = 6.0f;
  1026. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  1027. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  1028. for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
  1029. }
  1030. // Pass in translated ASCII characters for text input.
  1031. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  1032. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  1033. void ImGuiIO::AddInputCharacter(unsigned int c)
  1034. {
  1035. if (c != 0)
  1036. InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
  1037. }
  1038. // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
  1039. // we should save the high surrogate.
  1040. void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
  1041. {
  1042. if (c == 0 && InputQueueSurrogate == 0)
  1043. return;
  1044. if ((c & 0xFC00) == 0xD800) // High surrogate, must save
  1045. {
  1046. if (InputQueueSurrogate != 0)
  1047. InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
  1048. InputQueueSurrogate = c;
  1049. return;
  1050. }
  1051. ImWchar cp = c;
  1052. if (InputQueueSurrogate != 0)
  1053. {
  1054. if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
  1055. {
  1056. InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
  1057. }
  1058. else
  1059. {
  1060. #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
  1061. cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
  1062. #else
  1063. cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
  1064. #endif
  1065. }
  1066. InputQueueSurrogate = 0;
  1067. }
  1068. InputQueueCharacters.push_back(cp);
  1069. }
  1070. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  1071. {
  1072. while (*utf8_chars != 0)
  1073. {
  1074. unsigned int c = 0;
  1075. utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
  1076. if (c != 0)
  1077. InputQueueCharacters.push_back((ImWchar)c);
  1078. }
  1079. }
  1080. void ImGuiIO::ClearInputCharacters()
  1081. {
  1082. InputQueueCharacters.resize(0);
  1083. }
  1084. //-----------------------------------------------------------------------------
  1085. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  1086. //-----------------------------------------------------------------------------
  1087. ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
  1088. {
  1089. IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
  1090. ImVec2 p_last = p1;
  1091. ImVec2 p_closest;
  1092. float p_closest_dist2 = FLT_MAX;
  1093. float t_step = 1.0f / (float)num_segments;
  1094. for (int i_step = 1; i_step <= num_segments; i_step++)
  1095. {
  1096. ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
  1097. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1098. float dist2 = ImLengthSqr(p - p_line);
  1099. if (dist2 < p_closest_dist2)
  1100. {
  1101. p_closest = p_line;
  1102. p_closest_dist2 = dist2;
  1103. }
  1104. p_last = p_current;
  1105. }
  1106. return p_closest;
  1107. }
  1108. // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
  1109. 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)
  1110. {
  1111. float dx = x4 - x1;
  1112. float dy = y4 - y1;
  1113. float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
  1114. float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
  1115. d2 = (d2 >= 0) ? d2 : -d2;
  1116. d3 = (d3 >= 0) ? d3 : -d3;
  1117. if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
  1118. {
  1119. ImVec2 p_current(x4, y4);
  1120. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1121. float dist2 = ImLengthSqr(p - p_line);
  1122. if (dist2 < p_closest_dist2)
  1123. {
  1124. p_closest = p_line;
  1125. p_closest_dist2 = dist2;
  1126. }
  1127. p_last = p_current;
  1128. }
  1129. else if (level < 10)
  1130. {
  1131. float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
  1132. float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
  1133. float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
  1134. float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
  1135. float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
  1136. float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
  1137. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
  1138. ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
  1139. }
  1140. }
  1141. // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
  1142. // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
  1143. ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
  1144. {
  1145. IM_ASSERT(tess_tol > 0.0f);
  1146. ImVec2 p_last = p1;
  1147. ImVec2 p_closest;
  1148. float p_closest_dist2 = FLT_MAX;
  1149. 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);
  1150. return p_closest;
  1151. }
  1152. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  1153. {
  1154. ImVec2 ap = p - a;
  1155. ImVec2 ab_dir = b - a;
  1156. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  1157. if (dot < 0.0f)
  1158. return a;
  1159. float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
  1160. if (dot > ab_len_sqr)
  1161. return b;
  1162. return a + ab_dir * dot / ab_len_sqr;
  1163. }
  1164. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1165. {
  1166. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  1167. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  1168. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  1169. return ((b1 == b2) && (b2 == b3));
  1170. }
  1171. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  1172. {
  1173. ImVec2 v0 = b - a;
  1174. ImVec2 v1 = c - a;
  1175. ImVec2 v2 = p - a;
  1176. const float denom = v0.x * v1.y - v1.x * v0.y;
  1177. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  1178. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  1179. out_u = 1.0f - out_v - out_w;
  1180. }
  1181. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1182. {
  1183. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  1184. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  1185. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  1186. float dist2_ab = ImLengthSqr(p - proj_ab);
  1187. float dist2_bc = ImLengthSqr(p - proj_bc);
  1188. float dist2_ca = ImLengthSqr(p - proj_ca);
  1189. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  1190. if (m == dist2_ab)
  1191. return proj_ab;
  1192. if (m == dist2_bc)
  1193. return proj_bc;
  1194. return proj_ca;
  1195. }
  1196. //-----------------------------------------------------------------------------
  1197. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  1198. //-----------------------------------------------------------------------------
  1199. // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
  1200. int ImStricmp(const char* str1, const char* str2)
  1201. {
  1202. int d;
  1203. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  1204. return d;
  1205. }
  1206. int ImStrnicmp(const char* str1, const char* str2, size_t count)
  1207. {
  1208. int d = 0;
  1209. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  1210. return d;
  1211. }
  1212. void ImStrncpy(char* dst, const char* src, size_t count)
  1213. {
  1214. if (count < 1)
  1215. return;
  1216. if (count > 1)
  1217. strncpy(dst, src, count - 1);
  1218. dst[count - 1] = 0;
  1219. }
  1220. char* ImStrdup(const char* str)
  1221. {
  1222. size_t len = strlen(str);
  1223. void* buf = IM_ALLOC(len + 1);
  1224. return (char*)memcpy(buf, (const void*)str, len + 1);
  1225. }
  1226. char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
  1227. {
  1228. size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
  1229. size_t src_size = strlen(src) + 1;
  1230. if (dst_buf_size < src_size)
  1231. {
  1232. IM_FREE(dst);
  1233. dst = (char*)IM_ALLOC(src_size);
  1234. if (p_dst_size)
  1235. *p_dst_size = src_size;
  1236. }
  1237. return (char*)memcpy(dst, (const void*)src, src_size);
  1238. }
  1239. const char* ImStrchrRange(const char* str, const char* str_end, char c)
  1240. {
  1241. const char* p = (const char*)memchr(str, (int)c, str_end - str);
  1242. return p;
  1243. }
  1244. int ImStrlenW(const ImWchar* str)
  1245. {
  1246. //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
  1247. int n = 0;
  1248. while (*str++) n++;
  1249. return n;
  1250. }
  1251. // Find end-of-line. Return pointer will point to either first \n, either str_end.
  1252. const char* ImStreolRange(const char* str, const char* str_end)
  1253. {
  1254. const char* p = (const char*)memchr(str, '\n', str_end - str);
  1255. return p ? p : str_end;
  1256. }
  1257. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  1258. {
  1259. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  1260. buf_mid_line--;
  1261. return buf_mid_line;
  1262. }
  1263. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  1264. {
  1265. if (!needle_end)
  1266. needle_end = needle + strlen(needle);
  1267. const char un0 = (char)toupper(*needle);
  1268. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  1269. {
  1270. if (toupper(*haystack) == un0)
  1271. {
  1272. const char* b = needle + 1;
  1273. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  1274. if (toupper(*a) != toupper(*b))
  1275. break;
  1276. if (b == needle_end)
  1277. return haystack;
  1278. }
  1279. haystack++;
  1280. }
  1281. return NULL;
  1282. }
  1283. // 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.
  1284. void ImStrTrimBlanks(char* buf)
  1285. {
  1286. char* p = buf;
  1287. while (p[0] == ' ' || p[0] == '\t') // Leading blanks
  1288. p++;
  1289. char* p_start = p;
  1290. while (*p != 0) // Find end of string
  1291. p++;
  1292. while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
  1293. p--;
  1294. if (p_start != buf) // Copy memory if we had leading blanks
  1295. memmove(buf, p_start, p - p_start);
  1296. buf[p - p_start] = 0; // Zero terminate
  1297. }
  1298. const char* ImStrSkipBlank(const char* str)
  1299. {
  1300. while (str[0] == ' ' || str[0] == '\t')
  1301. str++;
  1302. return str;
  1303. }
  1304. // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  1305. // 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.
  1306. // B) When buf==NULL vsnprintf() will return the output size.
  1307. #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1308. // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
  1309. // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1310. // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
  1311. // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
  1312. #ifdef IMGUI_USE_STB_SPRINTF
  1313. #define STB_SPRINTF_IMPLEMENTATION
  1314. #include "stb_sprintf.h"
  1315. #endif
  1316. #if defined(_MSC_VER) && !defined(vsnprintf)
  1317. #define vsnprintf _vsnprintf
  1318. #endif
  1319. int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
  1320. {
  1321. va_list args;
  1322. va_start(args, fmt);
  1323. #ifdef IMGUI_USE_STB_SPRINTF
  1324. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1325. #else
  1326. int w = vsnprintf(buf, buf_size, fmt, args);
  1327. #endif
  1328. va_end(args);
  1329. if (buf == NULL)
  1330. return w;
  1331. if (w == -1 || w >= (int)buf_size)
  1332. w = (int)buf_size - 1;
  1333. buf[w] = 0;
  1334. return w;
  1335. }
  1336. int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
  1337. {
  1338. #ifdef IMGUI_USE_STB_SPRINTF
  1339. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1340. #else
  1341. int w = vsnprintf(buf, buf_size, fmt, args);
  1342. #endif
  1343. if (buf == NULL)
  1344. return w;
  1345. if (w == -1 || w >= (int)buf_size)
  1346. w = (int)buf_size - 1;
  1347. buf[w] = 0;
  1348. return w;
  1349. }
  1350. #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1351. // CRC32 needs a 1KB lookup table (not cache friendly)
  1352. // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
  1353. // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
  1354. static const ImU32 GCrc32LookupTable[256] =
  1355. {
  1356. 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
  1357. 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
  1358. 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
  1359. 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
  1360. 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
  1361. 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
  1362. 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
  1363. 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
  1364. 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
  1365. 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
  1366. 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
  1367. 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
  1368. 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
  1369. 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
  1370. 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
  1371. 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
  1372. };
  1373. // Known size hash
  1374. // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
  1375. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1376. ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
  1377. {
  1378. ImU32 crc = ~seed;
  1379. const unsigned char* data = (const unsigned char*)data_p;
  1380. const ImU32* crc32_lut = GCrc32LookupTable;
  1381. while (data_size-- != 0)
  1382. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
  1383. return ~crc;
  1384. }
  1385. // Zero-terminated string hash, with support for ### to reset back to seed value
  1386. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  1387. // Because this syntax is rarely used we are optimizing for the common case.
  1388. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  1389. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
  1390. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1391. ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
  1392. {
  1393. seed = ~seed;
  1394. ImU32 crc = seed;
  1395. const unsigned char* data = (const unsigned char*)data_p;
  1396. const ImU32* crc32_lut = GCrc32LookupTable;
  1397. if (data_size != 0)
  1398. {
  1399. while (data_size-- != 0)
  1400. {
  1401. unsigned char c = *data++;
  1402. if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
  1403. crc = seed;
  1404. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1405. }
  1406. }
  1407. else
  1408. {
  1409. while (unsigned char c = *data++)
  1410. {
  1411. if (c == '#' && data[0] == '#' && data[1] == '#')
  1412. crc = seed;
  1413. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1414. }
  1415. }
  1416. return ~crc;
  1417. }
  1418. //-----------------------------------------------------------------------------
  1419. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  1420. //-----------------------------------------------------------------------------
  1421. // Default file functions
  1422. #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1423. ImFileHandle ImFileOpen(const char* filename, const char* mode)
  1424. {
  1425. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
  1426. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
  1427. // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
  1428. const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
  1429. const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
  1430. ImVector<ImWchar> buf;
  1431. buf.resize(filename_wsize + mode_wsize);
  1432. ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
  1433. ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
  1434. return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
  1435. #else
  1436. return fopen(filename, mode);
  1437. #endif
  1438. }
  1439. // 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.
  1440. bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
  1441. 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; }
  1442. ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
  1443. ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
  1444. #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1445. // Helper: Load file content into memory
  1446. // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
  1447. // This can't really be used with "rt" because fseek size won't match read size.
  1448. void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
  1449. {
  1450. IM_ASSERT(filename && mode);
  1451. if (out_file_size)
  1452. *out_file_size = 0;
  1453. ImFileHandle f;
  1454. if ((f = ImFileOpen(filename, mode)) == NULL)
  1455. return NULL;
  1456. size_t file_size = (size_t)ImFileGetSize(f);
  1457. if (file_size == (size_t)-1)
  1458. {
  1459. ImFileClose(f);
  1460. return NULL;
  1461. }
  1462. void* file_data = IM_ALLOC(file_size + padding_bytes);
  1463. if (file_data == NULL)
  1464. {
  1465. ImFileClose(f);
  1466. return NULL;
  1467. }
  1468. if (ImFileRead(file_data, 1, file_size, f) != file_size)
  1469. {
  1470. ImFileClose(f);
  1471. IM_FREE(file_data);
  1472. return NULL;
  1473. }
  1474. if (padding_bytes > 0)
  1475. memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
  1476. ImFileClose(f);
  1477. if (out_file_size)
  1478. *out_file_size = file_size;
  1479. return file_data;
  1480. }
  1481. //-----------------------------------------------------------------------------
  1482. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  1483. //-----------------------------------------------------------------------------
  1484. // Convert UTF-8 to 32-bit character, process single character input.
  1485. // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
  1486. // We handle UTF-8 decoding error by skipping forward.
  1487. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1488. {
  1489. 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 };
  1490. static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
  1491. static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
  1492. static const int shiftc[] = { 0, 18, 12, 6, 0 };
  1493. static const int shifte[] = { 0, 6, 4, 2, 0 };
  1494. int len = lengths[*(const unsigned char*)in_text >> 3];
  1495. int wanted = len + !len;
  1496. if (in_text_end == NULL)
  1497. in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
  1498. // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
  1499. // so it is fast even with excessive branching.
  1500. unsigned char s[4];
  1501. s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
  1502. s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
  1503. s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
  1504. s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
  1505. // Assume a four-byte character and load four bytes. Unused bits are shifted out.
  1506. *out_char = (uint32_t)(s[0] & masks[len]) << 18;
  1507. *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
  1508. *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
  1509. *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
  1510. *out_char >>= shiftc[len];
  1511. // Accumulate the various error conditions.
  1512. int e = 0;
  1513. e = (*out_char < mins[len]) << 6; // non-canonical encoding
  1514. e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
  1515. e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
  1516. e |= (s[1] & 0xc0) >> 2;
  1517. e |= (s[2] & 0xc0) >> 4;
  1518. e |= (s[3] ) >> 6;
  1519. e ^= 0x2a; // top two bits of each tail byte correct?
  1520. e >>= shifte[len];
  1521. if (e)
  1522. {
  1523. // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
  1524. // One byte is consumed in case of invalid first byte of in_text.
  1525. // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
  1526. // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
  1527. wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
  1528. *out_char = IM_UNICODE_CODEPOINT_INVALID;
  1529. }
  1530. return wanted;
  1531. }
  1532. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1533. {
  1534. ImWchar* buf_out = buf;
  1535. ImWchar* buf_end = buf + buf_size;
  1536. while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1537. {
  1538. unsigned int c;
  1539. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1540. if (c == 0)
  1541. break;
  1542. *buf_out++ = (ImWchar)c;
  1543. }
  1544. *buf_out = 0;
  1545. if (in_text_remaining)
  1546. *in_text_remaining = in_text;
  1547. return (int)(buf_out - buf);
  1548. }
  1549. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1550. {
  1551. int char_count = 0;
  1552. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1553. {
  1554. unsigned int c;
  1555. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1556. if (c == 0)
  1557. break;
  1558. char_count++;
  1559. }
  1560. return char_count;
  1561. }
  1562. // Based on stb_to_utf8() from github.com/nothings/stb/
  1563. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  1564. {
  1565. if (c < 0x80)
  1566. {
  1567. buf[0] = (char)c;
  1568. return 1;
  1569. }
  1570. if (c < 0x800)
  1571. {
  1572. if (buf_size < 2) return 0;
  1573. buf[0] = (char)(0xc0 + (c >> 6));
  1574. buf[1] = (char)(0x80 + (c & 0x3f));
  1575. return 2;
  1576. }
  1577. if (c < 0x10000)
  1578. {
  1579. if (buf_size < 3) return 0;
  1580. buf[0] = (char)(0xe0 + (c >> 12));
  1581. buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
  1582. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1583. return 3;
  1584. }
  1585. if (c <= 0x10FFFF)
  1586. {
  1587. if (buf_size < 4) return 0;
  1588. buf[0] = (char)(0xf0 + (c >> 18));
  1589. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1590. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1591. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1592. return 4;
  1593. }
  1594. // Invalid code point, the max unicode is 0x10FFFF
  1595. return 0;
  1596. }
  1597. // Not optimal but we very rarely use this function.
  1598. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
  1599. {
  1600. unsigned int unused = 0;
  1601. return ImTextCharFromUtf8(&unused, in_text, in_text_end);
  1602. }
  1603. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1604. {
  1605. if (c < 0x80) return 1;
  1606. if (c < 0x800) return 2;
  1607. if (c < 0x10000) return 3;
  1608. if (c <= 0x10FFFF) return 4;
  1609. return 3;
  1610. }
  1611. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1612. {
  1613. char* buf_out = buf;
  1614. const char* buf_end = buf + buf_size;
  1615. while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1616. {
  1617. unsigned int c = (unsigned int)(*in_text++);
  1618. if (c < 0x80)
  1619. *buf_out++ = (char)c;
  1620. else
  1621. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c);
  1622. }
  1623. *buf_out = 0;
  1624. return (int)(buf_out - buf);
  1625. }
  1626. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1627. {
  1628. int bytes_count = 0;
  1629. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1630. {
  1631. unsigned int c = (unsigned int)(*in_text++);
  1632. if (c < 0x80)
  1633. bytes_count++;
  1634. else
  1635. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1636. }
  1637. return bytes_count;
  1638. }
  1639. //-----------------------------------------------------------------------------
  1640. // [SECTION] MISC HELPERS/UTILITIES (Color functions)
  1641. // Note: The Convert functions are early design which are not consistent with other API.
  1642. //-----------------------------------------------------------------------------
  1643. IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
  1644. {
  1645. float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
  1646. int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
  1647. int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
  1648. int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
  1649. return IM_COL32(r, g, b, 0xFF);
  1650. }
  1651. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1652. {
  1653. float s = 1.0f / 255.0f;
  1654. return ImVec4(
  1655. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1656. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1657. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1658. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1659. }
  1660. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1661. {
  1662. ImU32 out;
  1663. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1664. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1665. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1666. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1667. return out;
  1668. }
  1669. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1670. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1671. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1672. {
  1673. float K = 0.f;
  1674. if (g < b)
  1675. {
  1676. ImSwap(g, b);
  1677. K = -1.f;
  1678. }
  1679. if (r < g)
  1680. {
  1681. ImSwap(r, g);
  1682. K = -2.f / 6.f - K;
  1683. }
  1684. const float chroma = r - (g < b ? g : b);
  1685. out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
  1686. out_s = chroma / (r + 1e-20f);
  1687. out_v = r;
  1688. }
  1689. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1690. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1691. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1692. {
  1693. if (s == 0.0f)
  1694. {
  1695. // gray
  1696. out_r = out_g = out_b = v;
  1697. return;
  1698. }
  1699. h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
  1700. int i = (int)h;
  1701. float f = h - (float)i;
  1702. float p = v * (1.0f - s);
  1703. float q = v * (1.0f - s * f);
  1704. float t = v * (1.0f - s * (1.0f - f));
  1705. switch (i)
  1706. {
  1707. case 0: out_r = v; out_g = t; out_b = p; break;
  1708. case 1: out_r = q; out_g = v; out_b = p; break;
  1709. case 2: out_r = p; out_g = v; out_b = t; break;
  1710. case 3: out_r = p; out_g = q; out_b = v; break;
  1711. case 4: out_r = t; out_g = p; out_b = v; break;
  1712. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1713. }
  1714. }
  1715. //-----------------------------------------------------------------------------
  1716. // [SECTION] ImGuiStorage
  1717. // Helper: Key->value storage
  1718. //-----------------------------------------------------------------------------
  1719. // std::lower_bound but without the bullshit
  1720. static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
  1721. {
  1722. ImGuiStorage::ImGuiStoragePair* first = data.Data;
  1723. ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
  1724. size_t count = (size_t)(last - first);
  1725. while (count > 0)
  1726. {
  1727. size_t count2 = count >> 1;
  1728. ImGuiStorage::ImGuiStoragePair* mid = first + count2;
  1729. if (mid->key < key)
  1730. {
  1731. first = ++mid;
  1732. count -= count2 + 1;
  1733. }
  1734. else
  1735. {
  1736. count = count2;
  1737. }
  1738. }
  1739. return first;
  1740. }
  1741. // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
  1742. void ImGuiStorage::BuildSortByKey()
  1743. {
  1744. struct StaticFunc
  1745. {
  1746. static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
  1747. {
  1748. // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
  1749. if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
  1750. if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
  1751. return 0;
  1752. }
  1753. };
  1754. if (Data.Size > 1)
  1755. ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
  1756. }
  1757. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1758. {
  1759. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1760. if (it == Data.end() || it->key != key)
  1761. return default_val;
  1762. return it->val_i;
  1763. }
  1764. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1765. {
  1766. return GetInt(key, default_val ? 1 : 0) != 0;
  1767. }
  1768. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1769. {
  1770. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1771. if (it == Data.end() || it->key != key)
  1772. return default_val;
  1773. return it->val_f;
  1774. }
  1775. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1776. {
  1777. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1778. if (it == Data.end() || it->key != key)
  1779. return NULL;
  1780. return it->val_p;
  1781. }
  1782. // 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.
  1783. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1784. {
  1785. ImGuiStoragePair* it = LowerBound(Data, key);
  1786. if (it == Data.end() || it->key != key)
  1787. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1788. return &it->val_i;
  1789. }
  1790. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1791. {
  1792. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1793. }
  1794. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1795. {
  1796. ImGuiStoragePair* it = LowerBound(Data, key);
  1797. if (it == Data.end() || it->key != key)
  1798. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1799. return &it->val_f;
  1800. }
  1801. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1802. {
  1803. ImGuiStoragePair* it = LowerBound(Data, key);
  1804. if (it == Data.end() || it->key != key)
  1805. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1806. return &it->val_p;
  1807. }
  1808. // 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)
  1809. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1810. {
  1811. ImGuiStoragePair* it = LowerBound(Data, key);
  1812. if (it == Data.end() || it->key != key)
  1813. {
  1814. Data.insert(it, ImGuiStoragePair(key, val));
  1815. return;
  1816. }
  1817. it->val_i = val;
  1818. }
  1819. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1820. {
  1821. SetInt(key, val ? 1 : 0);
  1822. }
  1823. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1824. {
  1825. ImGuiStoragePair* it = LowerBound(Data, key);
  1826. if (it == Data.end() || it->key != key)
  1827. {
  1828. Data.insert(it, ImGuiStoragePair(key, val));
  1829. return;
  1830. }
  1831. it->val_f = val;
  1832. }
  1833. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1834. {
  1835. ImGuiStoragePair* it = LowerBound(Data, key);
  1836. if (it == Data.end() || it->key != key)
  1837. {
  1838. Data.insert(it, ImGuiStoragePair(key, val));
  1839. return;
  1840. }
  1841. it->val_p = val;
  1842. }
  1843. void ImGuiStorage::SetAllInt(int v)
  1844. {
  1845. for (int i = 0; i < Data.Size; i++)
  1846. Data[i].val_i = v;
  1847. }
  1848. //-----------------------------------------------------------------------------
  1849. // [SECTION] ImGuiTextFilter
  1850. //-----------------------------------------------------------------------------
  1851. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1852. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1853. {
  1854. if (default_filter)
  1855. {
  1856. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1857. Build();
  1858. }
  1859. else
  1860. {
  1861. InputBuf[0] = 0;
  1862. CountGrep = 0;
  1863. }
  1864. }
  1865. bool ImGuiTextFilter::Draw(const char* label, float width)
  1866. {
  1867. if (width != 0.0f)
  1868. ImGui::SetNextItemWidth(width);
  1869. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1870. if (value_changed)
  1871. Build();
  1872. return value_changed;
  1873. }
  1874. void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
  1875. {
  1876. out->resize(0);
  1877. const char* wb = b;
  1878. const char* we = wb;
  1879. while (we < e)
  1880. {
  1881. if (*we == separator)
  1882. {
  1883. out->push_back(ImGuiTextRange(wb, we));
  1884. wb = we + 1;
  1885. }
  1886. we++;
  1887. }
  1888. if (wb != we)
  1889. out->push_back(ImGuiTextRange(wb, we));
  1890. }
  1891. void ImGuiTextFilter::Build()
  1892. {
  1893. Filters.resize(0);
  1894. ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
  1895. input_range.split(',', &Filters);
  1896. CountGrep = 0;
  1897. for (int i = 0; i != Filters.Size; i++)
  1898. {
  1899. ImGuiTextRange& f = Filters[i];
  1900. while (f.b < f.e && ImCharIsBlankA(f.b[0]))
  1901. f.b++;
  1902. while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
  1903. f.e--;
  1904. if (f.empty())
  1905. continue;
  1906. if (Filters[i].b[0] != '-')
  1907. CountGrep += 1;
  1908. }
  1909. }
  1910. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1911. {
  1912. if (Filters.empty())
  1913. return true;
  1914. if (text == NULL)
  1915. text = "";
  1916. for (int i = 0; i != Filters.Size; i++)
  1917. {
  1918. const ImGuiTextRange& f = Filters[i];
  1919. if (f.empty())
  1920. continue;
  1921. if (f.b[0] == '-')
  1922. {
  1923. // Subtract
  1924. if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
  1925. return false;
  1926. }
  1927. else
  1928. {
  1929. // Grep
  1930. if (ImStristr(text, text_end, f.b, f.e) != NULL)
  1931. return true;
  1932. }
  1933. }
  1934. // Implicit * grep
  1935. if (CountGrep == 0)
  1936. return true;
  1937. return false;
  1938. }
  1939. //-----------------------------------------------------------------------------
  1940. // [SECTION] ImGuiTextBuffer
  1941. //-----------------------------------------------------------------------------
  1942. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1943. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1944. #ifndef va_copy
  1945. #if defined(__GNUC__) || defined(__clang__)
  1946. #define va_copy(dest, src) __builtin_va_copy(dest, src)
  1947. #else
  1948. #define va_copy(dest, src) (dest = src)
  1949. #endif
  1950. #endif
  1951. char ImGuiTextBuffer::EmptyString[1] = { 0 };
  1952. void ImGuiTextBuffer::append(const char* str, const char* str_end)
  1953. {
  1954. int len = str_end ? (int)(str_end - str) : (int)strlen(str);
  1955. // Add zero-terminator the first time
  1956. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  1957. const int needed_sz = write_off + len;
  1958. if (write_off + len >= Buf.Capacity)
  1959. {
  1960. int new_capacity = Buf.Capacity * 2;
  1961. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  1962. }
  1963. Buf.resize(needed_sz);
  1964. memcpy(&Buf[write_off - 1], str, (size_t)len);
  1965. Buf[write_off - 1 + len] = 0;
  1966. }
  1967. void ImGuiTextBuffer::appendf(const char* fmt, ...)
  1968. {
  1969. va_list args;
  1970. va_start(args, fmt);
  1971. appendfv(fmt, args);
  1972. va_end(args);
  1973. }
  1974. // Helper: Text buffer for logging/accumulating text
  1975. void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
  1976. {
  1977. va_list args_copy;
  1978. va_copy(args_copy, args);
  1979. int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1980. if (len <= 0)
  1981. {
  1982. va_end(args_copy);
  1983. return;
  1984. }
  1985. // Add zero-terminator the first time
  1986. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  1987. const int needed_sz = write_off + len;
  1988. if (write_off + len >= Buf.Capacity)
  1989. {
  1990. int new_capacity = Buf.Capacity * 2;
  1991. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  1992. }
  1993. Buf.resize(needed_sz);
  1994. ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
  1995. va_end(args_copy);
  1996. }
  1997. //-----------------------------------------------------------------------------
  1998. // [SECTION] ImGuiListClipper
  1999. // This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
  2000. // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
  2001. //-----------------------------------------------------------------------------
  2002. // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
  2003. // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
  2004. static bool GetSkipItemForListClipping()
  2005. {
  2006. ImGuiContext& g = *GImGui;
  2007. return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
  2008. }
  2009. // Helper to calculate coarse clipping of large list of evenly sized items.
  2010. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
  2011. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  2012. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  2013. {
  2014. ImGuiContext& g = *GImGui;
  2015. ImGuiWindow* window = g.CurrentWindow;
  2016. if (g.LogEnabled)
  2017. {
  2018. // If logging is active, do not perform any clipping
  2019. *out_items_display_start = 0;
  2020. *out_items_display_end = items_count;
  2021. return;
  2022. }
  2023. if (GetSkipItemForListClipping())
  2024. {
  2025. *out_items_display_start = *out_items_display_end = 0;
  2026. return;
  2027. }
  2028. // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
  2029. ImRect unclipped_rect = window->ClipRect;
  2030. if (g.NavMoveRequest)
  2031. unclipped_rect.Add(g.NavScoringRect);
  2032. if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
  2033. unclipped_rect.Add(ImRect(window->Pos + window->NavRectRel[0].Min, window->Pos + window->NavRectRel[0].Max));
  2034. const ImVec2 pos = window->DC.CursorPos;
  2035. int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
  2036. int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
  2037. // When performing a navigation request, ensure we have one item extra in the direction we are moving to
  2038. if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
  2039. start--;
  2040. if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
  2041. end++;
  2042. start = ImClamp(start, 0, items_count);
  2043. end = ImClamp(end + 1, start, items_count);
  2044. *out_items_display_start = start;
  2045. *out_items_display_end = end;
  2046. }
  2047. static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height)
  2048. {
  2049. // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
  2050. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
  2051. // The clipper should probably have a 4th step to display the last item in a regular manner.
  2052. ImGuiContext& g = *GImGui;
  2053. ImGuiWindow* window = g.CurrentWindow;
  2054. float off_y = pos_y - window->DC.CursorPos.y;
  2055. window->DC.CursorPos.y = pos_y;
  2056. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
  2057. 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.
  2058. 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.
  2059. if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
  2060. columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  2061. if (ImGuiTable* table = g.CurrentTable)
  2062. {
  2063. if (table->IsInsideRow)
  2064. ImGui::TableEndRow(table);
  2065. table->RowPosY2 = window->DC.CursorPos.y;
  2066. const int row_increase = (int)((off_y / line_height) + 0.5f);
  2067. //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
  2068. table->RowBgColorCounter += row_increase;
  2069. }
  2070. }
  2071. ImGuiListClipper::ImGuiListClipper()
  2072. {
  2073. memset(this, 0, sizeof(*this));
  2074. ItemsCount = -1;
  2075. }
  2076. ImGuiListClipper::~ImGuiListClipper()
  2077. {
  2078. IM_ASSERT(ItemsCount == -1 && "Forgot to call End(), or to Step() until false?");
  2079. }
  2080. // Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1
  2081. // Use case B: Begin() called from constructor with items_height>0
  2082. // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
  2083. void ImGuiListClipper::Begin(int items_count, float items_height)
  2084. {
  2085. ImGuiContext& g = *GImGui;
  2086. ImGuiWindow* window = g.CurrentWindow;
  2087. if (ImGuiTable* table = g.CurrentTable)
  2088. if (table->IsInsideRow)
  2089. ImGui::TableEndRow(table);
  2090. StartPosY = window->DC.CursorPos.y;
  2091. ItemsHeight = items_height;
  2092. ItemsCount = items_count;
  2093. ItemsFrozen = 0;
  2094. StepNo = 0;
  2095. DisplayStart = -1;
  2096. DisplayEnd = 0;
  2097. }
  2098. void ImGuiListClipper::End()
  2099. {
  2100. if (ItemsCount < 0) // Already ended
  2101. return;
  2102. // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
  2103. if (ItemsCount < INT_MAX && DisplayStart >= 0)
  2104. SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight);
  2105. ItemsCount = -1;
  2106. StepNo = 3;
  2107. }
  2108. bool ImGuiListClipper::Step()
  2109. {
  2110. ImGuiContext& g = *GImGui;
  2111. ImGuiWindow* window = g.CurrentWindow;
  2112. ImGuiTable* table = g.CurrentTable;
  2113. if (table && table->IsInsideRow)
  2114. ImGui::TableEndRow(table);
  2115. // No items
  2116. if (ItemsCount == 0 || GetSkipItemForListClipping())
  2117. {
  2118. End();
  2119. return false;
  2120. }
  2121. // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
  2122. if (StepNo == 0)
  2123. {
  2124. // While we are in frozen row state, keep displaying items one by one, unclipped
  2125. // FIXME: Could be stored as a table-agnostic state.
  2126. if (table != NULL && !table->IsUnfrozenRows)
  2127. {
  2128. DisplayStart = ItemsFrozen;
  2129. DisplayEnd = ItemsFrozen + 1;
  2130. ItemsFrozen++;
  2131. return true;
  2132. }
  2133. StartPosY = window->DC.CursorPos.y;
  2134. if (ItemsHeight <= 0.0f)
  2135. {
  2136. // Submit the first item so we can measure its height (generally it is 0..1)
  2137. DisplayStart = ItemsFrozen;
  2138. DisplayEnd = ItemsFrozen + 1;
  2139. StepNo = 1;
  2140. return true;
  2141. }
  2142. // Already has item height (given by user in Begin): skip to calculating step
  2143. DisplayStart = DisplayEnd;
  2144. StepNo = 2;
  2145. }
  2146. // Step 1: the clipper infer height from first element
  2147. if (StepNo == 1)
  2148. {
  2149. IM_ASSERT(ItemsHeight <= 0.0f);
  2150. if (table)
  2151. {
  2152. const float pos_y1 = table->RowPosY1; // Using this instead of StartPosY to handle clipper straddling the frozen row
  2153. const float pos_y2 = table->RowPosY2; // Using this instead of CursorPos.y to take account of tallest cell.
  2154. ItemsHeight = pos_y2 - pos_y1;
  2155. window->DC.CursorPos.y = pos_y2;
  2156. }
  2157. else
  2158. {
  2159. ItemsHeight = window->DC.CursorPos.y - StartPosY;
  2160. }
  2161. IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
  2162. StepNo = 2;
  2163. }
  2164. // Reached end of list
  2165. if (DisplayEnd >= ItemsCount)
  2166. {
  2167. End();
  2168. return false;
  2169. }
  2170. // Step 2: calculate the actual range of elements to display, and position the cursor before the first element
  2171. if (StepNo == 2)
  2172. {
  2173. IM_ASSERT(ItemsHeight > 0.0f);
  2174. int already_submitted = DisplayEnd;
  2175. ImGui::CalcListClipping(ItemsCount - already_submitted, ItemsHeight, &DisplayStart, &DisplayEnd);
  2176. DisplayStart += already_submitted;
  2177. DisplayEnd += already_submitted;
  2178. // Seek cursor
  2179. if (DisplayStart > already_submitted)
  2180. SetCursorPosYAndSetupForPrevLine(StartPosY + (DisplayStart - ItemsFrozen) * ItemsHeight, ItemsHeight);
  2181. StepNo = 3;
  2182. return true;
  2183. }
  2184. // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
  2185. // Advance the cursor to the end of the list and then returns 'false' to end the loop.
  2186. if (StepNo == 3)
  2187. {
  2188. // Seek cursor
  2189. if (ItemsCount < INT_MAX)
  2190. SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight); // advance cursor
  2191. ItemsCount = -1;
  2192. return false;
  2193. }
  2194. IM_ASSERT(0);
  2195. return false;
  2196. }
  2197. //-----------------------------------------------------------------------------
  2198. // [SECTION] STYLING
  2199. //-----------------------------------------------------------------------------
  2200. ImGuiStyle& ImGui::GetStyle()
  2201. {
  2202. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  2203. return GImGui->Style;
  2204. }
  2205. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  2206. {
  2207. ImGuiStyle& style = GImGui->Style;
  2208. ImVec4 c = style.Colors[idx];
  2209. c.w *= style.Alpha * alpha_mul;
  2210. return ColorConvertFloat4ToU32(c);
  2211. }
  2212. ImU32 ImGui::GetColorU32(const ImVec4& col)
  2213. {
  2214. ImGuiStyle& style = GImGui->Style;
  2215. ImVec4 c = col;
  2216. c.w *= style.Alpha;
  2217. return ColorConvertFloat4ToU32(c);
  2218. }
  2219. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  2220. {
  2221. ImGuiStyle& style = GImGui->Style;
  2222. return style.Colors[idx];
  2223. }
  2224. ImU32 ImGui::GetColorU32(ImU32 col)
  2225. {
  2226. ImGuiStyle& style = GImGui->Style;
  2227. if (style.Alpha >= 1.0f)
  2228. return col;
  2229. ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  2230. a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  2231. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  2232. }
  2233. // 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
  2234. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  2235. {
  2236. ImGuiContext& g = *GImGui;
  2237. ImGuiColorMod backup;
  2238. backup.Col = idx;
  2239. backup.BackupValue = g.Style.Colors[idx];
  2240. g.ColorStack.push_back(backup);
  2241. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  2242. }
  2243. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  2244. {
  2245. ImGuiContext& g = *GImGui;
  2246. ImGuiColorMod backup;
  2247. backup.Col = idx;
  2248. backup.BackupValue = g.Style.Colors[idx];
  2249. g.ColorStack.push_back(backup);
  2250. g.Style.Colors[idx] = col;
  2251. }
  2252. void ImGui::PopStyleColor(int count)
  2253. {
  2254. ImGuiContext& g = *GImGui;
  2255. while (count > 0)
  2256. {
  2257. ImGuiColorMod& backup = g.ColorStack.back();
  2258. g.Style.Colors[backup.Col] = backup.BackupValue;
  2259. g.ColorStack.pop_back();
  2260. count--;
  2261. }
  2262. }
  2263. struct ImGuiStyleVarInfo
  2264. {
  2265. ImGuiDataType Type;
  2266. ImU32 Count;
  2267. ImU32 Offset;
  2268. void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  2269. };
  2270. static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
  2271. {
  2272. ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
  2273. };
  2274. static const ImGuiStyleVarInfo GStyleVarInfo[] =
  2275. {
  2276. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  2277. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  2278. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  2279. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
  2280. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  2281. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
  2282. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
  2283. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
  2284. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
  2285. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
  2286. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  2287. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  2288. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
  2289. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  2290. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  2291. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  2292. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
  2293. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
  2294. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
  2295. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  2296. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
  2297. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
  2298. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  2299. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
  2300. };
  2301. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  2302. {
  2303. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
  2304. IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
  2305. return &GStyleVarInfo[idx];
  2306. }
  2307. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  2308. {
  2309. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2310. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
  2311. {
  2312. ImGuiContext& g = *GImGui;
  2313. float* pvar = (float*)var_info->GetVarPtr(&g.Style);
  2314. g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
  2315. *pvar = val;
  2316. return;
  2317. }
  2318. IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
  2319. }
  2320. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  2321. {
  2322. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2323. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
  2324. {
  2325. ImGuiContext& g = *GImGui;
  2326. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
  2327. g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
  2328. *pvar = val;
  2329. return;
  2330. }
  2331. IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
  2332. }
  2333. void ImGui::PopStyleVar(int count)
  2334. {
  2335. ImGuiContext& g = *GImGui;
  2336. while (count > 0)
  2337. {
  2338. // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
  2339. ImGuiStyleMod& backup = g.StyleVarStack.back();
  2340. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  2341. void* data = info->GetVarPtr(&g.Style);
  2342. if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
  2343. else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
  2344. g.StyleVarStack.pop_back();
  2345. count--;
  2346. }
  2347. }
  2348. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  2349. {
  2350. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  2351. switch (idx)
  2352. {
  2353. case ImGuiCol_Text: return "Text";
  2354. case ImGuiCol_TextDisabled: return "TextDisabled";
  2355. case ImGuiCol_WindowBg: return "WindowBg";
  2356. case ImGuiCol_ChildBg: return "ChildBg";
  2357. case ImGuiCol_PopupBg: return "PopupBg";
  2358. case ImGuiCol_Border: return "Border";
  2359. case ImGuiCol_BorderShadow: return "BorderShadow";
  2360. case ImGuiCol_FrameBg: return "FrameBg";
  2361. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  2362. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  2363. case ImGuiCol_TitleBg: return "TitleBg";
  2364. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  2365. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  2366. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  2367. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  2368. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  2369. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  2370. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  2371. case ImGuiCol_CheckMark: return "CheckMark";
  2372. case ImGuiCol_SliderGrab: return "SliderGrab";
  2373. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  2374. case ImGuiCol_Button: return "Button";
  2375. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  2376. case ImGuiCol_ButtonActive: return "ButtonActive";
  2377. case ImGuiCol_Header: return "Header";
  2378. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  2379. case ImGuiCol_HeaderActive: return "HeaderActive";
  2380. case ImGuiCol_Separator: return "Separator";
  2381. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  2382. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  2383. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  2384. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  2385. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  2386. case ImGuiCol_Tab: return "Tab";
  2387. case ImGuiCol_TabHovered: return "TabHovered";
  2388. case ImGuiCol_TabActive: return "TabActive";
  2389. case ImGuiCol_TabUnfocused: return "TabUnfocused";
  2390. case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
  2391. case ImGuiCol_DockingPreview: return "DockingPreview";
  2392. case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
  2393. case ImGuiCol_PlotLines: return "PlotLines";
  2394. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  2395. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  2396. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  2397. case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
  2398. case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
  2399. case ImGuiCol_TableBorderLight: return "TableBorderLight";
  2400. case ImGuiCol_TableRowBg: return "TableRowBg";
  2401. case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
  2402. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  2403. case ImGuiCol_DragDropTarget: return "DragDropTarget";
  2404. case ImGuiCol_NavHighlight: return "NavHighlight";
  2405. case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
  2406. case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
  2407. case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
  2408. }
  2409. IM_ASSERT(0);
  2410. return "Unknown";
  2411. }
  2412. //-----------------------------------------------------------------------------
  2413. // [SECTION] RENDER HELPERS
  2414. // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
  2415. // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
  2416. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
  2417. //-----------------------------------------------------------------------------
  2418. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  2419. {
  2420. const char* text_display_end = text;
  2421. if (!text_end)
  2422. text_end = (const char*)-1;
  2423. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2424. text_display_end++;
  2425. return text_display_end;
  2426. }
  2427. // Internal ImGui functions to render text
  2428. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  2429. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  2430. {
  2431. ImGuiContext& g = *GImGui;
  2432. ImGuiWindow* window = g.CurrentWindow;
  2433. // Hide anything after a '##' string
  2434. const char* text_display_end;
  2435. if (hide_text_after_hash)
  2436. {
  2437. text_display_end = FindRenderedTextEnd(text, text_end);
  2438. }
  2439. else
  2440. {
  2441. if (!text_end)
  2442. text_end = text + strlen(text); // FIXME-OPT
  2443. text_display_end = text_end;
  2444. }
  2445. if (text != text_display_end)
  2446. {
  2447. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  2448. if (g.LogEnabled)
  2449. LogRenderedText(&pos, text, text_display_end);
  2450. }
  2451. }
  2452. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  2453. {
  2454. ImGuiContext& g = *GImGui;
  2455. ImGuiWindow* window = g.CurrentWindow;
  2456. if (!text_end)
  2457. text_end = text + strlen(text); // FIXME-OPT
  2458. if (text != text_end)
  2459. {
  2460. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  2461. if (g.LogEnabled)
  2462. LogRenderedText(&pos, text, text_end);
  2463. }
  2464. }
  2465. // Default clip_rect uses (pos_min,pos_max)
  2466. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  2467. 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)
  2468. {
  2469. // Perform CPU side clipping for single clipped element to avoid using scissor state
  2470. ImVec2 pos = pos_min;
  2471. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  2472. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  2473. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  2474. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  2475. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  2476. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  2477. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  2478. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  2479. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  2480. // Render
  2481. if (need_clipping)
  2482. {
  2483. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  2484. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  2485. }
  2486. else
  2487. {
  2488. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2489. }
  2490. }
  2491. 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)
  2492. {
  2493. // Hide anything after a '##' string
  2494. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  2495. const int text_len = (int)(text_display_end - text);
  2496. if (text_len == 0)
  2497. return;
  2498. ImGuiContext& g = *GImGui;
  2499. ImGuiWindow* window = g.CurrentWindow;
  2500. RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
  2501. if (g.LogEnabled)
  2502. LogRenderedText(&pos_min, text, text_display_end);
  2503. }
  2504. // Another overly complex function until we reorganize everything into a nice all-in-one helper.
  2505. // 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.
  2506. // 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.
  2507. 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)
  2508. {
  2509. ImGuiContext& g = *GImGui;
  2510. if (text_end_full == NULL)
  2511. text_end_full = FindRenderedTextEnd(text);
  2512. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
  2513. //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));
  2514. //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));
  2515. //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
  2516. // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
  2517. if (text_size.x > pos_max.x - pos_min.x)
  2518. {
  2519. // Hello wo...
  2520. // | | |
  2521. // min max ellipsis_max
  2522. // <-> this is generally some padding value
  2523. const ImFont* font = draw_list->_Data->Font;
  2524. const float font_size = draw_list->_Data->FontSize;
  2525. const char* text_end_ellipsis = NULL;
  2526. ImWchar ellipsis_char = font->EllipsisChar;
  2527. int ellipsis_char_count = 1;
  2528. if (ellipsis_char == (ImWchar)-1)
  2529. {
  2530. ellipsis_char = (ImWchar)'.';
  2531. ellipsis_char_count = 3;
  2532. }
  2533. const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
  2534. float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
  2535. float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
  2536. if (ellipsis_char_count > 1)
  2537. {
  2538. // Full ellipsis size without free spacing after it.
  2539. const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
  2540. ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
  2541. ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
  2542. }
  2543. // We can now claim the space between pos_max.x and ellipsis_max.x
  2544. const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
  2545. float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
  2546. if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
  2547. {
  2548. // Always display at least 1 character if there's no room for character + ellipsis
  2549. text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
  2550. text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
  2551. }
  2552. while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
  2553. {
  2554. // 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)
  2555. text_end_ellipsis--;
  2556. 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
  2557. }
  2558. // Render text, render ellipsis
  2559. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
  2560. float ellipsis_x = pos_min.x + text_size_clipped_x;
  2561. if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
  2562. for (int i = 0; i < ellipsis_char_count; i++)
  2563. {
  2564. font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
  2565. ellipsis_x += ellipsis_glyph_width;
  2566. }
  2567. }
  2568. else
  2569. {
  2570. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
  2571. }
  2572. if (g.LogEnabled)
  2573. LogRenderedText(&pos_min, text, text_end_full);
  2574. }
  2575. // Render a rectangle shaped with optional rounding and borders
  2576. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2577. {
  2578. ImGuiContext& g = *GImGui;
  2579. ImGuiWindow* window = g.CurrentWindow;
  2580. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2581. const float border_size = g.Style.FrameBorderSize;
  2582. if (border && border_size > 0.0f)
  2583. {
  2584. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
  2585. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  2586. }
  2587. }
  2588. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  2589. {
  2590. ImGuiContext& g = *GImGui;
  2591. ImGuiWindow* window = g.CurrentWindow;
  2592. const float border_size = g.Style.FrameBorderSize;
  2593. if (border_size > 0.0f)
  2594. {
  2595. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
  2596. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  2597. }
  2598. }
  2599. void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
  2600. {
  2601. ImGuiContext& g = *GImGui;
  2602. if (id != g.NavId)
  2603. return;
  2604. if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
  2605. return;
  2606. ImGuiWindow* window = g.CurrentWindow;
  2607. if (window->DC.NavHideHighlightOneFrame)
  2608. return;
  2609. float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
  2610. ImRect display_rect = bb;
  2611. display_rect.ClipWith(window->ClipRect);
  2612. if (flags & ImGuiNavHighlightFlags_TypeDefault)
  2613. {
  2614. const float THICKNESS = 2.0f;
  2615. const float DISTANCE = 3.0f + THICKNESS * 0.5f;
  2616. display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
  2617. bool fully_visible = window->ClipRect.Contains(display_rect);
  2618. if (!fully_visible)
  2619. window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
  2620. 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);
  2621. if (!fully_visible)
  2622. window->DrawList->PopClipRect();
  2623. }
  2624. if (flags & ImGuiNavHighlightFlags_TypeThin)
  2625. {
  2626. window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
  2627. }
  2628. }
  2629. //-----------------------------------------------------------------------------
  2630. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  2631. //-----------------------------------------------------------------------------
  2632. // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
  2633. ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
  2634. {
  2635. memset(this, 0, sizeof(*this));
  2636. Name = ImStrdup(name);
  2637. NameBufLen = (int)strlen(name) + 1;
  2638. ID = ImHashStr(name);
  2639. IDStack.push_back(ID);
  2640. ViewportAllowPlatformMonitorExtend = -1;
  2641. ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
  2642. MoveId = GetID("#MOVE");
  2643. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  2644. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  2645. AutoFitFramesX = AutoFitFramesY = -1;
  2646. AutoPosLastDirection = ImGuiDir_None;
  2647. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  2648. SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
  2649. LastFrameActive = -1;
  2650. LastFrameJustFocused = -1;
  2651. LastTimeActive = -1.0f;
  2652. FontWindowScale = FontDpiScale = 1.0f;
  2653. SettingsOffset = -1;
  2654. DockOrder = -1;
  2655. DrawList = &DrawListInst;
  2656. DrawList->_Data = &context->DrawListSharedData;
  2657. DrawList->_OwnerName = Name;
  2658. }
  2659. ImGuiWindow::~ImGuiWindow()
  2660. {
  2661. IM_ASSERT(DrawList == &DrawListInst);
  2662. IM_DELETE(Name);
  2663. for (int i = 0; i != ColumnsStorage.Size; i++)
  2664. ColumnsStorage[i].~ImGuiOldColumns();
  2665. }
  2666. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  2667. {
  2668. ImGuiID seed = IDStack.back();
  2669. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  2670. ImGui::KeepAliveID(id);
  2671. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2672. ImGuiContext& g = *GImGui;
  2673. IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
  2674. #endif
  2675. return id;
  2676. }
  2677. ImGuiID ImGuiWindow::GetID(const void* ptr)
  2678. {
  2679. ImGuiID seed = IDStack.back();
  2680. ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
  2681. ImGui::KeepAliveID(id);
  2682. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2683. ImGuiContext& g = *GImGui;
  2684. IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
  2685. #endif
  2686. return id;
  2687. }
  2688. ImGuiID ImGuiWindow::GetID(int n)
  2689. {
  2690. ImGuiID seed = IDStack.back();
  2691. ImGuiID id = ImHashData(&n, sizeof(n), seed);
  2692. ImGui::KeepAliveID(id);
  2693. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2694. ImGuiContext& g = *GImGui;
  2695. IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
  2696. #endif
  2697. return id;
  2698. }
  2699. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  2700. {
  2701. ImGuiID seed = IDStack.back();
  2702. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  2703. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2704. ImGuiContext& g = *GImGui;
  2705. IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
  2706. #endif
  2707. return id;
  2708. }
  2709. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
  2710. {
  2711. ImGuiID seed = IDStack.back();
  2712. ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
  2713. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2714. ImGuiContext& g = *GImGui;
  2715. IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
  2716. #endif
  2717. return id;
  2718. }
  2719. ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
  2720. {
  2721. ImGuiID seed = IDStack.back();
  2722. ImGuiID id = ImHashData(&n, sizeof(n), seed);
  2723. #ifdef IMGUI_ENABLE_TEST_ENGINE
  2724. ImGuiContext& g = *GImGui;
  2725. IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
  2726. #endif
  2727. return id;
  2728. }
  2729. // This is only used in rare/specific situations to manufacture an ID out of nowhere.
  2730. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
  2731. {
  2732. ImGuiID seed = IDStack.back();
  2733. const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
  2734. ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
  2735. ImGui::KeepAliveID(id);
  2736. return id;
  2737. }
  2738. static void SetCurrentWindow(ImGuiWindow* window)
  2739. {
  2740. ImGuiContext& g = *GImGui;
  2741. g.CurrentWindow = window;
  2742. g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
  2743. if (window)
  2744. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  2745. }
  2746. void ImGui::GcCompactTransientMiscBuffers()
  2747. {
  2748. ImGuiContext& g = *GImGui;
  2749. g.ItemFlagsStack.clear();
  2750. g.GroupStack.clear();
  2751. TableGcCompactSettings();
  2752. }
  2753. // Free up/compact internal window buffers, we can use this when a window becomes unused.
  2754. // Not freed:
  2755. // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
  2756. // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
  2757. void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
  2758. {
  2759. window->MemoryCompacted = true;
  2760. window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
  2761. window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
  2762. window->IDStack.clear();
  2763. window->DrawList->_ClearFreeMemory();
  2764. window->DC.ChildWindows.clear();
  2765. window->DC.ItemWidthStack.clear();
  2766. window->DC.TextWrapPosStack.clear();
  2767. }
  2768. void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
  2769. {
  2770. // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
  2771. // The other buffers tends to amortize much faster.
  2772. window->MemoryCompacted = false;
  2773. window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
  2774. window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
  2775. window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
  2776. }
  2777. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  2778. {
  2779. ImGuiContext& g = *GImGui;
  2780. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  2781. if (g.ActiveIdIsJustActivated)
  2782. {
  2783. g.ActiveIdTimer = 0.0f;
  2784. g.ActiveIdHasBeenPressedBefore = false;
  2785. g.ActiveIdHasBeenEditedBefore = false;
  2786. g.ActiveIdMouseButton = -1;
  2787. if (id != 0)
  2788. {
  2789. g.LastActiveId = id;
  2790. g.LastActiveIdTimer = 0.0f;
  2791. }
  2792. }
  2793. g.ActiveId = id;
  2794. g.ActiveIdAllowOverlap = false;
  2795. g.ActiveIdNoClearOnFocusLoss = false;
  2796. g.ActiveIdWindow = window;
  2797. g.ActiveIdHasBeenEditedThisFrame = false;
  2798. if (id)
  2799. {
  2800. g.ActiveIdIsAlive = id;
  2801. g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
  2802. }
  2803. // Clear declaration of inputs claimed by the widget
  2804. // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
  2805. g.ActiveIdUsingMouseWheel = false;
  2806. g.ActiveIdUsingNavDirMask = 0x00;
  2807. g.ActiveIdUsingNavInputMask = 0x00;
  2808. g.ActiveIdUsingKeyInputMask = 0x00;
  2809. }
  2810. void ImGui::ClearActiveID()
  2811. {
  2812. SetActiveID(0, NULL); // g.ActiveId = 0;
  2813. }
  2814. void ImGui::SetHoveredID(ImGuiID id)
  2815. {
  2816. ImGuiContext& g = *GImGui;
  2817. g.HoveredId = id;
  2818. g.HoveredIdAllowOverlap = false;
  2819. g.HoveredIdUsingMouseWheel = false;
  2820. if (id != 0 && g.HoveredIdPreviousFrame != id)
  2821. g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
  2822. }
  2823. ImGuiID ImGui::GetHoveredID()
  2824. {
  2825. ImGuiContext& g = *GImGui;
  2826. return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
  2827. }
  2828. void ImGui::KeepAliveID(ImGuiID id)
  2829. {
  2830. ImGuiContext& g = *GImGui;
  2831. if (g.ActiveId == id)
  2832. g.ActiveIdIsAlive = id;
  2833. if (g.ActiveIdPreviousFrame == id)
  2834. g.ActiveIdPreviousFrameIsAlive = true;
  2835. }
  2836. void ImGui::MarkItemEdited(ImGuiID id)
  2837. {
  2838. // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
  2839. // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
  2840. ImGuiContext& g = *GImGui;
  2841. IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
  2842. IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
  2843. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
  2844. g.ActiveIdHasBeenEditedThisFrame = true;
  2845. g.ActiveIdHasBeenEditedBefore = true;
  2846. g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
  2847. }
  2848. static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
  2849. {
  2850. // An active popup disable hovering on other windows (apart from its own children)
  2851. // FIXME-OPT: This could be cached/stored within the window.
  2852. ImGuiContext& g = *GImGui;
  2853. if (g.NavWindow)
  2854. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
  2855. if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
  2856. {
  2857. // For the purpose of those flags we differentiate "standard popup" from "modal popup"
  2858. // NB: The order of those two tests is important because Modal windows are also Popups.
  2859. if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
  2860. return false;
  2861. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  2862. return false;
  2863. }
  2864. // Filter by viewport
  2865. if (window->Viewport != g.MouseViewport)
  2866. if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
  2867. return false;
  2868. return true;
  2869. }
  2870. // This is roughly matching the behavior of internal-facing ItemHoverable()
  2871. // - 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()
  2872. // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
  2873. bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
  2874. {
  2875. ImGuiContext& g = *GImGui;
  2876. ImGuiWindow* window = g.CurrentWindow;
  2877. if (g.NavDisableMouseHover && !g.NavDisableHighlight)
  2878. return IsItemFocused();
  2879. // Test for bounding box overlap, as updated as ItemAdd()
  2880. ImGuiItemStatusFlags status_flags = window->DC.LastItemStatusFlags;
  2881. if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
  2882. return false;
  2883. IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
  2884. // Test if we are hovering the right window (our window could be behind another window)
  2885. // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
  2886. // [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
  2887. // 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
  2888. // the test that has been running for a long while.
  2889. if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
  2890. if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
  2891. return false;
  2892. // Test if another item is active (e.g. being dragged)
  2893. if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
  2894. if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
  2895. return false;
  2896. // Test if interactions on this window are blocked by an active popup or modal.
  2897. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
  2898. if (!IsWindowContentHoverable(window, flags))
  2899. return false;
  2900. // Test if the item is disabled
  2901. if ((g.CurrentItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
  2902. return false;
  2903. // Special handling for calling after Begin() which represent the title bar or tab.
  2904. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
  2905. if ((window->DC.LastItemId == window->ID || window->DC.LastItemId == window->MoveId) && window->WriteAccessed)
  2906. return false;
  2907. return true;
  2908. }
  2909. // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
  2910. bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
  2911. {
  2912. ImGuiContext& g = *GImGui;
  2913. if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
  2914. return false;
  2915. ImGuiWindow* window = g.CurrentWindow;
  2916. if (g.HoveredWindow != window)
  2917. return false;
  2918. if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
  2919. return false;
  2920. if (!IsMouseHoveringRect(bb.Min, bb.Max))
  2921. return false;
  2922. if (g.NavDisableMouseHover)
  2923. return false;
  2924. if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None) || (g.CurrentItemFlags & ImGuiItemFlags_Disabled))
  2925. {
  2926. g.HoveredIdDisabled = true;
  2927. return false;
  2928. }
  2929. // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
  2930. // hover test in widgets code. We could also decide to split this function is two.
  2931. if (id != 0)
  2932. {
  2933. SetHoveredID(id);
  2934. // [DEBUG] Item Picker tool!
  2935. // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
  2936. // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
  2937. // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
  2938. // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
  2939. if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
  2940. GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
  2941. if (g.DebugItemPickerBreakId == id)
  2942. IM_DEBUG_BREAK();
  2943. }
  2944. return true;
  2945. }
  2946. bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
  2947. {
  2948. ImGuiContext& g = *GImGui;
  2949. ImGuiWindow* window = g.CurrentWindow;
  2950. if (!bb.Overlaps(window->ClipRect))
  2951. if (id == 0 || (id != g.ActiveId && id != g.NavId))
  2952. if (clip_even_when_logged || !g.LogEnabled)
  2953. return true;
  2954. return false;
  2955. }
  2956. // This is also inlined in ItemAdd()
  2957. // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
  2958. void ImGui::SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
  2959. {
  2960. window->DC.LastItemId = item_id;
  2961. window->DC.LastItemStatusFlags = item_flags;
  2962. window->DC.LastItemRect = item_rect;
  2963. }
  2964. // Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
  2965. void ImGui::ItemFocusable(ImGuiWindow* window, ImGuiID id)
  2966. {
  2967. ImGuiContext& g = *GImGui;
  2968. IM_ASSERT(id != 0 && id == window->DC.LastItemId);
  2969. // Increment counters
  2970. // FIXME: ImGuiItemFlags_Disabled should disable more.
  2971. const bool is_tab_stop = (g.CurrentItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
  2972. window->DC.FocusCounterRegular++;
  2973. if (is_tab_stop)
  2974. {
  2975. window->DC.FocusCounterTabStop++;
  2976. if (g.NavId == id)
  2977. g.NavIdTabCounter = window->DC.FocusCounterTabStop;
  2978. }
  2979. // Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
  2980. // (Note that we can always TAB out of a widget that doesn't allow tabbing in)
  2981. if (g.ActiveId == id && g.TabFocusPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.TabFocusRequestNextWindow == NULL)
  2982. {
  2983. g.TabFocusRequestNextWindow = window;
  2984. g.TabFocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
  2985. }
  2986. // Handle focus requests
  2987. if (g.TabFocusRequestCurrWindow == window)
  2988. {
  2989. if (window->DC.FocusCounterRegular == g.TabFocusRequestCurrCounterRegular)
  2990. {
  2991. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_FocusedByCode;
  2992. return;
  2993. }
  2994. if (is_tab_stop && window->DC.FocusCounterTabStop == g.TabFocusRequestCurrCounterTabStop)
  2995. {
  2996. g.NavJustTabbedId = id;
  2997. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_FocusedByTabbing;
  2998. return;
  2999. }
  3000. // If another item is about to be focused, we clear our own active id
  3001. if (g.ActiveId == id)
  3002. ClearActiveID();
  3003. }
  3004. }
  3005. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  3006. {
  3007. if (wrap_pos_x < 0.0f)
  3008. return 0.0f;
  3009. ImGuiContext& g = *GImGui;
  3010. ImGuiWindow* window = g.CurrentWindow;
  3011. if (wrap_pos_x == 0.0f)
  3012. {
  3013. // We could decide to setup a default wrapping max point for auto-resizing windows,
  3014. // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
  3015. //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
  3016. // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
  3017. //else
  3018. wrap_pos_x = window->WorkRect.Max.x;
  3019. }
  3020. else if (wrap_pos_x > 0.0f)
  3021. {
  3022. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  3023. }
  3024. return ImMax(wrap_pos_x - pos.x, 1.0f);
  3025. }
  3026. // IM_ALLOC() == ImGui::MemAlloc()
  3027. void* ImGui::MemAlloc(size_t size)
  3028. {
  3029. if (ImGuiContext* ctx = GImGui)
  3030. ctx->IO.MetricsActiveAllocations++;
  3031. return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
  3032. }
  3033. // IM_FREE() == ImGui::MemFree()
  3034. void ImGui::MemFree(void* ptr)
  3035. {
  3036. if (ptr)
  3037. if (ImGuiContext* ctx = GImGui)
  3038. ctx->IO.MetricsActiveAllocations--;
  3039. return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
  3040. }
  3041. const char* ImGui::GetClipboardText()
  3042. {
  3043. ImGuiContext& g = *GImGui;
  3044. return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
  3045. }
  3046. void ImGui::SetClipboardText(const char* text)
  3047. {
  3048. ImGuiContext& g = *GImGui;
  3049. if (g.IO.SetClipboardTextFn)
  3050. g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
  3051. }
  3052. const char* ImGui::GetVersion()
  3053. {
  3054. return IMGUI_VERSION;
  3055. }
  3056. // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
  3057. // 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
  3058. ImGuiContext* ImGui::GetCurrentContext()
  3059. {
  3060. return GImGui;
  3061. }
  3062. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  3063. {
  3064. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  3065. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  3066. #else
  3067. GImGui = ctx;
  3068. #endif
  3069. }
  3070. void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
  3071. {
  3072. GImAllocatorAllocFunc = alloc_func;
  3073. GImAllocatorFreeFunc = free_func;
  3074. GImAllocatorUserData = user_data;
  3075. }
  3076. // This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
  3077. void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
  3078. {
  3079. *p_alloc_func = GImAllocatorAllocFunc;
  3080. *p_free_func = GImAllocatorFreeFunc;
  3081. *p_user_data = GImAllocatorUserData;
  3082. }
  3083. ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
  3084. {
  3085. ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
  3086. if (GImGui == NULL)
  3087. SetCurrentContext(ctx);
  3088. Initialize(ctx);
  3089. return ctx;
  3090. }
  3091. void ImGui::DestroyContext(ImGuiContext* ctx)
  3092. {
  3093. if (ctx == NULL)
  3094. ctx = GImGui;
  3095. Shutdown(ctx);
  3096. if (GImGui == ctx)
  3097. SetCurrentContext(NULL);
  3098. IM_DELETE(ctx);
  3099. }
  3100. // No specific ordering/dependency support, will see as needed
  3101. ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
  3102. {
  3103. ImGuiContext& g = *ctx;
  3104. IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
  3105. g.Hooks.push_back(*hook);
  3106. g.Hooks.back().HookId = ++g.HookIdNext;
  3107. return g.HookIdNext;
  3108. }
  3109. // Deferred removal, avoiding issue with changing vector while iterating it
  3110. void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
  3111. {
  3112. ImGuiContext& g = *ctx;
  3113. IM_ASSERT(hook_id != 0);
  3114. for (int n = 0; n < g.Hooks.Size; n++)
  3115. if (g.Hooks[n].HookId == hook_id)
  3116. g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
  3117. }
  3118. // Call context hooks (used by e.g. test engine)
  3119. // We assume a small number of hooks so all stored in same array
  3120. void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
  3121. {
  3122. ImGuiContext& g = *ctx;
  3123. for (int n = 0; n < g.Hooks.Size; n++)
  3124. if (g.Hooks[n].Type == hook_type)
  3125. g.Hooks[n].Callback(&g, &g.Hooks[n]);
  3126. }
  3127. ImGuiIO& ImGui::GetIO()
  3128. {
  3129. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  3130. return GImGui->IO;
  3131. }
  3132. ImGuiPlatformIO& ImGui::GetPlatformIO()
  3133. {
  3134. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  3135. return GImGui->PlatformIO;
  3136. }
  3137. // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
  3138. ImDrawData* ImGui::GetDrawData()
  3139. {
  3140. ImGuiContext& g = *GImGui;
  3141. ImGuiViewportP* viewport = g.Viewports[0];
  3142. return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
  3143. }
  3144. double ImGui::GetTime()
  3145. {
  3146. return GImGui->Time;
  3147. }
  3148. int ImGui::GetFrameCount()
  3149. {
  3150. return GImGui->FrameCount;
  3151. }
  3152. static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
  3153. {
  3154. // Create the draw list on demand, because they are not frequently used for all viewports
  3155. ImGuiContext& g = *GImGui;
  3156. IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
  3157. ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
  3158. if (draw_list == NULL)
  3159. {
  3160. draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
  3161. draw_list->_OwnerName = drawlist_name;
  3162. viewport->DrawLists[drawlist_no] = draw_list;
  3163. }
  3164. // Our ImDrawList system requires that there is always a command
  3165. if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
  3166. {
  3167. draw_list->_ResetForNewFrame();
  3168. draw_list->PushTextureID(g.IO.Fonts->TexID);
  3169. draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
  3170. viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
  3171. }
  3172. return draw_list;
  3173. }
  3174. ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
  3175. {
  3176. return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
  3177. }
  3178. ImDrawList* ImGui::GetBackgroundDrawList()
  3179. {
  3180. ImGuiContext& g = *GImGui;
  3181. return GetBackgroundDrawList(g.CurrentWindow->Viewport);
  3182. }
  3183. ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
  3184. {
  3185. return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
  3186. }
  3187. ImDrawList* ImGui::GetForegroundDrawList()
  3188. {
  3189. ImGuiContext& g = *GImGui;
  3190. return GetForegroundDrawList(g.CurrentWindow->Viewport);
  3191. }
  3192. ImDrawListSharedData* ImGui::GetDrawListSharedData()
  3193. {
  3194. return &GImGui->DrawListSharedData;
  3195. }
  3196. void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
  3197. {
  3198. // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
  3199. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
  3200. // This is because we want ActiveId to be set even when the window is not permitted to move.
  3201. ImGuiContext& g = *GImGui;
  3202. FocusWindow(window);
  3203. SetActiveID(window->MoveId, window);
  3204. g.NavDisableHighlight = true;
  3205. g.ActiveIdNoClearOnFocusLoss = true;
  3206. g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
  3207. bool can_move_window = true;
  3208. if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
  3209. can_move_window = false;
  3210. if (ImGuiDockNode* node = window->DockNodeAsHost)
  3211. if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
  3212. can_move_window = false;
  3213. if (can_move_window)
  3214. g.MovingWindow = window;
  3215. }
  3216. // We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
  3217. // - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
  3218. // - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
  3219. void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
  3220. {
  3221. ImGuiContext& g = *GImGui;
  3222. bool can_undock_node = false;
  3223. if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
  3224. {
  3225. // Can undock if:
  3226. // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
  3227. // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
  3228. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  3229. if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
  3230. if (undock_floating_node || root_node->IsDockSpace())
  3231. can_undock_node = true;
  3232. }
  3233. const bool clicked = IsMouseClicked(0);
  3234. const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
  3235. if (can_undock_node && dragging)
  3236. DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
  3237. else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
  3238. StartMouseMovingWindow(window);
  3239. }
  3240. // Handle mouse moving window
  3241. // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
  3242. // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
  3243. // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
  3244. // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
  3245. void ImGui::UpdateMouseMovingWindowNewFrame()
  3246. {
  3247. ImGuiContext& g = *GImGui;
  3248. if (g.MovingWindow != NULL)
  3249. {
  3250. // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
  3251. // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
  3252. KeepAliveID(g.ActiveId);
  3253. IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
  3254. ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
  3255. if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
  3256. {
  3257. ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
  3258. if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
  3259. {
  3260. MarkIniSettingsDirty(moving_window);
  3261. SetWindowPos(moving_window, pos, ImGuiCond_Always);
  3262. if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
  3263. {
  3264. moving_window->Viewport->Pos = pos;
  3265. moving_window->Viewport->UpdateWorkRect();
  3266. }
  3267. }
  3268. FocusWindow(g.MovingWindow);
  3269. }
  3270. else
  3271. {
  3272. // Try to merge the window back into the main viewport.
  3273. // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
  3274. if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
  3275. UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
  3276. // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
  3277. if (!IsDragDropPayloadBeingAccepted())
  3278. g.MouseViewport = moving_window->Viewport;
  3279. // Clear the NoInput window flag set by the Viewport system
  3280. moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
  3281. ClearActiveID();
  3282. g.MovingWindow = NULL;
  3283. }
  3284. }
  3285. else
  3286. {
  3287. // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
  3288. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
  3289. {
  3290. KeepAliveID(g.ActiveId);
  3291. if (!g.IO.MouseDown[0])
  3292. ClearActiveID();
  3293. }
  3294. }
  3295. }
  3296. // Initiate moving window when clicking on empty space or title bar.
  3297. // Handle left-click and right-click focus.
  3298. void ImGui::UpdateMouseMovingWindowEndFrame()
  3299. {
  3300. ImGuiContext& g = *GImGui;
  3301. if (g.ActiveId != 0 || g.HoveredId != 0)
  3302. return;
  3303. // Unless we just made a window/popup appear
  3304. if (g.NavWindow && g.NavWindow->Appearing)
  3305. return;
  3306. // Click on empty space to focus window and start moving
  3307. // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
  3308. if (g.IO.MouseClicked[0])
  3309. {
  3310. // Handle the edge case of a popup being closed while clicking in its empty space.
  3311. // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
  3312. ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
  3313. const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
  3314. if (root_window != NULL && !is_closed_popup)
  3315. {
  3316. StartMouseMovingWindow(g.HoveredWindow); //-V595
  3317. // Cancel moving if clicked outside of title bar
  3318. if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
  3319. if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
  3320. if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
  3321. g.MovingWindow = NULL;
  3322. // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
  3323. if (g.HoveredIdDisabled)
  3324. g.MovingWindow = NULL;
  3325. }
  3326. else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
  3327. {
  3328. // Clicking on void disable focus
  3329. FocusWindow(NULL);
  3330. }
  3331. }
  3332. // With right mouse button we close popups without changing focus based on where the mouse is aimed
  3333. // Instead, focus will be restored to the window under the bottom-most closed popup.
  3334. // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
  3335. if (g.IO.MouseClicked[1])
  3336. {
  3337. // Find the top-most window between HoveredWindow and the top-most Modal Window.
  3338. // This is where we can trim the popup stack.
  3339. ImGuiWindow* modal = GetTopMostPopupModal();
  3340. bool hovered_window_above_modal = g.HoveredWindow && IsWindowAbove(g.HoveredWindow, modal);
  3341. ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
  3342. }
  3343. }
  3344. static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
  3345. {
  3346. window->Pos += delta;
  3347. window->ClipRect.Translate(delta);
  3348. window->OuterRectClipped.Translate(delta);
  3349. window->InnerRect.Translate(delta);
  3350. window->DC.CursorPos += delta;
  3351. window->DC.CursorStartPos += delta;
  3352. window->DC.CursorMaxPos += delta;
  3353. window->DC.LastItemRect.Translate(delta);
  3354. window->DC.LastItemDisplayRect.Translate(delta);
  3355. }
  3356. static void ScaleWindow(ImGuiWindow* window, float scale)
  3357. {
  3358. ImVec2 origin = window->Viewport->Pos;
  3359. window->Pos = ImFloor((window->Pos - origin) * scale + origin);
  3360. window->Size = ImFloor(window->Size * scale);
  3361. window->SizeFull = ImFloor(window->SizeFull * scale);
  3362. window->ContentSize = ImFloor(window->ContentSize * scale);
  3363. }
  3364. static bool IsWindowActiveAndVisible(ImGuiWindow* window)
  3365. {
  3366. return (window->Active) && (!window->Hidden);
  3367. }
  3368. static void ImGui::UpdateMouseInputs()
  3369. {
  3370. ImGuiContext& g = *GImGui;
  3371. // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
  3372. if (IsMousePosValid(&g.IO.MousePos))
  3373. g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
  3374. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
  3375. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
  3376. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  3377. else
  3378. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  3379. if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
  3380. g.NavDisableMouseHover = false;
  3381. g.IO.MousePosPrev = g.IO.MousePos;
  3382. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  3383. {
  3384. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  3385. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  3386. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  3387. g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  3388. g.IO.MouseDoubleClicked[i] = false;
  3389. if (g.IO.MouseClicked[i])
  3390. {
  3391. if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
  3392. {
  3393. ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  3394. if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  3395. g.IO.MouseDoubleClicked[i] = true;
  3396. g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" so the third click isn't turned into a double-click
  3397. }
  3398. else
  3399. {
  3400. g.IO.MouseClickedTime[i] = g.Time;
  3401. }
  3402. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  3403. g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
  3404. g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
  3405. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  3406. }
  3407. else if (g.IO.MouseDown[i])
  3408. {
  3409. // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
  3410. ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  3411. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
  3412. g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
  3413. g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
  3414. }
  3415. if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
  3416. g.IO.MouseDownWasDoubleClick[i] = false;
  3417. if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
  3418. g.NavDisableMouseHover = false;
  3419. }
  3420. }
  3421. static void StartLockWheelingWindow(ImGuiWindow* window)
  3422. {
  3423. ImGuiContext& g = *GImGui;
  3424. if (g.WheelingWindow == window)
  3425. return;
  3426. g.WheelingWindow = window;
  3427. g.WheelingWindowRefMousePos = g.IO.MousePos;
  3428. g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
  3429. }
  3430. void ImGui::UpdateMouseWheel()
  3431. {
  3432. ImGuiContext& g = *GImGui;
  3433. // Reset the locked window if we move the mouse or after the timer elapses
  3434. if (g.WheelingWindow != NULL)
  3435. {
  3436. g.WheelingWindowTimer -= g.IO.DeltaTime;
  3437. if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
  3438. g.WheelingWindowTimer = 0.0f;
  3439. if (g.WheelingWindowTimer <= 0.0f)
  3440. {
  3441. g.WheelingWindow = NULL;
  3442. g.WheelingWindowTimer = 0.0f;
  3443. }
  3444. }
  3445. if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
  3446. return;
  3447. if ((g.ActiveId != 0 && g.ActiveIdUsingMouseWheel) || (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel))
  3448. return;
  3449. ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
  3450. if (!window || window->Collapsed)
  3451. return;
  3452. // Zoom / Scale window
  3453. // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
  3454. if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  3455. {
  3456. StartLockWheelingWindow(window);
  3457. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  3458. const float scale = new_font_scale / window->FontWindowScale;
  3459. window->FontWindowScale = new_font_scale;
  3460. if (window == window->RootWindow)
  3461. {
  3462. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  3463. SetWindowPos(window, window->Pos + offset, 0);
  3464. window->Size = ImFloor(window->Size * scale);
  3465. window->SizeFull = ImFloor(window->SizeFull * scale);
  3466. }
  3467. return;
  3468. }
  3469. // Mouse wheel scrolling
  3470. // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
  3471. if (g.IO.KeyCtrl)
  3472. return;
  3473. // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
  3474. // (we avoid doing it on OSX as it the OS input layer handles this already)
  3475. const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
  3476. const float wheel_y = swap_axis ? 0.0f : g.IO.MouseWheel;
  3477. const float wheel_x = swap_axis ? g.IO.MouseWheel : g.IO.MouseWheelH;
  3478. // Vertical Mouse Wheel scrolling
  3479. if (wheel_y != 0.0f)
  3480. {
  3481. StartLockWheelingWindow(window);
  3482. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3483. window = window->ParentWindow;
  3484. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3485. {
  3486. float max_step = window->InnerRect.GetHeight() * 0.67f;
  3487. float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
  3488. SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
  3489. }
  3490. }
  3491. // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
  3492. if (wheel_x != 0.0f)
  3493. {
  3494. StartLockWheelingWindow(window);
  3495. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3496. window = window->ParentWindow;
  3497. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3498. {
  3499. float max_step = window->InnerRect.GetWidth() * 0.67f;
  3500. float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
  3501. SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
  3502. }
  3503. }
  3504. }
  3505. void ImGui::UpdateTabFocus()
  3506. {
  3507. ImGuiContext& g = *GImGui;
  3508. // Pressing TAB activate widget focus
  3509. g.TabFocusPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
  3510. if (g.ActiveId == 0 && g.TabFocusPressed)
  3511. {
  3512. // - This path is only taken when no widget are active/tabbed-into yet.
  3513. // Subsequent tabbing will be processed by FocusableItemRegister()
  3514. // - Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
  3515. // manipulate the Next fields here even though they will be turned into Curr fields below.
  3516. g.TabFocusRequestNextWindow = g.NavWindow;
  3517. g.TabFocusRequestNextCounterRegular = INT_MAX;
  3518. if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
  3519. g.TabFocusRequestNextCounterTabStop = g.NavIdTabCounter + (g.IO.KeyShift ? -1 : 0);
  3520. else
  3521. g.TabFocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
  3522. }
  3523. // Turn queued focus request into current one
  3524. g.TabFocusRequestCurrWindow = NULL;
  3525. g.TabFocusRequestCurrCounterRegular = g.TabFocusRequestCurrCounterTabStop = INT_MAX;
  3526. if (g.TabFocusRequestNextWindow != NULL)
  3527. {
  3528. ImGuiWindow* window = g.TabFocusRequestNextWindow;
  3529. g.TabFocusRequestCurrWindow = window;
  3530. if (g.TabFocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
  3531. g.TabFocusRequestCurrCounterRegular = ImModPositive(g.TabFocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
  3532. if (g.TabFocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
  3533. g.TabFocusRequestCurrCounterTabStop = ImModPositive(g.TabFocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
  3534. g.TabFocusRequestNextWindow = NULL;
  3535. g.TabFocusRequestNextCounterRegular = g.TabFocusRequestNextCounterTabStop = INT_MAX;
  3536. }
  3537. g.NavIdTabCounter = INT_MAX;
  3538. }
  3539. // 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)
  3540. void ImGui::UpdateHoveredWindowAndCaptureFlags()
  3541. {
  3542. ImGuiContext& g = *GImGui;
  3543. g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
  3544. // Find the window hovered by mouse:
  3545. // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
  3546. // - 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.
  3547. // - 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.
  3548. bool clear_hovered_windows = false;
  3549. FindHoveredWindow();
  3550. IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
  3551. // Modal windows prevents mouse from hovering behind them.
  3552. ImGuiWindow* modal_window = GetTopMostPopupModal();
  3553. if (modal_window && g.HoveredWindow && !IsWindowChildOf(g.HoveredWindow->RootWindowDockTree, modal_window))
  3554. clear_hovered_windows = true;
  3555. // Disabled mouse?
  3556. if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
  3557. clear_hovered_windows = true;
  3558. // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
  3559. int mouse_earliest_button_down = -1;
  3560. bool mouse_any_down = false;
  3561. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  3562. {
  3563. if (g.IO.MouseClicked[i])
  3564. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (g.OpenPopupStack.Size > 0);
  3565. mouse_any_down |= g.IO.MouseDown[i];
  3566. if (g.IO.MouseDown[i])
  3567. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
  3568. mouse_earliest_button_down = i;
  3569. }
  3570. const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
  3571. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  3572. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
  3573. const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
  3574. if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
  3575. clear_hovered_windows = true;
  3576. if (clear_hovered_windows)
  3577. g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3578. // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
  3579. if (g.WantCaptureMouseNextFrame != -1)
  3580. g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
  3581. else
  3582. g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.OpenPopupStack.Size > 0);
  3583. // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
  3584. if (g.WantCaptureKeyboardNextFrame != -1)
  3585. g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
  3586. else
  3587. g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
  3588. if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
  3589. g.IO.WantCaptureKeyboard = true;
  3590. // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
  3591. g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
  3592. }
  3593. ImGuiKeyModFlags ImGui::GetMergedKeyModFlags()
  3594. {
  3595. ImGuiContext& g = *GImGui;
  3596. ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None;
  3597. if (g.IO.KeyCtrl) { key_mod_flags |= ImGuiKeyModFlags_Ctrl; }
  3598. if (g.IO.KeyShift) { key_mod_flags |= ImGuiKeyModFlags_Shift; }
  3599. if (g.IO.KeyAlt) { key_mod_flags |= ImGuiKeyModFlags_Alt; }
  3600. if (g.IO.KeySuper) { key_mod_flags |= ImGuiKeyModFlags_Super; }
  3601. return key_mod_flags;
  3602. }
  3603. void ImGui::NewFrame()
  3604. {
  3605. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  3606. ImGuiContext& g = *GImGui;
  3607. // Remove pending delete hooks before frame start.
  3608. // This deferred removal avoid issues of removal while iterating the hook vector
  3609. for (int n = g.Hooks.Size - 1; n >= 0; n--)
  3610. if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
  3611. g.Hooks.erase(&g.Hooks[n]);
  3612. CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
  3613. // Check and assert for various common IO and Configuration mistakes
  3614. g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
  3615. ErrorCheckNewFrameSanityChecks();
  3616. g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
  3617. // Load settings on first frame, save settings when modified (after a delay)
  3618. UpdateSettings();
  3619. g.Time += g.IO.DeltaTime;
  3620. g.WithinFrameScope = true;
  3621. g.FrameCount += 1;
  3622. g.TooltipOverrideCount = 0;
  3623. g.WindowsActiveCount = 0;
  3624. g.MenusIdSubmittedThisFrame.resize(0);
  3625. // Calculate frame-rate for the user, as a purely luxurious feature
  3626. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  3627. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  3628. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  3629. g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
  3630. g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
  3631. UpdateViewportsNewFrame();
  3632. // Setup current font and draw list shared data
  3633. // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
  3634. g.IO.Fonts->Locked = true;
  3635. SetCurrentFont(GetDefaultFont());
  3636. IM_ASSERT(g.Font->IsLoaded());
  3637. ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  3638. for (int n = 0; n < g.Viewports.Size; n++)
  3639. virtual_space.Add(g.Viewports[n]->GetMainRect());
  3640. g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
  3641. g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
  3642. g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
  3643. g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
  3644. if (g.Style.AntiAliasedLines)
  3645. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
  3646. if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
  3647. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
  3648. if (g.Style.AntiAliasedFill)
  3649. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
  3650. if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
  3651. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
  3652. // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
  3653. for (int n = 0; n < g.Viewports.Size; n++)
  3654. {
  3655. ImGuiViewportP* viewport = g.Viewports[n];
  3656. viewport->DrawData = NULL;
  3657. viewport->DrawDataP.Clear();
  3658. }
  3659. // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
  3660. if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
  3661. KeepAliveID(g.DragDropPayload.SourceId);
  3662. // Update HoveredId data
  3663. if (!g.HoveredIdPreviousFrame)
  3664. g.HoveredIdTimer = 0.0f;
  3665. if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
  3666. g.HoveredIdNotActiveTimer = 0.0f;
  3667. if (g.HoveredId)
  3668. g.HoveredIdTimer += g.IO.DeltaTime;
  3669. if (g.HoveredId && g.ActiveId != g.HoveredId)
  3670. g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
  3671. g.HoveredIdPreviousFrame = g.HoveredId;
  3672. g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel;
  3673. g.HoveredId = 0;
  3674. g.HoveredIdAllowOverlap = false;
  3675. g.HoveredIdUsingMouseWheel = false;
  3676. g.HoveredIdDisabled = false;
  3677. // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
  3678. if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  3679. ClearActiveID();
  3680. if (g.ActiveId)
  3681. g.ActiveIdTimer += g.IO.DeltaTime;
  3682. g.LastActiveIdTimer += g.IO.DeltaTime;
  3683. g.ActiveIdPreviousFrame = g.ActiveId;
  3684. g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
  3685. g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
  3686. g.ActiveIdIsAlive = 0;
  3687. g.ActiveIdHasBeenEditedThisFrame = false;
  3688. g.ActiveIdPreviousFrameIsAlive = false;
  3689. g.ActiveIdIsJustActivated = false;
  3690. if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
  3691. g.TempInputId = 0;
  3692. if (g.ActiveId == 0)
  3693. {
  3694. g.ActiveIdUsingNavDirMask = 0x00;
  3695. g.ActiveIdUsingNavInputMask = 0x00;
  3696. g.ActiveIdUsingKeyInputMask = 0x00;
  3697. }
  3698. // Drag and drop
  3699. g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
  3700. g.DragDropAcceptIdCurr = 0;
  3701. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  3702. g.DragDropWithinSource = false;
  3703. g.DragDropWithinTarget = false;
  3704. g.DragDropHoldJustPressedId = 0;
  3705. // Update keyboard input state
  3706. // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools
  3707. g.IO.KeyMods = GetMergedKeyModFlags();
  3708. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  3709. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  3710. g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  3711. // Update gamepad/keyboard navigation
  3712. NavUpdate();
  3713. // Update mouse input state
  3714. UpdateMouseInputs();
  3715. // Undocking
  3716. // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
  3717. DockContextNewFrameUpdateUndocking(&g);
  3718. // Find hovered window
  3719. // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
  3720. UpdateHoveredWindowAndCaptureFlags();
  3721. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
  3722. UpdateMouseMovingWindowNewFrame();
  3723. // Background darkening/whitening
  3724. if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
  3725. g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  3726. else
  3727. g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
  3728. g.MouseCursor = ImGuiMouseCursor_Arrow;
  3729. g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
  3730. g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  3731. g.PlatformImePosViewport = NULL;
  3732. // Mouse wheel scrolling, scale
  3733. UpdateMouseWheel();
  3734. // Update legacy TAB focus
  3735. UpdateTabFocus();
  3736. // Mark all windows as not visible and compact unused memory.
  3737. IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
  3738. const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
  3739. for (int i = 0; i != g.Windows.Size; i++)
  3740. {
  3741. ImGuiWindow* window = g.Windows[i];
  3742. window->WasActive = window->Active;
  3743. window->BeginCount = 0;
  3744. window->Active = false;
  3745. window->WriteAccessed = false;
  3746. // Garbage collect transient buffers of recently unused windows
  3747. if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
  3748. GcCompactTransientWindowBuffers(window);
  3749. }
  3750. // Garbage collect transient buffers of recently unused tables
  3751. for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
  3752. if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
  3753. TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
  3754. for (int i = 0; i < g.TablesTempDataStack.Size; i++)
  3755. if (g.TablesTempDataStack[i].LastTimeActive >= 0.0f && g.TablesTempDataStack[i].LastTimeActive < memory_compact_start_time)
  3756. TableGcCompactTransientBuffers(&g.TablesTempDataStack[i]);
  3757. if (g.GcCompactAll)
  3758. GcCompactTransientMiscBuffers();
  3759. g.GcCompactAll = false;
  3760. // Closing the focused window restore focus to the first active root window in descending z-order
  3761. if (g.NavWindow && !g.NavWindow->WasActive)
  3762. FocusTopMostWindowUnderOne(NULL, NULL);
  3763. // No window should be open at the beginning of the frame.
  3764. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  3765. g.CurrentWindowStack.resize(0);
  3766. g.BeginPopupStack.resize(0);
  3767. g.ItemFlagsStack.resize(0);
  3768. g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
  3769. g.GroupStack.resize(0);
  3770. ClosePopupsOverWindow(g.NavWindow, false);
  3771. // Docking
  3772. DockContextNewFrameUpdateDocking(&g);
  3773. // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
  3774. UpdateDebugToolItemPicker();
  3775. // Create implicit/fallback window - which we will only render it if the user has added something to it.
  3776. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
  3777. // This fallback is particularly important as it avoid ImGui:: calls from crashing.
  3778. g.WithinFrameScopeWithImplicitWindow = true;
  3779. SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
  3780. Begin("Debug##Default");
  3781. IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
  3782. CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
  3783. }
  3784. // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
  3785. void ImGui::UpdateDebugToolItemPicker()
  3786. {
  3787. ImGuiContext& g = *GImGui;
  3788. g.DebugItemPickerBreakId = 0;
  3789. if (g.DebugItemPickerActive)
  3790. {
  3791. const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
  3792. ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
  3793. if (ImGui::IsKeyPressedMap(ImGuiKey_Escape))
  3794. g.DebugItemPickerActive = false;
  3795. if (ImGui::IsMouseClicked(0) && hovered_id)
  3796. {
  3797. g.DebugItemPickerBreakId = hovered_id;
  3798. g.DebugItemPickerActive = false;
  3799. }
  3800. ImGui::SetNextWindowBgAlpha(0.60f);
  3801. ImGui::BeginTooltip();
  3802. ImGui::Text("HoveredId: 0x%08X", hovered_id);
  3803. ImGui::Text("Press ESC to abort picking.");
  3804. ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
  3805. ImGui::EndTooltip();
  3806. }
  3807. }
  3808. void ImGui::Initialize(ImGuiContext* context)
  3809. {
  3810. ImGuiContext& g = *context;
  3811. IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
  3812. // Add .ini handle for ImGuiWindow type
  3813. {
  3814. ImGuiSettingsHandler ini_handler;
  3815. ini_handler.TypeName = "Window";
  3816. ini_handler.TypeHash = ImHashStr("Window");
  3817. ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
  3818. ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
  3819. ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
  3820. ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
  3821. ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
  3822. g.SettingsHandlers.push_back(ini_handler);
  3823. }
  3824. #ifdef IMGUI_HAS_TABLE
  3825. // Add .ini handle for ImGuiTable type
  3826. TableSettingsInstallHandler(context);
  3827. #endif // #ifdef IMGUI_HAS_TABLE
  3828. // Create default viewport
  3829. ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
  3830. viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
  3831. viewport->Idx = 0;
  3832. viewport->PlatformWindowCreated = true;
  3833. viewport->Flags = ImGuiViewportFlags_OwnedByApp;
  3834. g.Viewports.push_back(viewport);
  3835. g.PlatformIO.Viewports.push_back(g.Viewports[0]);
  3836. #ifdef IMGUI_HAS_DOCK
  3837. // Initialize Docking
  3838. DockContextInitialize(&g);
  3839. #endif
  3840. g.Initialized = true;
  3841. }
  3842. // This function is merely here to free heap allocations.
  3843. void ImGui::Shutdown(ImGuiContext* context)
  3844. {
  3845. // 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)
  3846. ImGuiContext& g = *context;
  3847. if (g.IO.Fonts && g.FontAtlasOwnedByContext)
  3848. {
  3849. g.IO.Fonts->Locked = false;
  3850. IM_DELETE(g.IO.Fonts);
  3851. }
  3852. g.IO.Fonts = NULL;
  3853. // Cleanup of other data are conditional on actually having initialized Dear ImGui.
  3854. if (!g.Initialized)
  3855. return;
  3856. // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
  3857. if (g.SettingsLoaded && g.IO.IniFilename != NULL)
  3858. {
  3859. ImGuiContext* backup_context = GImGui;
  3860. SetCurrentContext(&g);
  3861. SaveIniSettingsToDisk(g.IO.IniFilename);
  3862. SetCurrentContext(backup_context);
  3863. }
  3864. // Destroy platform windows
  3865. ImGuiContext* backup_context = ImGui::GetCurrentContext();
  3866. SetCurrentContext(context);
  3867. DestroyPlatformWindows();
  3868. SetCurrentContext(backup_context);
  3869. // Shutdown extensions
  3870. DockContextShutdown(&g);
  3871. CallContextHooks(&g, ImGuiContextHookType_Shutdown);
  3872. // Clear everything else
  3873. for (int i = 0; i < g.Windows.Size; i++)
  3874. IM_DELETE(g.Windows[i]);
  3875. g.Windows.clear();
  3876. g.WindowsFocusOrder.clear();
  3877. g.WindowsTempSortBuffer.clear();
  3878. g.CurrentWindow = NULL;
  3879. g.CurrentWindowStack.clear();
  3880. g.WindowsById.Clear();
  3881. g.NavWindow = NULL;
  3882. g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3883. g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
  3884. g.MovingWindow = NULL;
  3885. g.ColorStack.clear();
  3886. g.StyleVarStack.clear();
  3887. g.FontStack.clear();
  3888. g.OpenPopupStack.clear();
  3889. g.BeginPopupStack.clear();
  3890. g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
  3891. for (int i = 0; i < g.Viewports.Size; i++)
  3892. IM_DELETE(g.Viewports[i]);
  3893. g.Viewports.clear();
  3894. g.TabBars.Clear();
  3895. g.CurrentTabBarStack.clear();
  3896. g.ShrinkWidthBuffer.clear();
  3897. g.Tables.Clear();
  3898. for (int i = 0; i < g.TablesTempDataStack.Size; i++)
  3899. g.TablesTempDataStack[i].~ImGuiTableTempData();
  3900. g.TablesTempDataStack.clear();
  3901. g.DrawChannelsTempMergeBuffer.clear();
  3902. g.ClipboardHandlerData.clear();
  3903. g.MenusIdSubmittedThisFrame.clear();
  3904. g.InputTextState.ClearFreeMemory();
  3905. g.SettingsWindows.clear();
  3906. g.SettingsHandlers.clear();
  3907. if (g.LogFile)
  3908. {
  3909. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  3910. if (g.LogFile != stdout)
  3911. #endif
  3912. ImFileClose(g.LogFile);
  3913. g.LogFile = NULL;
  3914. }
  3915. g.LogBuffer.clear();
  3916. g.Initialized = false;
  3917. }
  3918. // FIXME: Add a more explicit sort order in the window structure.
  3919. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
  3920. {
  3921. const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
  3922. const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
  3923. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  3924. return d;
  3925. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  3926. return d;
  3927. return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
  3928. }
  3929. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
  3930. {
  3931. out_sorted_windows->push_back(window);
  3932. if (window->Active)
  3933. {
  3934. int count = window->DC.ChildWindows.Size;
  3935. if (count > 1)
  3936. ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  3937. for (int i = 0; i < count; i++)
  3938. {
  3939. ImGuiWindow* child = window->DC.ChildWindows[i];
  3940. if (child->Active)
  3941. AddWindowToSortBuffer(out_sorted_windows, child);
  3942. }
  3943. }
  3944. }
  3945. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
  3946. {
  3947. // Remove trailing command if unused.
  3948. // Technically we could return directly instead of popping, but this make things looks neat in Metrics/Debugger window as well.
  3949. draw_list->_PopUnusedDrawCmd();
  3950. if (draw_list->CmdBuffer.Size == 0)
  3951. return;
  3952. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
  3953. // May trigger for you if you are using PrimXXX functions incorrectly.
  3954. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  3955. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  3956. if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
  3957. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  3958. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
  3959. // If this assert triggers because you are drawing lots of stuff manually:
  3960. // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
  3961. // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
  3962. // - If you want large meshes with more than 64K vertices, you can either:
  3963. // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
  3964. // Most example backends already support this from 1.71. Pre-1.71 backends won't.
  3965. // 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.
  3966. // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
  3967. // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
  3968. // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
  3969. // Your own engine or render API may use different parameters or function calls to specify index sizes.
  3970. // 2 and 4 bytes indices are generally supported by most graphics API.
  3971. // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
  3972. // the 64K limit to split your draw commands in multiple draw lists.
  3973. if (sizeof(ImDrawIdx) == 2)
  3974. IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
  3975. out_list->push_back(draw_list);
  3976. }
  3977. static void AddWindowToDrawData(ImGuiWindow* window, int layer)
  3978. {
  3979. ImGuiContext& g = *GImGui;
  3980. ImGuiViewportP* viewport = window->Viewport;
  3981. g.IO.MetricsRenderWindows++;
  3982. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
  3983. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  3984. {
  3985. ImGuiWindow* child = window->DC.ChildWindows[i];
  3986. if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
  3987. AddWindowToDrawData(child, layer);
  3988. }
  3989. }
  3990. // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
  3991. static void AddRootWindowToDrawData(ImGuiWindow* window)
  3992. {
  3993. int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
  3994. AddWindowToDrawData(window, layer);
  3995. }
  3996. void ImDrawDataBuilder::FlattenIntoSingleLayer()
  3997. {
  3998. int n = Layers[0].Size;
  3999. int size = n;
  4000. for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
  4001. size += Layers[i].Size;
  4002. Layers[0].resize(size);
  4003. for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
  4004. {
  4005. ImVector<ImDrawList*>& layer = Layers[layer_n];
  4006. if (layer.empty())
  4007. continue;
  4008. memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  4009. n += layer.Size;
  4010. layer.resize(0);
  4011. }
  4012. }
  4013. static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
  4014. {
  4015. // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
  4016. // and to allow applications/backends to easily skip rendering.
  4017. // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
  4018. // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
  4019. // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
  4020. const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0;
  4021. ImGuiIO& io = ImGui::GetIO();
  4022. ImDrawData* draw_data = &viewport->DrawDataP;
  4023. viewport->DrawData = draw_data; // Make publicly accessible
  4024. draw_data->Valid = true;
  4025. draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
  4026. draw_data->CmdListsCount = draw_lists->Size;
  4027. draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
  4028. draw_data->DisplayPos = viewport->Pos;
  4029. draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
  4030. draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
  4031. draw_data->OwnerViewport = viewport;
  4032. for (int n = 0; n < draw_lists->Size; n++)
  4033. {
  4034. draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
  4035. draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
  4036. }
  4037. }
  4038. // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
  4039. // - When using this function it is sane to ensure that float are perfectly rounded to integer values,
  4040. // so that e.g. (int)(max.x-min.x) in user's render produce correct result.
  4041. // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
  4042. // some frequently called functions which to modify both channels and clipping simultaneously tend to use the
  4043. // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
  4044. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  4045. {
  4046. ImGuiWindow* window = GetCurrentWindow();
  4047. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  4048. window->ClipRect = window->DrawList->_ClipRectStack.back();
  4049. }
  4050. void ImGui::PopClipRect()
  4051. {
  4052. ImGuiWindow* window = GetCurrentWindow();
  4053. window->DrawList->PopClipRect();
  4054. window->ClipRect = window->DrawList->_ClipRectStack.back();
  4055. }
  4056. static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
  4057. {
  4058. for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
  4059. if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
  4060. return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
  4061. return window;
  4062. }
  4063. static void ImGui::EndFrameDrawDimmedBackgrounds()
  4064. {
  4065. ImGuiContext& g = *GImGui;
  4066. // Draw modal whitening background on _other_ viewports than the one the modal is one
  4067. ImGuiWindow* modal_window = GetTopMostPopupModal();
  4068. const bool dim_bg_for_modal = (modal_window != NULL);
  4069. const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL);
  4070. if (dim_bg_for_modal || dim_bg_for_window_list)
  4071. for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
  4072. {
  4073. ImGuiViewportP* viewport = g.Viewports[viewport_n];
  4074. if (modal_window && viewport == modal_window->Viewport)
  4075. continue;
  4076. if (g.NavWindowingListWindow && viewport == g.NavWindowingListWindow->Viewport)
  4077. continue;
  4078. if (g.NavWindowingTargetAnim && viewport == g.NavWindowingTargetAnim->Viewport)
  4079. continue;
  4080. if (viewport->Window && modal_window && IsWindowAbove(viewport->Window, modal_window))
  4081. continue;
  4082. ImDrawList* draw_list = GetForegroundDrawList(viewport);
  4083. const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
  4084. draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
  4085. }
  4086. // Draw modal whitening background between CTRL-TAB list
  4087. if (dim_bg_for_window_list && g.NavWindowingTargetAnim->Active)
  4088. {
  4089. // Choose a draw list that will be front-most across all our children
  4090. // In the unlikely case that the window wasn't made active we can't rely on its drawlist and skip rendering all-together.
  4091. ImGuiWindow* window = g.NavWindowingTargetAnim;
  4092. ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
  4093. draw_list->PushClipRectFullScreen();
  4094. // Docking: draw modal whitening background on other nodes of a same dock tree
  4095. // For CTRL+TAB within a docking node we need to render the dimming background in 8 steps
  4096. // (Because the root node renders the background in one shot, in order to avoid flickering when a child dock node is not submitted)
  4097. if (window->RootWindow->DockIsActive)
  4098. if (window->RootWindowDockTree != window->RootWindow)
  4099. RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio), g.Style.WindowRounding);
  4100. // Draw navigation selection/windowing rectangle border
  4101. float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
  4102. ImRect bb = window->Rect();
  4103. bb.Expand(g.FontSize);
  4104. if (bb.Contains(window->Viewport->GetMainRect())) // If a window fits the entire viewport, adjust its highlight inward
  4105. {
  4106. bb.Expand(-g.FontSize - 1.0f);
  4107. rounding = window->WindowRounding;
  4108. }
  4109. draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, 0, 3.0f);
  4110. draw_list->PopClipRect();
  4111. }
  4112. }
  4113. // 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.
  4114. void ImGui::EndFrame()
  4115. {
  4116. ImGuiContext& g = *GImGui;
  4117. IM_ASSERT(g.Initialized);
  4118. // Don't process EndFrame() multiple times.
  4119. if (g.FrameCountEnded == g.FrameCount)
  4120. return;
  4121. IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
  4122. CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
  4123. ErrorCheckEndFrameSanityChecks();
  4124. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  4125. if (g.PlatformIO.Platform_SetImeInputPos && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImePos - g.PlatformImeLastPos) > 0.0001f))
  4126. if (g.PlatformImePosViewport && g.PlatformImePosViewport->PlatformWindowCreated)
  4127. {
  4128. g.PlatformIO.Platform_SetImeInputPos(g.PlatformImePosViewport, g.PlatformImePos);
  4129. g.PlatformImeLastPos = g.PlatformImePos;
  4130. g.PlatformImePosViewport = NULL;
  4131. }
  4132. // Hide implicit/fallback "Debug" window if it hasn't been used
  4133. g.WithinFrameScopeWithImplicitWindow = false;
  4134. if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
  4135. g.CurrentWindow->Active = false;
  4136. End();
  4137. // Draw modal whitening background on _other_ viewports than the one the modal is one
  4138. EndFrameDrawDimmedBackgrounds();
  4139. // Update navigation: CTRL+Tab, wrap-around requests
  4140. NavEndFrame();
  4141. SetCurrentViewport(NULL, NULL);
  4142. // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
  4143. if (g.DragDropActive)
  4144. {
  4145. bool is_delivered = g.DragDropPayload.Delivery;
  4146. bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
  4147. if (is_delivered || is_elapsed)
  4148. ClearDragDrop();
  4149. }
  4150. // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
  4151. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  4152. {
  4153. g.DragDropWithinSource = true;
  4154. SetTooltip("...");
  4155. g.DragDropWithinSource = false;
  4156. }
  4157. // End frame
  4158. g.WithinFrameScope = false;
  4159. g.FrameCountEnded = g.FrameCount;
  4160. // Initiate moving window + handle left-click and right-click focus
  4161. UpdateMouseMovingWindowEndFrame();
  4162. // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
  4163. UpdateViewportsEndFrame();
  4164. // Sort the window list so that all child windows are after their parent
  4165. // We cannot do that on FocusWindow() because children may not exist yet
  4166. g.WindowsTempSortBuffer.resize(0);
  4167. g.WindowsTempSortBuffer.reserve(g.Windows.Size);
  4168. for (int i = 0; i != g.Windows.Size; i++)
  4169. {
  4170. ImGuiWindow* window = g.Windows[i];
  4171. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  4172. continue;
  4173. AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
  4174. }
  4175. // 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.
  4176. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
  4177. g.Windows.swap(g.WindowsTempSortBuffer);
  4178. g.IO.MetricsActiveWindows = g.WindowsActiveCount;
  4179. // Unlock font atlas
  4180. g.IO.Fonts->Locked = false;
  4181. // Clear Input data for next frame
  4182. g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
  4183. g.IO.InputQueueCharacters.resize(0);
  4184. memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
  4185. CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
  4186. }
  4187. void ImGui::Render()
  4188. {
  4189. ImGuiContext& g = *GImGui;
  4190. IM_ASSERT(g.Initialized);
  4191. if (g.FrameCountEnded != g.FrameCount)
  4192. EndFrame();
  4193. g.FrameCountRendered = g.FrameCount;
  4194. g.IO.MetricsRenderWindows = 0;
  4195. CallContextHooks(&g, ImGuiContextHookType_RenderPre);
  4196. // Add background ImDrawList (for each active viewport)
  4197. for (int n = 0; n != g.Viewports.Size; n++)
  4198. {
  4199. ImGuiViewportP* viewport = g.Viewports[n];
  4200. viewport->DrawDataBuilder.Clear();
  4201. if (viewport->DrawLists[0] != NULL)
  4202. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
  4203. }
  4204. // Add ImDrawList to render
  4205. ImGuiWindow* windows_to_render_top_most[2];
  4206. windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
  4207. windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
  4208. for (int n = 0; n != g.Windows.Size; n++)
  4209. {
  4210. ImGuiWindow* window = g.Windows[n];
  4211. IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
  4212. if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
  4213. AddRootWindowToDrawData(window);
  4214. }
  4215. for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
  4216. if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
  4217. AddRootWindowToDrawData(windows_to_render_top_most[n]);
  4218. ImVec2 mouse_cursor_offset, mouse_cursor_size, mouse_cursor_uv[4];
  4219. if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
  4220. g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &mouse_cursor_offset, &mouse_cursor_size, &mouse_cursor_uv[0], &mouse_cursor_uv[2]);
  4221. // Setup ImDrawData structures for end-user
  4222. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
  4223. for (int n = 0; n < g.Viewports.Size; n++)
  4224. {
  4225. ImGuiViewportP* viewport = g.Viewports[n];
  4226. viewport->DrawDataBuilder.FlattenIntoSingleLayer();
  4227. // Draw software mouse cursor if requested by io.MouseDrawCursor flag
  4228. // (note we scale cursor by current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor)
  4229. if (mouse_cursor_size.x > 0.0f && mouse_cursor_size.y > 0.0f)
  4230. {
  4231. float scale = g.Style.MouseCursorScale * viewport->DpiScale;
  4232. if (viewport->GetMainRect().Overlaps(ImRect(g.IO.MousePos, g.IO.MousePos + ImVec2(mouse_cursor_size.x + 2, mouse_cursor_size.y + 2) * scale)))
  4233. RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, scale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
  4234. }
  4235. // Add foreground ImDrawList (for each active viewport)
  4236. if (viewport->DrawLists[1] != NULL)
  4237. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
  4238. SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
  4239. ImDrawData* draw_data = viewport->DrawData;
  4240. g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
  4241. g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
  4242. }
  4243. CallContextHooks(&g, ImGuiContextHookType_RenderPost);
  4244. }
  4245. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  4246. // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
  4247. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  4248. {
  4249. ImGuiContext& g = *GImGui;
  4250. const char* text_display_end;
  4251. if (hide_text_after_double_hash)
  4252. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  4253. else
  4254. text_display_end = text_end;
  4255. ImFont* font = g.Font;
  4256. const float font_size = g.FontSize;
  4257. if (text == text_display_end)
  4258. return ImVec2(0.0f, font_size);
  4259. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  4260. // Round
  4261. // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
  4262. // FIXME: Investigate using ceilf or e.g.
  4263. // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
  4264. // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
  4265. text_size.x = IM_FLOOR(text_size.x + 0.99999f);
  4266. return text_size;
  4267. }
  4268. // Find window given position, search front-to-back
  4269. // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
  4270. // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
  4271. // called, aka before the next Begin(). Moving window isn't affected.
  4272. static void FindHoveredWindow()
  4273. {
  4274. ImGuiContext& g = *GImGui;
  4275. // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
  4276. ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
  4277. if (g.MovingWindow)
  4278. g.MovingWindow->Viewport = g.MouseViewport;
  4279. ImGuiWindow* hovered_window = NULL;
  4280. ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
  4281. if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
  4282. hovered_window = g.MovingWindow;
  4283. ImVec2 padding_regular = g.Style.TouchExtraPadding;
  4284. ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
  4285. for (int i = g.Windows.Size - 1; i >= 0; i--)
  4286. {
  4287. ImGuiWindow* window = g.Windows[i];
  4288. IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
  4289. if (!window->Active || window->Hidden)
  4290. continue;
  4291. if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
  4292. continue;
  4293. IM_ASSERT(window->Viewport);
  4294. if (window->Viewport != g.MouseViewport)
  4295. continue;
  4296. // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
  4297. ImRect bb(window->OuterRectClipped);
  4298. if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
  4299. bb.Expand(padding_regular);
  4300. else
  4301. bb.Expand(padding_for_resize);
  4302. if (!bb.Contains(g.IO.MousePos))
  4303. continue;
  4304. // Support for one rectangular hole in any given window
  4305. // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
  4306. if (window->HitTestHoleSize.x != 0)
  4307. {
  4308. ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
  4309. ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
  4310. if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
  4311. continue;
  4312. }
  4313. if (hovered_window == NULL)
  4314. hovered_window = window;
  4315. IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
  4316. if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
  4317. hovered_window_ignoring_moving_window = window;
  4318. if (hovered_window && hovered_window_ignoring_moving_window)
  4319. break;
  4320. }
  4321. g.HoveredWindow = hovered_window;
  4322. g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
  4323. if (g.MovingWindow)
  4324. g.MovingWindow->Viewport = moving_window_viewport;
  4325. }
  4326. // Test if mouse cursor is hovering given rectangle
  4327. // NB- Rectangle is clipped by our current clip setting
  4328. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  4329. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  4330. {
  4331. ImGuiContext& g = *GImGui;
  4332. // Clip
  4333. ImRect rect_clipped(r_min, r_max);
  4334. if (clip)
  4335. rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
  4336. // Expand for touch input
  4337. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  4338. if (!rect_for_touch.Contains(g.IO.MousePos))
  4339. return false;
  4340. if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
  4341. return false;
  4342. return true;
  4343. }
  4344. int ImGui::GetKeyIndex(ImGuiKey imgui_key)
  4345. {
  4346. IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
  4347. ImGuiContext& g = *GImGui;
  4348. return g.IO.KeyMap[imgui_key];
  4349. }
  4350. // Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
  4351. // Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]!
  4352. bool ImGui::IsKeyDown(int user_key_index)
  4353. {
  4354. if (user_key_index < 0)
  4355. return false;
  4356. ImGuiContext& g = *GImGui;
  4357. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4358. return g.IO.KeysDown[user_key_index];
  4359. }
  4360. // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
  4361. // t1 = current time (e.g.: g.Time)
  4362. // An event is triggered at:
  4363. // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
  4364. int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
  4365. {
  4366. if (t1 == 0.0f)
  4367. return 1;
  4368. if (t0 >= t1)
  4369. return 0;
  4370. if (repeat_rate <= 0.0f)
  4371. return (t0 < repeat_delay) && (t1 >= repeat_delay);
  4372. const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
  4373. const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
  4374. const int count = count_t1 - count_t0;
  4375. return count;
  4376. }
  4377. int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
  4378. {
  4379. ImGuiContext& g = *GImGui;
  4380. if (key_index < 0)
  4381. return 0;
  4382. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4383. const float t = g.IO.KeysDownDuration[key_index];
  4384. return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
  4385. }
  4386. bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
  4387. {
  4388. ImGuiContext& g = *GImGui;
  4389. if (user_key_index < 0)
  4390. return false;
  4391. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4392. const float t = g.IO.KeysDownDuration[user_key_index];
  4393. if (t == 0.0f)
  4394. return true;
  4395. if (repeat && t > g.IO.KeyRepeatDelay)
  4396. return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  4397. return false;
  4398. }
  4399. bool ImGui::IsKeyReleased(int user_key_index)
  4400. {
  4401. ImGuiContext& g = *GImGui;
  4402. if (user_key_index < 0) return false;
  4403. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4404. return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
  4405. }
  4406. bool ImGui::IsMouseDown(ImGuiMouseButton button)
  4407. {
  4408. ImGuiContext& g = *GImGui;
  4409. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4410. return g.IO.MouseDown[button];
  4411. }
  4412. bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
  4413. {
  4414. ImGuiContext& g = *GImGui;
  4415. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4416. const float t = g.IO.MouseDownDuration[button];
  4417. if (t == 0.0f)
  4418. return true;
  4419. if (repeat && t > g.IO.KeyRepeatDelay)
  4420. {
  4421. // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
  4422. int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
  4423. if (amount > 0)
  4424. return true;
  4425. }
  4426. return false;
  4427. }
  4428. bool ImGui::IsMouseReleased(ImGuiMouseButton button)
  4429. {
  4430. ImGuiContext& g = *GImGui;
  4431. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4432. return g.IO.MouseReleased[button];
  4433. }
  4434. bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
  4435. {
  4436. ImGuiContext& g = *GImGui;
  4437. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4438. return g.IO.MouseDoubleClicked[button];
  4439. }
  4440. // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
  4441. // [Internal] This doesn't test if the button is pressed
  4442. bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
  4443. {
  4444. ImGuiContext& g = *GImGui;
  4445. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4446. if (lock_threshold < 0.0f)
  4447. lock_threshold = g.IO.MouseDragThreshold;
  4448. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  4449. }
  4450. bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
  4451. {
  4452. ImGuiContext& g = *GImGui;
  4453. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4454. if (!g.IO.MouseDown[button])
  4455. return false;
  4456. return IsMouseDragPastThreshold(button, lock_threshold);
  4457. }
  4458. ImVec2 ImGui::GetMousePos()
  4459. {
  4460. ImGuiContext& g = *GImGui;
  4461. return g.IO.MousePos;
  4462. }
  4463. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  4464. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  4465. {
  4466. ImGuiContext& g = *GImGui;
  4467. if (g.BeginPopupStack.Size > 0)
  4468. return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
  4469. return g.IO.MousePos;
  4470. }
  4471. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
  4472. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  4473. {
  4474. // The assert is only to silence a false-positive in XCode Static Analysis.
  4475. // 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).
  4476. IM_ASSERT(GImGui != NULL);
  4477. const float MOUSE_INVALID = -256000.0f;
  4478. ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
  4479. return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
  4480. }
  4481. bool ImGui::IsAnyMouseDown()
  4482. {
  4483. ImGuiContext& g = *GImGui;
  4484. for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
  4485. if (g.IO.MouseDown[n])
  4486. return true;
  4487. return false;
  4488. }
  4489. // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
  4490. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
  4491. // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
  4492. ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
  4493. {
  4494. ImGuiContext& g = *GImGui;
  4495. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4496. if (lock_threshold < 0.0f)
  4497. lock_threshold = g.IO.MouseDragThreshold;
  4498. if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
  4499. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  4500. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
  4501. return g.IO.MousePos - g.IO.MouseClickedPos[button];
  4502. return ImVec2(0.0f, 0.0f);
  4503. }
  4504. void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
  4505. {
  4506. ImGuiContext& g = *GImGui;
  4507. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4508. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  4509. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  4510. }
  4511. ImGuiMouseCursor ImGui::GetMouseCursor()
  4512. {
  4513. return GImGui->MouseCursor;
  4514. }
  4515. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  4516. {
  4517. GImGui->MouseCursor = cursor_type;
  4518. }
  4519. void ImGui::CaptureKeyboardFromApp(bool capture)
  4520. {
  4521. GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
  4522. }
  4523. void ImGui::CaptureMouseFromApp(bool capture)
  4524. {
  4525. GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
  4526. }
  4527. bool ImGui::IsItemActive()
  4528. {
  4529. ImGuiContext& g = *GImGui;
  4530. if (g.ActiveId)
  4531. {
  4532. ImGuiWindow* window = g.CurrentWindow;
  4533. return g.ActiveId == window->DC.LastItemId;
  4534. }
  4535. return false;
  4536. }
  4537. bool ImGui::IsItemActivated()
  4538. {
  4539. ImGuiContext& g = *GImGui;
  4540. if (g.ActiveId)
  4541. {
  4542. ImGuiWindow* window = g.CurrentWindow;
  4543. if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
  4544. return true;
  4545. }
  4546. return false;
  4547. }
  4548. bool ImGui::IsItemDeactivated()
  4549. {
  4550. ImGuiContext& g = *GImGui;
  4551. ImGuiWindow* window = g.CurrentWindow;
  4552. if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
  4553. return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
  4554. return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
  4555. }
  4556. bool ImGui::IsItemDeactivatedAfterEdit()
  4557. {
  4558. ImGuiContext& g = *GImGui;
  4559. return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
  4560. }
  4561. // == GetItemID() == GetFocusID()
  4562. bool ImGui::IsItemFocused()
  4563. {
  4564. ImGuiContext& g = *GImGui;
  4565. ImGuiWindow* window = g.CurrentWindow;
  4566. if (g.NavId != window->DC.LastItemId || g.NavId == 0)
  4567. return false;
  4568. // Special handling for the dummy item after Begin() which represent the title bar or tab.
  4569. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
  4570. if (window->DC.LastItemId == window->ID && window->WriteAccessed)
  4571. return false;
  4572. return true;
  4573. }
  4574. // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
  4575. // Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
  4576. bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
  4577. {
  4578. return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
  4579. }
  4580. bool ImGui::IsItemToggledOpen()
  4581. {
  4582. ImGuiContext& g = *GImGui;
  4583. return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
  4584. }
  4585. bool ImGui::IsItemToggledSelection()
  4586. {
  4587. ImGuiContext& g = *GImGui;
  4588. return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
  4589. }
  4590. bool ImGui::IsAnyItemHovered()
  4591. {
  4592. ImGuiContext& g = *GImGui;
  4593. return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
  4594. }
  4595. bool ImGui::IsAnyItemActive()
  4596. {
  4597. ImGuiContext& g = *GImGui;
  4598. return g.ActiveId != 0;
  4599. }
  4600. bool ImGui::IsAnyItemFocused()
  4601. {
  4602. ImGuiContext& g = *GImGui;
  4603. return g.NavId != 0 && !g.NavDisableHighlight;
  4604. }
  4605. bool ImGui::IsItemVisible()
  4606. {
  4607. ImGuiWindow* window = GetCurrentWindowRead();
  4608. return window->ClipRect.Overlaps(window->DC.LastItemRect);
  4609. }
  4610. bool ImGui::IsItemEdited()
  4611. {
  4612. ImGuiWindow* window = GetCurrentWindowRead();
  4613. return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
  4614. }
  4615. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  4616. // FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
  4617. void ImGui::SetItemAllowOverlap()
  4618. {
  4619. ImGuiContext& g = *GImGui;
  4620. ImGuiID id = g.CurrentWindow->DC.LastItemId;
  4621. if (g.HoveredId == id)
  4622. g.HoveredIdAllowOverlap = true;
  4623. if (g.ActiveId == id)
  4624. g.ActiveIdAllowOverlap = true;
  4625. }
  4626. void ImGui::SetItemUsingMouseWheel()
  4627. {
  4628. ImGuiContext& g = *GImGui;
  4629. ImGuiID id = g.CurrentWindow->DC.LastItemId;
  4630. if (g.HoveredId == id)
  4631. g.HoveredIdUsingMouseWheel = true;
  4632. if (g.ActiveId == id)
  4633. g.ActiveIdUsingMouseWheel = true;
  4634. }
  4635. ImVec2 ImGui::GetItemRectMin()
  4636. {
  4637. ImGuiWindow* window = GetCurrentWindowRead();
  4638. return window->DC.LastItemRect.Min;
  4639. }
  4640. ImVec2 ImGui::GetItemRectMax()
  4641. {
  4642. ImGuiWindow* window = GetCurrentWindowRead();
  4643. return window->DC.LastItemRect.Max;
  4644. }
  4645. ImVec2 ImGui::GetItemRectSize()
  4646. {
  4647. ImGuiWindow* window = GetCurrentWindowRead();
  4648. return window->DC.LastItemRect.GetSize();
  4649. }
  4650. bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
  4651. {
  4652. ImGuiContext& g = *GImGui;
  4653. ImGuiWindow* parent_window = g.CurrentWindow;
  4654. flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
  4655. flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
  4656. // Size
  4657. const ImVec2 content_avail = GetContentRegionAvail();
  4658. ImVec2 size = ImFloor(size_arg);
  4659. const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
  4660. if (size.x <= 0.0f)
  4661. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  4662. if (size.y <= 0.0f)
  4663. size.y = ImMax(content_avail.y + size.y, 4.0f);
  4664. SetNextWindowSize(size);
  4665. // 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.
  4666. if (name)
  4667. ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%s_%08X", parent_window->Name, name, id);
  4668. else
  4669. ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%08X", parent_window->Name, id);
  4670. const float backup_border_size = g.Style.ChildBorderSize;
  4671. if (!border)
  4672. g.Style.ChildBorderSize = 0.0f;
  4673. bool ret = Begin(g.TempBuffer, NULL, flags);
  4674. g.Style.ChildBorderSize = backup_border_size;
  4675. ImGuiWindow* child_window = g.CurrentWindow;
  4676. child_window->ChildId = id;
  4677. child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
  4678. // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
  4679. // While this is not really documented/defined, it seems that the expected thing to do.
  4680. if (child_window->BeginCount == 1)
  4681. parent_window->DC.CursorPos = child_window->Pos;
  4682. // Process navigation-in immediately so NavInit can run on first frame
  4683. if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
  4684. {
  4685. FocusWindow(child_window);
  4686. NavInitWindow(child_window, false);
  4687. SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
  4688. g.ActiveIdSource = ImGuiInputSource_Nav;
  4689. }
  4690. return ret;
  4691. }
  4692. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4693. {
  4694. ImGuiWindow* window = GetCurrentWindow();
  4695. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  4696. }
  4697. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4698. {
  4699. IM_ASSERT(id != 0);
  4700. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  4701. }
  4702. void ImGui::EndChild()
  4703. {
  4704. ImGuiContext& g = *GImGui;
  4705. ImGuiWindow* window = g.CurrentWindow;
  4706. IM_ASSERT(g.WithinEndChild == false);
  4707. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
  4708. g.WithinEndChild = true;
  4709. if (window->BeginCount > 1)
  4710. {
  4711. End();
  4712. }
  4713. else
  4714. {
  4715. ImVec2 sz = window->Size;
  4716. if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  4717. sz.x = ImMax(4.0f, sz.x);
  4718. if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
  4719. sz.y = ImMax(4.0f, sz.y);
  4720. End();
  4721. ImGuiWindow* parent_window = g.CurrentWindow;
  4722. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  4723. ItemSize(sz);
  4724. if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
  4725. {
  4726. ItemAdd(bb, window->ChildId);
  4727. RenderNavHighlight(bb, window->ChildId);
  4728. // When browsing a window that has no activable items (scroll only) we keep a highlight on the child
  4729. if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
  4730. RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
  4731. }
  4732. else
  4733. {
  4734. // Not navigable into
  4735. ItemAdd(bb, 0);
  4736. }
  4737. if (g.HoveredWindow == window)
  4738. parent_window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
  4739. }
  4740. g.WithinEndChild = false;
  4741. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  4742. }
  4743. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  4744. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  4745. {
  4746. ImGuiContext& g = *GImGui;
  4747. const ImGuiStyle& style = g.Style;
  4748. PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
  4749. PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
  4750. PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
  4751. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  4752. bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  4753. PopStyleVar(3);
  4754. PopStyleColor();
  4755. return ret;
  4756. }
  4757. void ImGui::EndChildFrame()
  4758. {
  4759. EndChild();
  4760. }
  4761. static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
  4762. {
  4763. window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
  4764. window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
  4765. window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
  4766. window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
  4767. }
  4768. ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
  4769. {
  4770. ImGuiContext& g = *GImGui;
  4771. return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
  4772. }
  4773. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  4774. {
  4775. ImGuiID id = ImHashStr(name);
  4776. return FindWindowByID(id);
  4777. }
  4778. static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
  4779. {
  4780. const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  4781. window->ViewportPos = main_viewport->Pos;
  4782. if (settings->ViewportId)
  4783. {
  4784. window->ViewportId = settings->ViewportId;
  4785. window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
  4786. }
  4787. window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
  4788. if (settings->Size.x > 0 && settings->Size.y > 0)
  4789. window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
  4790. window->Collapsed = settings->Collapsed;
  4791. window->DockId = settings->DockId;
  4792. window->DockOrder = settings->DockOrder;
  4793. }
  4794. static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
  4795. {
  4796. ImGuiContext& g = *GImGui;
  4797. //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
  4798. // Create window the first time
  4799. ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
  4800. window->Flags = flags;
  4801. g.WindowsById.SetVoidPtr(window->ID, window);
  4802. // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  4803. const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  4804. window->Pos = main_viewport->Pos + ImVec2(60, 60);
  4805. window->ViewportPos = main_viewport->Pos;
  4806. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  4807. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4808. if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
  4809. {
  4810. // Retrieve settings from .ini file
  4811. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  4812. SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
  4813. ApplyWindowSettings(window, settings);
  4814. }
  4815. window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
  4816. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  4817. {
  4818. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  4819. window->AutoFitOnlyGrows = false;
  4820. }
  4821. else
  4822. {
  4823. if (window->Size.x <= 0.0f)
  4824. window->AutoFitFramesX = 2;
  4825. if (window->Size.y <= 0.0f)
  4826. window->AutoFitFramesY = 2;
  4827. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  4828. }
  4829. if (!(flags & ImGuiWindowFlags_ChildWindow))
  4830. {
  4831. g.WindowsFocusOrder.push_back(window);
  4832. window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
  4833. }
  4834. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  4835. g.Windows.push_front(window); // Quite slow but rare and only once
  4836. else
  4837. g.Windows.push_back(window);
  4838. return window;
  4839. }
  4840. static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
  4841. {
  4842. return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
  4843. }
  4844. static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
  4845. {
  4846. return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
  4847. }
  4848. static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
  4849. {
  4850. ImGuiContext& g = *GImGui;
  4851. ImVec2 new_size = size_desired;
  4852. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
  4853. {
  4854. // Using -1,-1 on either X/Y axis to preserve the current size.
  4855. ImRect cr = g.NextWindowData.SizeConstraintRect;
  4856. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  4857. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  4858. if (g.NextWindowData.SizeCallback)
  4859. {
  4860. ImGuiSizeCallbackData data;
  4861. data.UserData = g.NextWindowData.SizeCallbackUserData;
  4862. data.Pos = window->Pos;
  4863. data.CurrentSize = window->SizeFull;
  4864. data.DesiredSize = new_size;
  4865. g.NextWindowData.SizeCallback(&data);
  4866. new_size = data.DesiredSize;
  4867. }
  4868. new_size.x = IM_FLOOR(new_size.x);
  4869. new_size.y = IM_FLOOR(new_size.y);
  4870. }
  4871. // Minimum size
  4872. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  4873. {
  4874. ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
  4875. const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight();
  4876. new_size = ImMax(new_size, g.Style.WindowMinSize);
  4877. new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
  4878. }
  4879. return new_size;
  4880. }
  4881. static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
  4882. {
  4883. bool preserve_old_content_sizes = false;
  4884. if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  4885. preserve_old_content_sizes = true;
  4886. else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
  4887. preserve_old_content_sizes = true;
  4888. if (preserve_old_content_sizes)
  4889. {
  4890. *content_size_current = window->ContentSize;
  4891. *content_size_ideal = window->ContentSizeIdeal;
  4892. return;
  4893. }
  4894. content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
  4895. content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
  4896. 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);
  4897. 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);
  4898. }
  4899. static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
  4900. {
  4901. ImGuiContext& g = *GImGui;
  4902. ImGuiStyle& style = g.Style;
  4903. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  4904. ImVec2 size_pad = window->WindowPadding * 2.0f;
  4905. ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height);
  4906. if (window->Flags & ImGuiWindowFlags_Tooltip)
  4907. {
  4908. // Tooltip always resize
  4909. return size_desired;
  4910. }
  4911. else
  4912. {
  4913. // Maximum window size is determined by the viewport size or monitor size
  4914. const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
  4915. const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
  4916. ImVec2 size_min = style.WindowMinSize;
  4917. 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)
  4918. size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
  4919. // FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows?
  4920. ImVec2 avail_size = window->Viewport->Size;
  4921. if (window->ViewportOwned)
  4922. avail_size = ImVec2(FLT_MAX, FLT_MAX);
  4923. const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
  4924. if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
  4925. avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
  4926. ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
  4927. // When the window cannot fit all contents (either because of constraints, either because screen is too small),
  4928. // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
  4929. ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4930. 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);
  4931. 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);
  4932. if (will_have_scrollbar_x)
  4933. size_auto_fit.y += style.ScrollbarSize;
  4934. if (will_have_scrollbar_y)
  4935. size_auto_fit.x += style.ScrollbarSize;
  4936. return size_auto_fit;
  4937. }
  4938. }
  4939. ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
  4940. {
  4941. ImVec2 size_contents_current;
  4942. ImVec2 size_contents_ideal;
  4943. CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
  4944. ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
  4945. ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4946. return size_final;
  4947. }
  4948. static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
  4949. {
  4950. if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  4951. return ImGuiCol_PopupBg;
  4952. if (flags & ImGuiWindowFlags_ChildWindow)
  4953. return ImGuiCol_ChildBg;
  4954. return ImGuiCol_WindowBg;
  4955. }
  4956. static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
  4957. {
  4958. ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
  4959. ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
  4960. ImVec2 size_expected = pos_max - pos_min;
  4961. ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
  4962. *out_pos = pos_min;
  4963. if (corner_norm.x == 0.0f)
  4964. out_pos->x -= (size_constrained.x - size_expected.x);
  4965. if (corner_norm.y == 0.0f)
  4966. out_pos->y -= (size_constrained.y - size_expected.y);
  4967. *out_size = size_constrained;
  4968. }
  4969. // Data for resizing from corner
  4970. struct ImGuiResizeGripDef
  4971. {
  4972. ImVec2 CornerPosN;
  4973. ImVec2 InnerDir;
  4974. int AngleMin12, AngleMax12;
  4975. };
  4976. static const ImGuiResizeGripDef resize_grip_def[4] =
  4977. {
  4978. { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right
  4979. { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left
  4980. { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused)
  4981. { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
  4982. };
  4983. // Data for resizing from borders
  4984. struct ImGuiResizeBorderDef
  4985. {
  4986. ImVec2 InnerDir;
  4987. ImVec2 SegmentN1, SegmentN2;
  4988. float OuterAngle;
  4989. };
  4990. static const ImGuiResizeBorderDef resize_border_def[4] =
  4991. {
  4992. { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
  4993. { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
  4994. { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
  4995. { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
  4996. };
  4997. static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
  4998. {
  4999. ImRect rect = window->Rect();
  5000. if (thickness == 0.0f)
  5001. rect.Max -= ImVec2(1, 1);
  5002. 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); }
  5003. 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); }
  5004. 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); }
  5005. 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); }
  5006. IM_ASSERT(0);
  5007. return ImRect();
  5008. }
  5009. // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
  5010. ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
  5011. {
  5012. IM_ASSERT(n >= 0 && n < 4);
  5013. ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
  5014. id = ImHashStr("#RESIZE", 0, id);
  5015. id = ImHashData(&n, sizeof(int), id);
  5016. return id;
  5017. }
  5018. // Borders (Left, Right, Up, Down)
  5019. ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
  5020. {
  5021. IM_ASSERT(dir >= 0 && dir < 4);
  5022. int n = (int)dir + 4;
  5023. ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
  5024. id = ImHashStr("#RESIZE", 0, id);
  5025. id = ImHashData(&n, sizeof(int), id);
  5026. return id;
  5027. }
  5028. // Handle resize for: Resize Grips, Borders, Gamepad
  5029. // Return true when using auto-fit (double click on resize grip)
  5030. 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)
  5031. {
  5032. ImGuiContext& g = *GImGui;
  5033. ImGuiWindowFlags flags = window->Flags;
  5034. if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5035. return false;
  5036. if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
  5037. return false;
  5038. bool ret_auto_fit = false;
  5039. const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
  5040. const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  5041. const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
  5042. const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
  5043. ImVec2 pos_target(FLT_MAX, FLT_MAX);
  5044. ImVec2 size_target(FLT_MAX, FLT_MAX);
  5045. // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
  5046. // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
  5047. // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
  5048. // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
  5049. // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
  5050. // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
  5051. const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
  5052. if (clip_with_viewport_rect)
  5053. window->ClipRect = window->Viewport->GetMainRect();
  5054. // Resize grips and borders are on layer 1
  5055. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  5056. // Manual resize grips
  5057. PushID("#RESIZE");
  5058. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5059. {
  5060. const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
  5061. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
  5062. // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
  5063. bool hovered, held;
  5064. ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
  5065. if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
  5066. if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
  5067. ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
  5068. ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  5069. //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
  5070. if (hovered || held)
  5071. g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  5072. if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
  5073. {
  5074. // Manual auto-fit when double-clicking
  5075. size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  5076. ret_auto_fit = true;
  5077. ClearActiveID();
  5078. }
  5079. else if (held)
  5080. {
  5081. // Resize from any of the four corners
  5082. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  5083. 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);
  5084. 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);
  5085. 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
  5086. corner_target = ImClamp(corner_target, clamp_min, clamp_max);
  5087. CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
  5088. }
  5089. // Only lower-left grip is visible before hovering/activating
  5090. if (resize_grip_n == 0 || held || hovered)
  5091. resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  5092. }
  5093. for (int border_n = 0; border_n < resize_border_count; border_n++)
  5094. {
  5095. const ImGuiResizeBorderDef& def = resize_border_def[border_n];
  5096. const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  5097. bool hovered, held;
  5098. ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
  5099. ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
  5100. ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren);
  5101. //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
  5102. if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
  5103. {
  5104. g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
  5105. if (held)
  5106. *border_held = border_n;
  5107. }
  5108. if (held)
  5109. {
  5110. ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
  5111. ImVec2 clamp_max(border_n == ImGuiDir_Left ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? visibility_rect.Max.y : +FLT_MAX);
  5112. ImVec2 border_target = window->Pos;
  5113. border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
  5114. border_target = ImClamp(border_target, clamp_min, clamp_max);
  5115. CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
  5116. }
  5117. }
  5118. PopID();
  5119. // Restore nav layer
  5120. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5121. // Navigation resize (keyboard/gamepad)
  5122. if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
  5123. {
  5124. ImVec2 nav_resize_delta;
  5125. if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
  5126. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  5127. if (g.NavInputSource == ImGuiInputSource_Gamepad)
  5128. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
  5129. if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
  5130. {
  5131. const float NAV_RESIZE_SPEED = 600.0f;
  5132. nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
  5133. nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);
  5134. g.NavWindowingToggleLayer = false;
  5135. g.NavDisableMouseHover = true;
  5136. resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
  5137. // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
  5138. size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
  5139. }
  5140. }
  5141. // Apply back modified position/size to window
  5142. if (size_target.x != FLT_MAX)
  5143. {
  5144. window->SizeFull = size_target;
  5145. MarkIniSettingsDirty(window);
  5146. }
  5147. if (pos_target.x != FLT_MAX)
  5148. {
  5149. window->Pos = ImFloor(pos_target);
  5150. MarkIniSettingsDirty(window);
  5151. }
  5152. window->Size = window->SizeFull;
  5153. return ret_auto_fit;
  5154. }
  5155. static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)
  5156. {
  5157. ImGuiContext& g = *GImGui;
  5158. ImVec2 size_for_clamping = window->Size;
  5159. if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5160. size_for_clamping.y = window->TitleBarHeight();
  5161. window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
  5162. }
  5163. static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
  5164. {
  5165. ImGuiContext& g = *GImGui;
  5166. float rounding = window->WindowRounding;
  5167. float border_size = window->WindowBorderSize;
  5168. if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
  5169. window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
  5170. int border_held = window->ResizeBorderHeld;
  5171. if (border_held != -1)
  5172. {
  5173. const ImGuiResizeBorderDef& def = resize_border_def[border_held];
  5174. ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
  5175. 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);
  5176. 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);
  5177. window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
  5178. }
  5179. if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
  5180. {
  5181. float y = window->Pos.y + window->TitleBarHeight() - 1;
  5182. 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);
  5183. }
  5184. }
  5185. // Draw background and borders
  5186. // Draw and handle scrollbars
  5187. void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
  5188. {
  5189. ImGuiContext& g = *GImGui;
  5190. ImGuiStyle& style = g.Style;
  5191. ImGuiWindowFlags flags = window->Flags;
  5192. // Ensure that ScrollBar doesn't read last frame's SkipItems
  5193. IM_ASSERT(window->BeginCount == 0);
  5194. window->SkipItems = false;
  5195. // Draw window + handle manual resize
  5196. // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
  5197. const float window_rounding = window->WindowRounding;
  5198. const float window_border_size = window->WindowBorderSize;
  5199. if (window->Collapsed)
  5200. {
  5201. // Title bar only
  5202. float backup_border_size = style.FrameBorderSize;
  5203. g.Style.FrameBorderSize = window->WindowBorderSize;
  5204. ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
  5205. RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
  5206. g.Style.FrameBorderSize = backup_border_size;
  5207. }
  5208. else
  5209. {
  5210. // Window background
  5211. if (!(flags & ImGuiWindowFlags_NoBackground))
  5212. {
  5213. bool is_docking_transparent_payload = false;
  5214. if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
  5215. if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
  5216. is_docking_transparent_payload = true;
  5217. ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
  5218. if (window->ViewportOwned)
  5219. {
  5220. // No alpha
  5221. bg_col = (bg_col | IM_COL32_A_MASK);
  5222. if (is_docking_transparent_payload)
  5223. window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
  5224. }
  5225. else
  5226. {
  5227. // Adjust alpha. For docking
  5228. bool override_alpha = false;
  5229. float alpha = 1.0f;
  5230. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
  5231. {
  5232. alpha = g.NextWindowData.BgAlphaVal;
  5233. override_alpha = true;
  5234. }
  5235. if (is_docking_transparent_payload)
  5236. {
  5237. alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
  5238. override_alpha = true;
  5239. }
  5240. if (override_alpha)
  5241. bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
  5242. }
  5243. window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
  5244. }
  5245. // Title bar
  5246. // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
  5247. // in order for their pos/size to be matching their undocking state.)
  5248. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
  5249. {
  5250. ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  5251. window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
  5252. }
  5253. // Menu bar
  5254. if (flags & ImGuiWindowFlags_MenuBar)
  5255. {
  5256. ImRect menu_bar_rect = window->MenuBarRect();
  5257. 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.
  5258. 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);
  5259. if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
  5260. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  5261. }
  5262. // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
  5263. ImGuiDockNode* node = window->DockNode;
  5264. if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
  5265. {
  5266. float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
  5267. float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
  5268. ImVec2 p = node->Pos;
  5269. ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
  5270. bool hovered, held;
  5271. if (ButtonBehavior(r, window->GetID("#UNHIDE"), &hovered, &held, ImGuiButtonFlags_FlattenChildren))
  5272. node->WantHiddenTabBarToggle = true;
  5273. else if (held && IsMouseDragging(0))
  5274. StartMouseMovingWindowOrNode(window, node, true);
  5275. // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
  5276. ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5277. window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
  5278. }
  5279. // Scrollbars
  5280. if (window->ScrollbarX)
  5281. Scrollbar(ImGuiAxis_X);
  5282. if (window->ScrollbarY)
  5283. Scrollbar(ImGuiAxis_Y);
  5284. // Render resize grips (after their input handling so we don't have a frame of latency)
  5285. if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
  5286. {
  5287. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5288. {
  5289. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  5290. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
  5291. 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)));
  5292. 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)));
  5293. 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);
  5294. window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
  5295. }
  5296. }
  5297. // Borders (for dock node host they will be rendered over after the tab bar)
  5298. if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
  5299. RenderWindowOuterBorders(window);
  5300. }
  5301. }
  5302. // Render title text, collapse button, close button
  5303. // When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
  5304. void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
  5305. {
  5306. ImGuiContext& g = *GImGui;
  5307. ImGuiStyle& style = g.Style;
  5308. ImGuiWindowFlags flags = window->Flags;
  5309. const bool has_close_button = (p_open != NULL);
  5310. const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
  5311. // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
  5312. const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
  5313. g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
  5314. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  5315. // Layout buttons
  5316. // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
  5317. float pad_l = style.FramePadding.x;
  5318. float pad_r = style.FramePadding.x;
  5319. float button_sz = g.FontSize;
  5320. ImVec2 close_button_pos;
  5321. ImVec2 collapse_button_pos;
  5322. if (has_close_button)
  5323. {
  5324. pad_r += button_sz;
  5325. close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5326. }
  5327. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
  5328. {
  5329. pad_r += button_sz;
  5330. collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5331. }
  5332. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
  5333. {
  5334. collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
  5335. pad_l += button_sz;
  5336. }
  5337. // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
  5338. if (has_collapse_button)
  5339. if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
  5340. window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
  5341. // Close button
  5342. if (has_close_button)
  5343. if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
  5344. *p_open = false;
  5345. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5346. g.CurrentItemFlags = item_flags_backup;
  5347. // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
  5348. // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
  5349. const char* UNSAVED_DOCUMENT_MARKER = "*";
  5350. const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
  5351. const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
  5352. // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
  5353. // while uncentered title text will still reach edges correctly.
  5354. if (pad_l > style.FramePadding.x)
  5355. pad_l += g.Style.ItemInnerSpacing.x;
  5356. if (pad_r > style.FramePadding.x)
  5357. pad_r += g.Style.ItemInnerSpacing.x;
  5358. if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
  5359. {
  5360. float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
  5361. float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
  5362. pad_l = ImMax(pad_l, pad_extend * centerness);
  5363. pad_r = ImMax(pad_r, pad_extend * centerness);
  5364. }
  5365. 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);
  5366. 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);
  5367. //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
  5368. //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
  5369. RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
  5370. if (flags & ImGuiWindowFlags_UnsavedDocument)
  5371. {
  5372. ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
  5373. ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f));
  5374. RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
  5375. }
  5376. }
  5377. void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
  5378. {
  5379. window->ParentWindow = parent_window;
  5380. window->RootWindow = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
  5381. if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  5382. {
  5383. window->RootWindowDockTree = parent_window->RootWindowDockTree;
  5384. if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
  5385. window->RootWindow = parent_window->RootWindow;
  5386. }
  5387. if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  5388. window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
  5389. while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
  5390. {
  5391. IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
  5392. window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
  5393. }
  5394. }
  5395. // Push a new Dear ImGui window to add widgets to.
  5396. // - 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.
  5397. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  5398. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  5399. // 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.
  5400. // - 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.
  5401. // - 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.
  5402. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  5403. {
  5404. ImGuiContext& g = *GImGui;
  5405. const ImGuiStyle& style = g.Style;
  5406. IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
  5407. IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
  5408. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  5409. // Find or create
  5410. ImGuiWindow* window = FindWindowByName(name);
  5411. const bool window_just_created = (window == NULL);
  5412. if (window_just_created)
  5413. window = CreateNewWindow(name, flags);
  5414. // Automatically disable manual moving/resizing when NoInputs is set
  5415. if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
  5416. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  5417. if (flags & ImGuiWindowFlags_NavFlattened)
  5418. IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
  5419. const int current_frame = g.FrameCount;
  5420. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  5421. window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
  5422. // Update the Appearing flag
  5423. bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  5424. if (flags & ImGuiWindowFlags_Popup)
  5425. {
  5426. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5427. window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
  5428. window_just_activated_by_user |= (window != popup_ref.Window);
  5429. }
  5430. window->Appearing = window_just_activated_by_user;
  5431. if (window->Appearing)
  5432. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
  5433. // Update Flags, LastFrameActive, BeginOrderXXX fields
  5434. if (first_begin_of_the_frame)
  5435. {
  5436. window->FlagsPreviousFrame = window->Flags;
  5437. window->Flags = (ImGuiWindowFlags)flags;
  5438. window->LastFrameActive = current_frame;
  5439. window->LastTimeActive = (float)g.Time;
  5440. window->BeginOrderWithinParent = 0;
  5441. window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
  5442. }
  5443. else
  5444. {
  5445. flags = window->Flags;
  5446. }
  5447. // Docking
  5448. // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
  5449. IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
  5450. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
  5451. SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
  5452. if (first_begin_of_the_frame)
  5453. {
  5454. bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
  5455. bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
  5456. if (has_dock_node || new_auto_dock_node)
  5457. {
  5458. BeginDocked(window, p_open);
  5459. flags = window->Flags;
  5460. if (window->DockIsActive)
  5461. IM_ASSERT(window->DockNode != NULL);
  5462. // Docking currently override constraints
  5463. g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint;
  5464. }
  5465. }
  5466. // 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
  5467. ImGuiWindow* parent_window_in_stack = window->DockIsActive ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
  5468. ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
  5469. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  5470. // We allow window memory to be compacted so recreate the base stack when needed.
  5471. if (window->IDStack.Size == 0)
  5472. window->IDStack.push_back(window->ID);
  5473. // Add to stack
  5474. // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
  5475. g.CurrentWindowStack.push_back(window);
  5476. g.CurrentWindow = window;
  5477. window->DC.StackSizesOnBegin.SetToCurrentState();
  5478. g.CurrentWindow = NULL;
  5479. if (flags & ImGuiWindowFlags_Popup)
  5480. {
  5481. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5482. popup_ref.Window = window;
  5483. g.BeginPopupStack.push_back(popup_ref);
  5484. window->PopupId = popup_ref.PopupId;
  5485. }
  5486. // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
  5487. if (first_begin_of_the_frame)
  5488. UpdateWindowParentAndRootLinks(window, flags, parent_window);
  5489. // Process SetNextWindow***() calls
  5490. // (FIXME: Consider splitting the HasXXX flags into X/Y components
  5491. bool window_pos_set_by_api = false;
  5492. bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
  5493. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
  5494. {
  5495. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
  5496. if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
  5497. {
  5498. // May be processed on the next frame if this is our first frame and we are measuring size
  5499. // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
  5500. window->SetWindowPosVal = g.NextWindowData.PosVal;
  5501. window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
  5502. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5503. }
  5504. else
  5505. {
  5506. SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
  5507. }
  5508. }
  5509. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
  5510. {
  5511. window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
  5512. window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
  5513. SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
  5514. }
  5515. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
  5516. {
  5517. if (g.NextWindowData.ScrollVal.x >= 0.0f)
  5518. {
  5519. window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
  5520. window->ScrollTargetCenterRatio.x = 0.0f;
  5521. }
  5522. if (g.NextWindowData.ScrollVal.y >= 0.0f)
  5523. {
  5524. window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
  5525. window->ScrollTargetCenterRatio.y = 0.0f;
  5526. }
  5527. }
  5528. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
  5529. window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
  5530. else if (first_begin_of_the_frame)
  5531. window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
  5532. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
  5533. window->WindowClass = g.NextWindowData.WindowClass;
  5534. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
  5535. SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
  5536. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
  5537. FocusWindow(window);
  5538. if (window->Appearing)
  5539. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
  5540. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  5541. if (first_begin_of_the_frame)
  5542. {
  5543. // Initialize
  5544. const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
  5545. window->Active = true;
  5546. window->HasCloseButton = (p_open != NULL);
  5547. window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
  5548. window->IDStack.resize(1);
  5549. window->DrawList->_ResetForNewFrame();
  5550. window->DC.CurrentTableIdx = -1;
  5551. // Restore buffer capacity when woken from a compacted state, to avoid
  5552. if (window->MemoryCompacted)
  5553. GcAwakeTransientWindowBuffers(window);
  5554. // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
  5555. // 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.
  5556. bool window_title_visible_elsewhere = false;
  5557. if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
  5558. window_title_visible_elsewhere = true;
  5559. else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
  5560. window_title_visible_elsewhere = true;
  5561. if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
  5562. {
  5563. size_t buf_len = (size_t)window->NameBufLen;
  5564. window->Name = ImStrdupcpy(window->Name, &buf_len, name);
  5565. window->NameBufLen = (int)buf_len;
  5566. }
  5567. // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
  5568. // Update contents size from last frame for auto-fitting (or use explicit size)
  5569. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
  5570. CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
  5571. // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
  5572. // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
  5573. // it has a single usage before this code block and may be set below before it is finally checked.
  5574. if (window->HiddenFramesCanSkipItems > 0)
  5575. window->HiddenFramesCanSkipItems--;
  5576. if (window->HiddenFramesCannotSkipItems > 0)
  5577. window->HiddenFramesCannotSkipItems--;
  5578. if (window->HiddenFramesForRenderOnly > 0)
  5579. window->HiddenFramesForRenderOnly--;
  5580. // Hide new windows for one frame until they calculate their size
  5581. if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
  5582. window->HiddenFramesCannotSkipItems = 1;
  5583. // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
  5584. // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
  5585. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
  5586. {
  5587. window->HiddenFramesCannotSkipItems = 1;
  5588. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  5589. {
  5590. if (!window_size_x_set_by_api)
  5591. window->Size.x = window->SizeFull.x = 0.f;
  5592. if (!window_size_y_set_by_api)
  5593. window->Size.y = window->SizeFull.y = 0.f;
  5594. window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
  5595. }
  5596. }
  5597. // SELECT VIEWPORT
  5598. // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
  5599. UpdateSelectWindowViewport(window);
  5600. SetCurrentViewport(window, window->Viewport);
  5601. window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
  5602. SetCurrentWindow(window);
  5603. flags = window->Flags;
  5604. // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
  5605. // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
  5606. if (flags & ImGuiWindowFlags_ChildWindow)
  5607. window->WindowBorderSize = style.ChildBorderSize;
  5608. else
  5609. window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
  5610. if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
  5611. window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
  5612. else
  5613. window->WindowPadding = style.WindowPadding;
  5614. // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
  5615. window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
  5616. window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
  5617. // Collapse window by double-clicking on title bar
  5618. // 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
  5619. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
  5620. {
  5621. // 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.
  5622. ImRect title_bar_rect = window->TitleBarRect();
  5623. if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
  5624. window->WantCollapseToggle = true;
  5625. if (window->WantCollapseToggle)
  5626. {
  5627. window->Collapsed = !window->Collapsed;
  5628. MarkIniSettingsDirty(window);
  5629. }
  5630. }
  5631. else
  5632. {
  5633. window->Collapsed = false;
  5634. }
  5635. window->WantCollapseToggle = false;
  5636. // SIZE
  5637. // Calculate auto-fit size, handle automatic resize
  5638. const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
  5639. bool use_current_size_for_scrollbar_x = window_just_created;
  5640. bool use_current_size_for_scrollbar_y = window_just_created;
  5641. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
  5642. {
  5643. // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
  5644. if (!window_size_x_set_by_api)
  5645. {
  5646. window->SizeFull.x = size_auto_fit.x;
  5647. use_current_size_for_scrollbar_x = true;
  5648. }
  5649. if (!window_size_y_set_by_api)
  5650. {
  5651. window->SizeFull.y = size_auto_fit.y;
  5652. use_current_size_for_scrollbar_y = true;
  5653. }
  5654. }
  5655. else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5656. {
  5657. // Auto-fit may only grow window during the first few frames
  5658. // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  5659. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
  5660. {
  5661. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  5662. use_current_size_for_scrollbar_x = true;
  5663. }
  5664. if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
  5665. {
  5666. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  5667. use_current_size_for_scrollbar_y = true;
  5668. }
  5669. if (!window->Collapsed)
  5670. MarkIniSettingsDirty(window);
  5671. }
  5672. // Apply minimum/maximum window size constraints and final size
  5673. window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
  5674. window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
  5675. // Decoration size
  5676. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  5677. // POSITION
  5678. // Popup latch its initial position, will position itself when it appears next frame
  5679. if (window_just_activated_by_user)
  5680. {
  5681. window->AutoPosLastDirection = ImGuiDir_None;
  5682. if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
  5683. window->Pos = g.BeginPopupStack.back().OpenPopupPos;
  5684. }
  5685. // Position child window
  5686. if (flags & ImGuiWindowFlags_ChildWindow)
  5687. {
  5688. IM_ASSERT(parent_window && parent_window->Active);
  5689. window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
  5690. parent_window->DC.ChildWindows.push_back(window);
  5691. if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
  5692. window->Pos = parent_window->DC.CursorPos;
  5693. }
  5694. const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
  5695. if (window_pos_with_pivot)
  5696. SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
  5697. else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
  5698. window->Pos = FindBestWindowPosForPopup(window);
  5699. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
  5700. window->Pos = FindBestWindowPosForPopup(window);
  5701. else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
  5702. window->Pos = FindBestWindowPosForPopup(window);
  5703. // Late create viewport if we don't fit within our current host viewport.
  5704. if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
  5705. if (!window->Viewport->GetMainRect().Contains(window->Rect()))
  5706. {
  5707. // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
  5708. //ImGuiViewport* old_viewport = window->Viewport;
  5709. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
  5710. // FIXME-DPI
  5711. //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
  5712. SetCurrentViewport(window, window->Viewport);
  5713. window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
  5714. SetCurrentWindow(window);
  5715. }
  5716. bool viewport_rect_changed = false;
  5717. if (window->ViewportOwned)
  5718. {
  5719. // Synchronize window --> viewport in most situations
  5720. // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
  5721. if (window->Viewport->PlatformRequestMove)
  5722. {
  5723. window->Pos = window->Viewport->Pos;
  5724. MarkIniSettingsDirty(window);
  5725. }
  5726. else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
  5727. {
  5728. viewport_rect_changed = true;
  5729. window->Viewport->Pos = window->Pos;
  5730. }
  5731. if (window->Viewport->PlatformRequestResize)
  5732. {
  5733. window->Size = window->SizeFull = window->Viewport->Size;
  5734. MarkIniSettingsDirty(window);
  5735. }
  5736. else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
  5737. {
  5738. viewport_rect_changed = true;
  5739. window->Viewport->Size = window->Size;
  5740. }
  5741. window->Viewport->UpdateWorkRect();
  5742. // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
  5743. // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
  5744. if (viewport_rect_changed)
  5745. UpdateViewportPlatformMonitor(window->Viewport);
  5746. // Update common viewport flags
  5747. const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
  5748. ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
  5749. const bool is_modal = (flags & ImGuiWindowFlags_Modal) != 0;
  5750. const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
  5751. if (flags & ImGuiWindowFlags_Tooltip)
  5752. viewport_flags |= ImGuiViewportFlags_TopMost;
  5753. if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
  5754. viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
  5755. if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
  5756. viewport_flags |= ImGuiViewportFlags_NoDecoration;
  5757. // Not correct to set modal as topmost because:
  5758. // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
  5759. // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
  5760. //if (flags & ImGuiWindowFlags_Modal)
  5761. // viewport_flags |= ImGuiViewportFlags_TopMost;
  5762. // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
  5763. // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
  5764. // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
  5765. // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
  5766. if (is_short_lived_floating_window && !is_modal)
  5767. viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
  5768. // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
  5769. // We don't default to the main viewport because.
  5770. if (window->WindowClass.ParentViewportId)
  5771. window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
  5772. else if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack)
  5773. window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
  5774. else
  5775. window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
  5776. if (window->WindowClass.ViewportFlagsOverrideSet)
  5777. viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
  5778. if (window->WindowClass.ViewportFlagsOverrideClear)
  5779. viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
  5780. // We can also tell the backend that clearing the platform window won't be necessary,
  5781. // as our window background is filling the viewport and we have disabled BgAlpha.
  5782. // FIXME: Work on support for per-viewport transparency (#2766)
  5783. if (!(flags & ImGuiWindowFlags_NoBackground))
  5784. viewport_flags |= ImGuiViewportFlags_NoRendererClear;
  5785. window->Viewport->Flags = viewport_flags;
  5786. }
  5787. // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
  5788. // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
  5789. ImRect viewport_rect(window->Viewport->GetMainRect());
  5790. ImRect viewport_work_rect(window->Viewport->GetWorkRect());
  5791. ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  5792. ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
  5793. // Clamp position/size so window stays visible within its viewport or monitor
  5794. // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
  5795. // FIXME: Similar to code in GetWindowAllowedExtentRect()
  5796. if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  5797. {
  5798. if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
  5799. {
  5800. ClampWindowRect(window, visibility_rect);
  5801. }
  5802. else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
  5803. {
  5804. // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
  5805. const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
  5806. visibility_rect.Min = monitor->WorkPos + visibility_padding;
  5807. visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
  5808. ClampWindowRect(window, visibility_rect);
  5809. }
  5810. }
  5811. window->Pos = ImFloor(window->Pos);
  5812. // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
  5813. // Large values tend to lead to variety of artifacts and are not recommended.
  5814. if (window->ViewportOwned || window->DockIsActive)
  5815. window->WindowRounding = 0.0f;
  5816. else
  5817. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
  5818. // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
  5819. //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5820. // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
  5821. // Apply window focus (new and reactivated windows are moved to front)
  5822. bool want_focus = false;
  5823. if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  5824. {
  5825. if (flags & ImGuiWindowFlags_Popup)
  5826. want_focus = true;
  5827. else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
  5828. want_focus = true;
  5829. }
  5830. // Decide if we are going to handle borders and resize grips
  5831. const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
  5832. // Handle manual resize: Resize Grips, Borders, Gamepad
  5833. int border_held = -1;
  5834. ImU32 resize_grip_col[4] = {};
  5835. const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
  5836. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  5837. if (handle_borders_and_resize_grips && !window->Collapsed)
  5838. if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
  5839. use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
  5840. window->ResizeBorderHeld = (signed char)border_held;
  5841. // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
  5842. if (window->ViewportOwned)
  5843. {
  5844. if (!window->Viewport->PlatformRequestMove)
  5845. window->Viewport->Pos = window->Pos;
  5846. if (!window->Viewport->PlatformRequestResize)
  5847. window->Viewport->Size = window->Size;
  5848. window->Viewport->UpdateWorkRect();
  5849. viewport_rect = window->Viewport->GetMainRect();
  5850. }
  5851. // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
  5852. window->ViewportPos = window->Viewport->Pos;
  5853. // SCROLLBAR VISIBILITY
  5854. // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
  5855. if (!window->Collapsed)
  5856. {
  5857. // When reading the current size we need to read it after size constraints have been applied.
  5858. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
  5859. ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
  5860. ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
  5861. ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
  5862. float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
  5863. float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
  5864. //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
  5865. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
  5866. 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));
  5867. if (window->ScrollbarX && !window->ScrollbarY)
  5868. window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
  5869. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  5870. }
  5871. // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
  5872. // Update various regions. Variables they depends on should be set above in this function.
  5873. // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
  5874. // Outer rectangle
  5875. // Not affected by window border size. Used by:
  5876. // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
  5877. // - Begin() initial clipping rect for drawing window background and borders.
  5878. // - Begin() clipping whole child
  5879. const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
  5880. const ImRect outer_rect = window->Rect();
  5881. const ImRect title_bar_rect = window->TitleBarRect();
  5882. window->OuterRectClipped = outer_rect;
  5883. if (window->DockIsActive)
  5884. window->OuterRectClipped.Min.y += window->TitleBarHeight();
  5885. window->OuterRectClipped.ClipWith(host_rect);
  5886. // Inner rectangle
  5887. // Not affected by window border size. Used by:
  5888. // - InnerClipRect
  5889. // - ScrollToBringRectIntoView()
  5890. // - NavUpdatePageUpPageDown()
  5891. // - Scrollbar()
  5892. window->InnerRect.Min.x = window->Pos.x;
  5893. window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
  5894. window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
  5895. window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
  5896. // Inner clipping rectangle.
  5897. // Will extend a little bit outside the normal work region.
  5898. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
  5899. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  5900. // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
  5901. // Affected by window/frame border size. Used by:
  5902. // - Begin() initial clip rect
  5903. float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
  5904. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5905. window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
  5906. window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5907. window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
  5908. window->InnerClipRect.ClipWithFull(host_rect);
  5909. // Default item width. Make it proportional to window size if window manually resizes
  5910. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  5911. window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
  5912. else
  5913. window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
  5914. // SCROLLING
  5915. // Lock down maximum scrolling
  5916. // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
  5917. // for right/bottom aligned items without creating a scrollbar.
  5918. window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
  5919. window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
  5920. // Apply scrolling
  5921. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  5922. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  5923. // DRAWING
  5924. // Setup draw list and outer clipping rectangle
  5925. IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
  5926. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  5927. PushClipRect(host_rect.Min, host_rect.Max, false);
  5928. // Draw modal or window list full viewport dimming background (for other viewports we'll render them in EndFrame)
  5929. ImGuiWindow* window_window_list = g.NavWindowingListWindow;
  5930. const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
  5931. const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && ((window == g.NavWindowingTargetAnim->RootWindowDockTree) || (window == window_window_list && window_window_list->Viewport != g.NavWindowingTargetAnim->Viewport));
  5932. if (dim_bg_for_modal || dim_bg_for_window_list)
  5933. {
  5934. const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
  5935. window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
  5936. }
  5937. // Draw navigation selection/windowing rectangle background
  5938. if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
  5939. {
  5940. ImRect bb = window->Rect();
  5941. bb.Expand(g.FontSize);
  5942. if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
  5943. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
  5944. }
  5945. // Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
  5946. // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
  5947. // We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
  5948. // We also disabled this when we have dimming overlay behind this specific one child.
  5949. // FIXME: More 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.
  5950. const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
  5951. if (is_undocked_or_docked_visible)
  5952. {
  5953. bool render_decorations_in_parent = false;
  5954. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
  5955. if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
  5956. render_decorations_in_parent = true;
  5957. if (render_decorations_in_parent)
  5958. window->DrawList = parent_window->DrawList;
  5959. // Handle title bar, scrollbar, resize grips and resize borders
  5960. const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
  5961. const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
  5962. RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
  5963. if (render_decorations_in_parent)
  5964. window->DrawList = &window->DrawListInst;
  5965. }
  5966. // Draw navigation selection/windowing rectangle border
  5967. if (g.NavWindowingTargetAnim == window)
  5968. {
  5969. float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
  5970. ImRect bb = window->Rect();
  5971. bb.Expand(g.FontSize);
  5972. if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
  5973. {
  5974. bb.Expand(-g.FontSize - 1.0f);
  5975. rounding = window->WindowRounding;
  5976. }
  5977. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, 0, 3.0f);
  5978. }
  5979. // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
  5980. // Work rectangle.
  5981. // Affected by window padding and border size. Used by:
  5982. // - Columns() for right-most edge
  5983. // - TreeNode(), CollapsingHeader() for right-most edge
  5984. // - BeginTabBar() for right-most edge
  5985. const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
  5986. const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
  5987. 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));
  5988. 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));
  5989. window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
  5990. window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
  5991. window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
  5992. window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
  5993. window->ParentWorkRect = window->WorkRect;
  5994. // [LEGACY] Content Region
  5995. // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
  5996. // Used by:
  5997. // - Mouse wheel scrolling + many other things
  5998. window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
  5999. window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
  6000. 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));
  6001. 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));
  6002. // Setup drawing context
  6003. // (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.)
  6004. window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
  6005. window->DC.GroupOffset.x = 0.0f;
  6006. window->DC.ColumnsOffset.x = 0.0f;
  6007. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
  6008. window->DC.CursorPos = window->DC.CursorStartPos;
  6009. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  6010. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  6011. window->DC.IdealMaxPos = window->DC.CursorStartPos;
  6012. window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
  6013. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  6014. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  6015. window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
  6016. window->DC.NavLayersActiveMaskNext = 0x00;
  6017. window->DC.NavHideHighlightOneFrame = false;
  6018. window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
  6019. window->DC.MenuBarAppending = false;
  6020. window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
  6021. window->DC.TreeDepth = 0;
  6022. window->DC.TreeJumpToParentOnPopMask = 0x00;
  6023. window->DC.ChildWindows.resize(0);
  6024. window->DC.StateStorage = &window->StateStorage;
  6025. window->DC.CurrentColumns = NULL;
  6026. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  6027. window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
  6028. window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
  6029. window->DC.ItemWidth = window->ItemWidthDefault;
  6030. window->DC.TextWrapPos = -1.0f; // disabled
  6031. window->DC.ItemWidthStack.resize(0);
  6032. window->DC.TextWrapPosStack.resize(0);
  6033. if (window->AutoFitFramesX > 0)
  6034. window->AutoFitFramesX--;
  6035. if (window->AutoFitFramesY > 0)
  6036. window->AutoFitFramesY--;
  6037. // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  6038. if (want_focus)
  6039. {
  6040. FocusWindow(window);
  6041. NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
  6042. }
  6043. // Close requested by platform window
  6044. if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
  6045. {
  6046. if (!window->DockIsActive || window->DockTabIsVisible)
  6047. {
  6048. window->Viewport->PlatformRequestClose = false;
  6049. g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
  6050. IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' PlatformRequestClose\n", window->Name);
  6051. *p_open = false;
  6052. }
  6053. }
  6054. // Title bar
  6055. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
  6056. 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);
  6057. // Clear hit test shape every frame
  6058. window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
  6059. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  6060. // 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.
  6061. // Maybe we can support CTRL+C on every element?
  6062. /*
  6063. //if (g.NavWindow == window && g.ActiveId == 0)
  6064. if (g.ActiveId == window->MoveId)
  6065. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  6066. LogToClipboard();
  6067. */
  6068. if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
  6069. {
  6070. // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
  6071. // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
  6072. if (g.MovingWindow == window && g.IO.KeyShift == false)
  6073. if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
  6074. BeginDockableDragDropSource(window);
  6075. // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
  6076. if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
  6077. if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
  6078. if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
  6079. BeginDockableDragDropTarget(window);
  6080. }
  6081. // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
  6082. // This is useful to allow creating context menus on title bar only, etc.
  6083. if (window->DockIsActive)
  6084. SetLastItemData(window, window->ID, window->DockTabItemStatusFlags, window->DockTabItemRect);
  6085. else
  6086. SetLastItemData(window, window->MoveId, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
  6087. #ifdef IMGUI_ENABLE_TEST_ENGINE
  6088. if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
  6089. IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
  6090. #endif
  6091. }
  6092. else
  6093. {
  6094. // Append
  6095. SetCurrentViewport(window, window->Viewport);
  6096. SetCurrentWindow(window);
  6097. }
  6098. // Pull/inherit current state
  6099. g.CurrentItemFlags = g.ItemFlagsStack.back(); // Inherit from shared stack
  6100. window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // Inherit from parent only // -V595
  6101. if (!(flags & ImGuiWindowFlags_DockNodeHost))
  6102. PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
  6103. // 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)
  6104. window->WriteAccessed = false;
  6105. window->BeginCount++;
  6106. g.NextWindowData.ClearFlags();
  6107. // Update visibility
  6108. if (first_begin_of_the_frame)
  6109. {
  6110. // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
  6111. // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
  6112. // This is analogous to regular windows being hidden from one frame.
  6113. // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
  6114. if (window->DockIsActive && !window->DockTabIsVisible)
  6115. {
  6116. if (window->LastFrameJustFocused == g.FrameCount)
  6117. window->HiddenFramesCannotSkipItems = 1;
  6118. else
  6119. window->HiddenFramesCanSkipItems = 1;
  6120. }
  6121. if (flags & ImGuiWindowFlags_ChildWindow)
  6122. {
  6123. // Child window can be out of sight and have "negative" clip windows.
  6124. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
  6125. IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
  6126. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
  6127. if (!g.LogEnabled)
  6128. if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
  6129. window->HiddenFramesCanSkipItems = 1;
  6130. // Hide along with parent or if parent is collapsed
  6131. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
  6132. window->HiddenFramesCanSkipItems = 1;
  6133. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
  6134. window->HiddenFramesCannotSkipItems = 1;
  6135. }
  6136. // 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)
  6137. if (style.Alpha <= 0.0f)
  6138. window->HiddenFramesCanSkipItems = 1;
  6139. // Update the Hidden flag
  6140. window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0) || (window->HiddenFramesForRenderOnly > 0);
  6141. // Disable inputs for requested number of frames
  6142. if (window->DisableInputsFrames > 0)
  6143. {
  6144. window->DisableInputsFrames--;
  6145. window->Flags |= ImGuiWindowFlags_NoInputs;
  6146. }
  6147. // Update the SkipItems flag, used to early out of all items functions (no layout required)
  6148. bool skip_items = false;
  6149. if (window->Collapsed || !window->Active || window->Hidden)
  6150. if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
  6151. skip_items = true;
  6152. window->SkipItems = skip_items;
  6153. }
  6154. return !window->SkipItems;
  6155. }
  6156. void ImGui::End()
  6157. {
  6158. ImGuiContext& g = *GImGui;
  6159. ImGuiWindow* window = g.CurrentWindow;
  6160. // Error checking: verify that user hasn't called End() too many times!
  6161. if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
  6162. {
  6163. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
  6164. return;
  6165. }
  6166. IM_ASSERT(g.CurrentWindowStack.Size > 0);
  6167. // Error checking: verify that user doesn't directly call End() on a child window.
  6168. if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
  6169. IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
  6170. // Close anything that is open
  6171. if (window->DC.CurrentColumns)
  6172. EndColumns();
  6173. if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle
  6174. PopClipRect();
  6175. // Stop logging
  6176. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  6177. LogFinish();
  6178. // Docking: report contents sizes to parent to allow for auto-resize
  6179. if (window->DockNode && window->DockTabIsVisible)
  6180. if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
  6181. host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
  6182. // Pop from window stack
  6183. g.CurrentWindowStack.pop_back();
  6184. if (window->Flags & ImGuiWindowFlags_Popup)
  6185. g.BeginPopupStack.pop_back();
  6186. window->DC.StackSizesOnBegin.CompareWithCurrentState();
  6187. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  6188. if (g.CurrentWindow)
  6189. SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
  6190. }
  6191. void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
  6192. {
  6193. ImGuiContext& g = *GImGui;
  6194. IM_ASSERT(window == window->RootWindow);
  6195. const int cur_order = window->FocusOrder;
  6196. IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
  6197. if (g.WindowsFocusOrder.back() == window)
  6198. return;
  6199. const int new_order = g.WindowsFocusOrder.Size - 1;
  6200. for (int n = cur_order; n < new_order; n++)
  6201. {
  6202. g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
  6203. g.WindowsFocusOrder[n]->FocusOrder--;
  6204. IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
  6205. }
  6206. g.WindowsFocusOrder[new_order] = window;
  6207. window->FocusOrder = (short)new_order;
  6208. }
  6209. void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
  6210. {
  6211. ImGuiContext& g = *GImGui;
  6212. ImGuiWindow* current_front_window = g.Windows.back();
  6213. if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
  6214. return;
  6215. for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
  6216. if (g.Windows[i] == window)
  6217. {
  6218. memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
  6219. g.Windows[g.Windows.Size - 1] = window;
  6220. break;
  6221. }
  6222. }
  6223. void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
  6224. {
  6225. ImGuiContext& g = *GImGui;
  6226. if (g.Windows[0] == window)
  6227. return;
  6228. for (int i = 0; i < g.Windows.Size; i++)
  6229. if (g.Windows[i] == window)
  6230. {
  6231. memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
  6232. g.Windows[0] = window;
  6233. break;
  6234. }
  6235. }
  6236. // Moving window to front of display and set focus (which happens to be back of our sorted list)
  6237. void ImGui::FocusWindow(ImGuiWindow* window)
  6238. {
  6239. ImGuiContext& g = *GImGui;
  6240. if (g.NavWindow != window)
  6241. {
  6242. g.NavWindow = window;
  6243. if (window && g.NavDisableMouseHover)
  6244. g.NavMousePosDirty = true;
  6245. g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
  6246. g.NavFocusScopeId = 0;
  6247. g.NavIdIsAlive = false;
  6248. g.NavLayer = ImGuiNavLayer_Main;
  6249. g.NavInitRequest = g.NavMoveRequest = false;
  6250. NavUpdateAnyRequestFlag();
  6251. //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
  6252. }
  6253. // Close popups if any
  6254. ClosePopupsOverWindow(window, false);
  6255. // Move the root window to the top of the pile
  6256. IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
  6257. ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
  6258. ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
  6259. ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
  6260. bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
  6261. // Steal active widgets. Some of the cases it triggers includes:
  6262. // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
  6263. // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
  6264. // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
  6265. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
  6266. if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
  6267. ClearActiveID();
  6268. // Passing NULL allow to disable keyboard focus
  6269. if (!window)
  6270. return;
  6271. window->LastFrameJustFocused = g.FrameCount;
  6272. // Select in dock node
  6273. if (dock_node && dock_node->TabBar)
  6274. dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->ID;
  6275. // Bring to front
  6276. BringWindowToFocusFront(focus_front_window);
  6277. if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
  6278. BringWindowToDisplayFront(display_front_window);
  6279. }
  6280. void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
  6281. {
  6282. ImGuiContext& g = *GImGui;
  6283. const int start_idx = ((under_this_window != NULL) ? FindWindowFocusIndex(under_this_window) : g.WindowsFocusOrder.Size) - 1;
  6284. for (int i = start_idx; i >= 0; i--)
  6285. {
  6286. // 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.
  6287. ImGuiWindow* window = g.WindowsFocusOrder[i];
  6288. IM_ASSERT(window == window->RootWindow);
  6289. if (window != ignore_window && window->WasActive)
  6290. if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
  6291. {
  6292. // FIXME-DOCK: This is failing (lagging by one frame) for docked windows.
  6293. // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
  6294. // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
  6295. // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
  6296. ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
  6297. FocusWindow(focus_window);
  6298. return;
  6299. }
  6300. }
  6301. FocusWindow(NULL);
  6302. }
  6303. // Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
  6304. void ImGui::SetCurrentFont(ImFont* font)
  6305. {
  6306. ImGuiContext& g = *GImGui;
  6307. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  6308. IM_ASSERT(font->Scale > 0.0f);
  6309. g.Font = font;
  6310. g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
  6311. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  6312. ImFontAtlas* atlas = g.Font->ContainerAtlas;
  6313. g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
  6314. g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
  6315. g.DrawListSharedData.Font = g.Font;
  6316. g.DrawListSharedData.FontSize = g.FontSize;
  6317. }
  6318. void ImGui::PushFont(ImFont* font)
  6319. {
  6320. ImGuiContext& g = *GImGui;
  6321. if (!font)
  6322. font = GetDefaultFont();
  6323. SetCurrentFont(font);
  6324. g.FontStack.push_back(font);
  6325. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  6326. }
  6327. void ImGui::PopFont()
  6328. {
  6329. ImGuiContext& g = *GImGui;
  6330. g.CurrentWindow->DrawList->PopTextureID();
  6331. g.FontStack.pop_back();
  6332. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  6333. }
  6334. void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
  6335. {
  6336. ImGuiContext& g = *GImGui;
  6337. ImGuiItemFlags item_flags = g.CurrentItemFlags;
  6338. IM_ASSERT(item_flags == g.ItemFlagsStack.back());
  6339. if (enabled)
  6340. item_flags |= option;
  6341. else
  6342. item_flags &= ~option;
  6343. g.CurrentItemFlags = item_flags;
  6344. g.ItemFlagsStack.push_back(item_flags);
  6345. }
  6346. void ImGui::PopItemFlag()
  6347. {
  6348. ImGuiContext& g = *GImGui;
  6349. IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
  6350. g.ItemFlagsStack.pop_back();
  6351. g.CurrentItemFlags = g.ItemFlagsStack.back();
  6352. }
  6353. // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
  6354. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  6355. {
  6356. PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
  6357. }
  6358. void ImGui::PopAllowKeyboardFocus()
  6359. {
  6360. PopItemFlag();
  6361. }
  6362. void ImGui::PushButtonRepeat(bool repeat)
  6363. {
  6364. PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
  6365. }
  6366. void ImGui::PopButtonRepeat()
  6367. {
  6368. PopItemFlag();
  6369. }
  6370. void ImGui::PushTextWrapPos(float wrap_pos_x)
  6371. {
  6372. ImGuiWindow* window = GetCurrentWindow();
  6373. window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
  6374. window->DC.TextWrapPos = wrap_pos_x;
  6375. }
  6376. void ImGui::PopTextWrapPos()
  6377. {
  6378. ImGuiWindow* window = GetCurrentWindow();
  6379. window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
  6380. window->DC.TextWrapPosStack.pop_back();
  6381. }
  6382. bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
  6383. {
  6384. if (window->RootWindowDockTree == potential_parent)
  6385. return true;
  6386. while (window != NULL)
  6387. {
  6388. if (window == potential_parent)
  6389. return true;
  6390. window = window->ParentWindow;
  6391. }
  6392. return false;
  6393. }
  6394. bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
  6395. {
  6396. ImGuiContext& g = *GImGui;
  6397. for (int i = g.Windows.Size - 1; i >= 0; i--)
  6398. {
  6399. ImGuiWindow* candidate_window = g.Windows[i];
  6400. if (candidate_window == potential_above)
  6401. return true;
  6402. if (candidate_window == potential_below)
  6403. return false;
  6404. }
  6405. return false;
  6406. }
  6407. bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
  6408. {
  6409. IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
  6410. ImGuiContext& g = *GImGui;
  6411. if (g.HoveredWindow == NULL)
  6412. return false;
  6413. if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
  6414. {
  6415. ImGuiWindow* window = g.CurrentWindow;
  6416. switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
  6417. {
  6418. case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
  6419. if (g.HoveredWindow->RootWindow != window->RootWindow)
  6420. return false;
  6421. break;
  6422. case ImGuiHoveredFlags_RootWindow:
  6423. if (g.HoveredWindow != window->RootWindow)
  6424. return false;
  6425. break;
  6426. case ImGuiHoveredFlags_ChildWindows:
  6427. if (!IsWindowChildOf(g.HoveredWindow, window))
  6428. return false;
  6429. break;
  6430. default:
  6431. if (g.HoveredWindow != window)
  6432. return false;
  6433. break;
  6434. }
  6435. }
  6436. if (!IsWindowContentHoverable(g.HoveredWindow, flags))
  6437. return false;
  6438. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  6439. if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
  6440. return false;
  6441. return true;
  6442. }
  6443. bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
  6444. {
  6445. ImGuiContext& g = *GImGui;
  6446. if (flags & ImGuiFocusedFlags_AnyWindow)
  6447. return g.NavWindow != NULL;
  6448. IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
  6449. switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
  6450. {
  6451. case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
  6452. return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
  6453. case ImGuiFocusedFlags_RootWindow:
  6454. return g.NavWindow == g.CurrentWindow->RootWindow;
  6455. case ImGuiFocusedFlags_ChildWindows:
  6456. return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
  6457. default:
  6458. return g.NavWindow == g.CurrentWindow;
  6459. }
  6460. }
  6461. ImGuiID ImGui::GetWindowDockID()
  6462. {
  6463. ImGuiContext& g = *GImGui;
  6464. return g.CurrentWindow->DockId;
  6465. }
  6466. bool ImGui::IsWindowDocked()
  6467. {
  6468. ImGuiContext& g = *GImGui;
  6469. return g.CurrentWindow->DockIsActive;
  6470. }
  6471. // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
  6472. // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
  6473. // If you want a window to never be focused, you may use the e.g. NoInputs flag.
  6474. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
  6475. {
  6476. return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
  6477. }
  6478. float ImGui::GetWindowWidth()
  6479. {
  6480. ImGuiWindow* window = GImGui->CurrentWindow;
  6481. return window->Size.x;
  6482. }
  6483. float ImGui::GetWindowHeight()
  6484. {
  6485. ImGuiWindow* window = GImGui->CurrentWindow;
  6486. return window->Size.y;
  6487. }
  6488. ImVec2 ImGui::GetWindowPos()
  6489. {
  6490. ImGuiContext& g = *GImGui;
  6491. ImGuiWindow* window = g.CurrentWindow;
  6492. return window->Pos;
  6493. }
  6494. void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  6495. {
  6496. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6497. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  6498. return;
  6499. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6500. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6501. window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
  6502. // Set
  6503. const ImVec2 old_pos = window->Pos;
  6504. window->Pos = ImFloor(pos);
  6505. ImVec2 offset = window->Pos - old_pos;
  6506. 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
  6507. window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
  6508. window->DC.IdealMaxPos += offset;
  6509. window->DC.CursorStartPos += offset;
  6510. }
  6511. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  6512. {
  6513. ImGuiWindow* window = GetCurrentWindowRead();
  6514. SetWindowPos(window, pos, cond);
  6515. }
  6516. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  6517. {
  6518. if (ImGuiWindow* window = FindWindowByName(name))
  6519. SetWindowPos(window, pos, cond);
  6520. }
  6521. ImVec2 ImGui::GetWindowSize()
  6522. {
  6523. ImGuiWindow* window = GetCurrentWindowRead();
  6524. return window->Size;
  6525. }
  6526. void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  6527. {
  6528. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6529. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  6530. return;
  6531. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6532. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6533. // Set
  6534. if (size.x > 0.0f)
  6535. {
  6536. window->AutoFitFramesX = 0;
  6537. window->SizeFull.x = IM_FLOOR(size.x);
  6538. }
  6539. else
  6540. {
  6541. window->AutoFitFramesX = 2;
  6542. window->AutoFitOnlyGrows = false;
  6543. }
  6544. if (size.y > 0.0f)
  6545. {
  6546. window->AutoFitFramesY = 0;
  6547. window->SizeFull.y = IM_FLOOR(size.y);
  6548. }
  6549. else
  6550. {
  6551. window->AutoFitFramesY = 2;
  6552. window->AutoFitOnlyGrows = false;
  6553. }
  6554. }
  6555. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  6556. {
  6557. SetWindowSize(GImGui->CurrentWindow, size, cond);
  6558. }
  6559. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  6560. {
  6561. if (ImGuiWindow* window = FindWindowByName(name))
  6562. SetWindowSize(window, size, cond);
  6563. }
  6564. void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  6565. {
  6566. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6567. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  6568. return;
  6569. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6570. // Set
  6571. window->Collapsed = collapsed;
  6572. }
  6573. void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
  6574. {
  6575. IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
  6576. window->HitTestHoleSize = ImVec2ih(size);
  6577. window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
  6578. }
  6579. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  6580. {
  6581. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  6582. }
  6583. bool ImGui::IsWindowCollapsed()
  6584. {
  6585. ImGuiWindow* window = GetCurrentWindowRead();
  6586. return window->Collapsed;
  6587. }
  6588. bool ImGui::IsWindowAppearing()
  6589. {
  6590. ImGuiWindow* window = GetCurrentWindowRead();
  6591. return window->Appearing;
  6592. }
  6593. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  6594. {
  6595. if (ImGuiWindow* window = FindWindowByName(name))
  6596. SetWindowCollapsed(window, collapsed, cond);
  6597. }
  6598. void ImGui::SetWindowFocus()
  6599. {
  6600. FocusWindow(GImGui->CurrentWindow);
  6601. }
  6602. void ImGui::SetWindowFocus(const char* name)
  6603. {
  6604. if (name)
  6605. {
  6606. if (ImGuiWindow* window = FindWindowByName(name))
  6607. FocusWindow(window);
  6608. }
  6609. else
  6610. {
  6611. FocusWindow(NULL);
  6612. }
  6613. }
  6614. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
  6615. {
  6616. ImGuiContext& g = *GImGui;
  6617. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6618. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
  6619. g.NextWindowData.PosVal = pos;
  6620. g.NextWindowData.PosPivotVal = pivot;
  6621. g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
  6622. g.NextWindowData.PosUndock = true;
  6623. }
  6624. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  6625. {
  6626. ImGuiContext& g = *GImGui;
  6627. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6628. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
  6629. g.NextWindowData.SizeVal = size;
  6630. g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
  6631. }
  6632. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
  6633. {
  6634. ImGuiContext& g = *GImGui;
  6635. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
  6636. g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
  6637. g.NextWindowData.SizeCallback = custom_callback;
  6638. g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
  6639. }
  6640. // Content size = inner scrollable rectangle, padded with WindowPadding.
  6641. // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
  6642. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  6643. {
  6644. ImGuiContext& g = *GImGui;
  6645. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
  6646. g.NextWindowData.ContentSizeVal = ImFloor(size);
  6647. }
  6648. void ImGui::SetNextWindowScroll(const ImVec2& scroll)
  6649. {
  6650. ImGuiContext& g = *GImGui;
  6651. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
  6652. g.NextWindowData.ScrollVal = scroll;
  6653. }
  6654. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  6655. {
  6656. ImGuiContext& g = *GImGui;
  6657. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6658. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
  6659. g.NextWindowData.CollapsedVal = collapsed;
  6660. g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
  6661. }
  6662. void ImGui::SetNextWindowFocus()
  6663. {
  6664. ImGuiContext& g = *GImGui;
  6665. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
  6666. }
  6667. void ImGui::SetNextWindowBgAlpha(float alpha)
  6668. {
  6669. ImGuiContext& g = *GImGui;
  6670. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
  6671. g.NextWindowData.BgAlphaVal = alpha;
  6672. }
  6673. void ImGui::SetNextWindowViewport(ImGuiID id)
  6674. {
  6675. ImGuiContext& g = *GImGui;
  6676. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
  6677. g.NextWindowData.ViewportId = id;
  6678. }
  6679. void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
  6680. {
  6681. ImGuiContext& g = *GImGui;
  6682. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
  6683. g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
  6684. g.NextWindowData.DockId = id;
  6685. }
  6686. void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
  6687. {
  6688. ImGuiContext& g = *GImGui;
  6689. IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
  6690. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
  6691. g.NextWindowData.WindowClass = *window_class;
  6692. }
  6693. ImDrawList* ImGui::GetWindowDrawList()
  6694. {
  6695. ImGuiWindow* window = GetCurrentWindow();
  6696. return window->DrawList;
  6697. }
  6698. float ImGui::GetWindowDpiScale()
  6699. {
  6700. ImGuiContext& g = *GImGui;
  6701. return g.CurrentDpiScale;
  6702. }
  6703. ImGuiViewport* ImGui::GetWindowViewport()
  6704. {
  6705. ImGuiContext& g = *GImGui;
  6706. IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
  6707. return g.CurrentViewport;
  6708. }
  6709. ImFont* ImGui::GetFont()
  6710. {
  6711. return GImGui->Font;
  6712. }
  6713. float ImGui::GetFontSize()
  6714. {
  6715. return GImGui->FontSize;
  6716. }
  6717. ImVec2 ImGui::GetFontTexUvWhitePixel()
  6718. {
  6719. return GImGui->DrawListSharedData.TexUvWhitePixel;
  6720. }
  6721. void ImGui::SetWindowFontScale(float scale)
  6722. {
  6723. IM_ASSERT(scale > 0.0f);
  6724. ImGuiContext& g = *GImGui;
  6725. ImGuiWindow* window = GetCurrentWindow();
  6726. window->FontWindowScale = scale;
  6727. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  6728. }
  6729. void ImGui::ActivateItem(ImGuiID id)
  6730. {
  6731. ImGuiContext& g = *GImGui;
  6732. g.NavNextActivateId = id;
  6733. }
  6734. void ImGui::PushFocusScope(ImGuiID id)
  6735. {
  6736. ImGuiContext& g = *GImGui;
  6737. ImGuiWindow* window = g.CurrentWindow;
  6738. g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent);
  6739. window->DC.NavFocusScopeIdCurrent = id;
  6740. }
  6741. void ImGui::PopFocusScope()
  6742. {
  6743. ImGuiContext& g = *GImGui;
  6744. ImGuiWindow* window = g.CurrentWindow;
  6745. IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
  6746. window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back();
  6747. g.FocusScopeStack.pop_back();
  6748. }
  6749. void ImGui::SetKeyboardFocusHere(int offset)
  6750. {
  6751. IM_ASSERT(offset >= -1); // -1 is allowed but not below
  6752. ImGuiContext& g = *GImGui;
  6753. ImGuiWindow* window = g.CurrentWindow;
  6754. g.TabFocusRequestNextWindow = window;
  6755. g.TabFocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
  6756. g.TabFocusRequestNextCounterTabStop = INT_MAX;
  6757. }
  6758. void ImGui::SetItemDefaultFocus()
  6759. {
  6760. ImGuiContext& g = *GImGui;
  6761. ImGuiWindow* window = g.CurrentWindow;
  6762. if (!window->Appearing)
  6763. return;
  6764. if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == window->DC.NavLayerCurrent)
  6765. {
  6766. g.NavInitRequest = false;
  6767. g.NavInitResultId = window->DC.LastItemId;
  6768. g.NavInitResultRectRel = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
  6769. NavUpdateAnyRequestFlag();
  6770. if (!IsItemVisible())
  6771. SetScrollHereY();
  6772. }
  6773. }
  6774. void ImGui::SetStateStorage(ImGuiStorage* tree)
  6775. {
  6776. ImGuiWindow* window = GImGui->CurrentWindow;
  6777. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  6778. }
  6779. ImGuiStorage* ImGui::GetStateStorage()
  6780. {
  6781. ImGuiWindow* window = GImGui->CurrentWindow;
  6782. return window->DC.StateStorage;
  6783. }
  6784. void ImGui::PushID(const char* str_id)
  6785. {
  6786. ImGuiContext& g = *GImGui;
  6787. ImGuiWindow* window = g.CurrentWindow;
  6788. ImGuiID id = window->GetIDNoKeepAlive(str_id);
  6789. window->IDStack.push_back(id);
  6790. }
  6791. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  6792. {
  6793. ImGuiContext& g = *GImGui;
  6794. ImGuiWindow* window = g.CurrentWindow;
  6795. ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end);
  6796. window->IDStack.push_back(id);
  6797. }
  6798. void ImGui::PushID(const void* ptr_id)
  6799. {
  6800. ImGuiContext& g = *GImGui;
  6801. ImGuiWindow* window = g.CurrentWindow;
  6802. ImGuiID id = window->GetIDNoKeepAlive(ptr_id);
  6803. window->IDStack.push_back(id);
  6804. }
  6805. void ImGui::PushID(int int_id)
  6806. {
  6807. ImGuiContext& g = *GImGui;
  6808. ImGuiWindow* window = g.CurrentWindow;
  6809. ImGuiID id = window->GetIDNoKeepAlive(int_id);
  6810. window->IDStack.push_back(id);
  6811. }
  6812. // Push a given id value ignoring the ID stack as a seed.
  6813. void ImGui::PushOverrideID(ImGuiID id)
  6814. {
  6815. ImGuiContext& g = *GImGui;
  6816. ImGuiWindow* window = g.CurrentWindow;
  6817. window->IDStack.push_back(id);
  6818. }
  6819. // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
  6820. // (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
  6821. // for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
  6822. ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
  6823. {
  6824. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  6825. ImGui::KeepAliveID(id);
  6826. #ifdef IMGUI_ENABLE_TEST_ENGINE
  6827. ImGuiContext& g = *GImGui;
  6828. IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
  6829. #endif
  6830. return id;
  6831. }
  6832. void ImGui::PopID()
  6833. {
  6834. ImGuiWindow* window = GImGui->CurrentWindow;
  6835. IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
  6836. window->IDStack.pop_back();
  6837. }
  6838. ImGuiID ImGui::GetID(const char* str_id)
  6839. {
  6840. ImGuiWindow* window = GImGui->CurrentWindow;
  6841. return window->GetID(str_id);
  6842. }
  6843. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  6844. {
  6845. ImGuiWindow* window = GImGui->CurrentWindow;
  6846. return window->GetID(str_id_begin, str_id_end);
  6847. }
  6848. ImGuiID ImGui::GetID(const void* ptr_id)
  6849. {
  6850. ImGuiWindow* window = GImGui->CurrentWindow;
  6851. return window->GetID(ptr_id);
  6852. }
  6853. bool ImGui::IsRectVisible(const ImVec2& size)
  6854. {
  6855. ImGuiWindow* window = GImGui->CurrentWindow;
  6856. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  6857. }
  6858. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  6859. {
  6860. ImGuiWindow* window = GImGui->CurrentWindow;
  6861. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  6862. }
  6863. //-----------------------------------------------------------------------------
  6864. // [SECTION] ERROR CHECKING
  6865. //-----------------------------------------------------------------------------
  6866. // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
  6867. // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
  6868. // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
  6869. // may see different structures than what imgui.cpp sees, which is problematic.
  6870. // We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
  6871. 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)
  6872. {
  6873. bool error = false;
  6874. if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
  6875. if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
  6876. if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
  6877. if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
  6878. if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
  6879. if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
  6880. if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
  6881. return !error;
  6882. }
  6883. static void ImGui::ErrorCheckNewFrameSanityChecks()
  6884. {
  6885. ImGuiContext& g = *GImGui;
  6886. // Check user IM_ASSERT macro
  6887. // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
  6888. // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
  6889. // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
  6890. // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
  6891. // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
  6892. if (true) IM_ASSERT(1); else IM_ASSERT(0);
  6893. // Check user data
  6894. // (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)
  6895. IM_ASSERT(g.Initialized);
  6896. IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
  6897. IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
  6898. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
  6899. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?");
  6900. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?");
  6901. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
  6902. IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
  6903. 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
  6904. IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
  6905. IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
  6906. for (int n = 0; n < ImGuiKey_COUNT; n++)
  6907. IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
  6908. // 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)
  6909. if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
  6910. IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
  6911. // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
  6912. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
  6913. g.IO.ConfigWindowsResizeFromEdges = false;
  6914. // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
  6915. if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
  6916. IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
  6917. if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
  6918. IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
  6919. // Perform simple checks: multi-viewport and platform windows support
  6920. if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  6921. {
  6922. if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
  6923. {
  6924. IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
  6925. IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
  6926. IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
  6927. IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
  6928. IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
  6929. IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
  6930. IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
  6931. IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
  6932. IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
  6933. if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  6934. IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
  6935. }
  6936. else
  6937. {
  6938. // Disable feature, our backends do not support it
  6939. g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
  6940. }
  6941. // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
  6942. for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
  6943. {
  6944. ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
  6945. IM_UNUSED(mon);
  6946. IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
  6947. IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
  6948. IM_ASSERT(mon.DpiScale != 0.0f);
  6949. }
  6950. }
  6951. }
  6952. static void ImGui::ErrorCheckEndFrameSanityChecks()
  6953. {
  6954. ImGuiContext& g = *GImGui;
  6955. // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
  6956. // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
  6957. // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
  6958. // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
  6959. // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
  6960. // while still correctly asserting on mid-frame key press events.
  6961. const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags();
  6962. IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
  6963. IM_UNUSED(key_mod_flags);
  6964. // Recover from errors
  6965. //ErrorCheckEndFrameRecover();
  6966. // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
  6967. // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
  6968. if (g.CurrentWindowStack.Size != 1)
  6969. {
  6970. if (g.CurrentWindowStack.Size > 1)
  6971. {
  6972. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
  6973. while (g.CurrentWindowStack.Size > 1)
  6974. End();
  6975. }
  6976. else
  6977. {
  6978. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
  6979. }
  6980. }
  6981. IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
  6982. }
  6983. // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
  6984. // Must be called during or before EndFrame().
  6985. // This is generally flawed as we are not necessarily End/Popping things in the right order.
  6986. // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
  6987. // FIXME: Can't recover from interleaved BeginTabBar/Begin
  6988. void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
  6989. {
  6990. // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
  6991. ImGuiContext& g = *GImGui;
  6992. while (g.CurrentWindowStack.Size > 0)
  6993. {
  6994. #ifdef IMGUI_HAS_TABLE
  6995. while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
  6996. {
  6997. if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
  6998. EndTable();
  6999. }
  7000. #endif
  7001. ImGuiWindow* window = g.CurrentWindow;
  7002. IM_ASSERT(window != NULL);
  7003. while (g.CurrentTabBar != NULL) //-V1044
  7004. {
  7005. if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
  7006. EndTabBar();
  7007. }
  7008. while (window->DC.TreeDepth > 0)
  7009. {
  7010. if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
  7011. TreePop();
  7012. }
  7013. while (g.GroupStack.Size > window->DC.StackSizesOnBegin.SizeOfGroupStack)
  7014. {
  7015. if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
  7016. EndGroup();
  7017. }
  7018. while (window->IDStack.Size > 1)
  7019. {
  7020. if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
  7021. PopID();
  7022. }
  7023. while (g.ColorStack.Size > window->DC.StackSizesOnBegin.SizeOfColorStack)
  7024. {
  7025. if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
  7026. PopStyleColor();
  7027. }
  7028. while (g.StyleVarStack.Size > window->DC.StackSizesOnBegin.SizeOfStyleVarStack)
  7029. {
  7030. if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
  7031. PopStyleVar();
  7032. }
  7033. while (g.FocusScopeStack.Size > window->DC.StackSizesOnBegin.SizeOfFocusScopeStack)
  7034. {
  7035. if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
  7036. PopFocusScope();
  7037. }
  7038. if (g.CurrentWindowStack.Size == 1)
  7039. {
  7040. IM_ASSERT(g.CurrentWindow->IsFallbackWindow);
  7041. break;
  7042. }
  7043. IM_ASSERT(window == g.CurrentWindow);
  7044. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  7045. {
  7046. if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
  7047. EndChild();
  7048. }
  7049. else
  7050. {
  7051. if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
  7052. End();
  7053. }
  7054. }
  7055. }
  7056. // Save current stack sizes for later compare
  7057. void ImGuiStackSizes::SetToCurrentState()
  7058. {
  7059. ImGuiContext& g = *GImGui;
  7060. ImGuiWindow* window = g.CurrentWindow;
  7061. SizeOfIDStack = (short)window->IDStack.Size;
  7062. SizeOfColorStack = (short)g.ColorStack.Size;
  7063. SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
  7064. SizeOfFontStack = (short)g.FontStack.Size;
  7065. SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
  7066. SizeOfGroupStack = (short)g.GroupStack.Size;
  7067. SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
  7068. }
  7069. // Compare to detect usage errors
  7070. void ImGuiStackSizes::CompareWithCurrentState()
  7071. {
  7072. ImGuiContext& g = *GImGui;
  7073. ImGuiWindow* window = g.CurrentWindow;
  7074. IM_UNUSED(window);
  7075. // Window stacks
  7076. // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
  7077. IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
  7078. // Global stacks
  7079. // 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.
  7080. IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
  7081. IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
  7082. IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
  7083. IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
  7084. IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
  7085. IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
  7086. }
  7087. //-----------------------------------------------------------------------------
  7088. // [SECTION] LAYOUT
  7089. //-----------------------------------------------------------------------------
  7090. // - ItemSize()
  7091. // - ItemAdd()
  7092. // - SameLine()
  7093. // - GetCursorScreenPos()
  7094. // - SetCursorScreenPos()
  7095. // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
  7096. // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
  7097. // - GetCursorStartPos()
  7098. // - Indent()
  7099. // - Unindent()
  7100. // - SetNextItemWidth()
  7101. // - PushItemWidth()
  7102. // - PushMultiItemsWidths()
  7103. // - PopItemWidth()
  7104. // - CalcItemWidth()
  7105. // - CalcItemSize()
  7106. // - GetTextLineHeight()
  7107. // - GetTextLineHeightWithSpacing()
  7108. // - GetFrameHeight()
  7109. // - GetFrameHeightWithSpacing()
  7110. // - GetContentRegionMax()
  7111. // - GetContentRegionMaxAbs() [Internal]
  7112. // - GetContentRegionAvail(),
  7113. // - GetWindowContentRegionMin(), GetWindowContentRegionMax()
  7114. // - GetWindowContentRegionWidth()
  7115. // - BeginGroup()
  7116. // - EndGroup()
  7117. // Also see in imgui_widgets: tab bars, columns.
  7118. //-----------------------------------------------------------------------------
  7119. // Advance cursor given item size for layout.
  7120. // Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
  7121. // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
  7122. void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
  7123. {
  7124. ImGuiContext& g = *GImGui;
  7125. ImGuiWindow* window = g.CurrentWindow;
  7126. if (window->SkipItems)
  7127. return;
  7128. // We increase the height in this function to accommodate for baseline offset.
  7129. // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
  7130. // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
  7131. const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
  7132. const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
  7133. // Always align ourselves on pixel boundaries
  7134. //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]
  7135. window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
  7136. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
  7137. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
  7138. window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
  7139. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  7140. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
  7141. //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
  7142. window->DC.PrevLineSize.y = line_height;
  7143. window->DC.CurrLineSize.y = 0.0f;
  7144. window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
  7145. window->DC.CurrLineTextBaseOffset = 0.0f;
  7146. // Horizontal layout mode
  7147. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  7148. SameLine();
  7149. }
  7150. void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
  7151. {
  7152. ItemSize(bb.GetSize(), text_baseline_y);
  7153. }
  7154. // Declare item bounding box for clipping and interaction.
  7155. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  7156. // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
  7157. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemAddFlags flags)
  7158. {
  7159. ImGuiContext& g = *GImGui;
  7160. ImGuiWindow* window = g.CurrentWindow;
  7161. if (id != 0)
  7162. {
  7163. // Navigation processing runs prior to clipping early-out
  7164. // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
  7165. // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
  7166. // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
  7167. // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
  7168. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
  7169. // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
  7170. // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
  7171. // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
  7172. window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
  7173. if (g.NavId == id || g.NavAnyRequest)
  7174. if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
  7175. if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
  7176. NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
  7177. // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
  7178. #ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
  7179. if (id == g.DebugItemPickerBreakId)
  7180. {
  7181. IM_DEBUG_BREAK();
  7182. g.DebugItemPickerBreakId = 0;
  7183. }
  7184. #endif
  7185. }
  7186. // Equivalent to calling SetLastItemData()
  7187. window->DC.LastItemId = id;
  7188. window->DC.LastItemRect = bb;
  7189. window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
  7190. g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
  7191. #ifdef IMGUI_ENABLE_TEST_ENGINE
  7192. if (id != 0)
  7193. IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
  7194. #endif
  7195. // Clipping test
  7196. const bool is_clipped = IsClippedEx(bb, id, false);
  7197. if (is_clipped)
  7198. return false;
  7199. //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
  7200. // Tab stop handling (previously was using internal ItemFocusable() api)
  7201. // FIXME-NAV: We would now want to move this above the clipping test, but this would require being able to scroll and currently this would mean an extra frame. (#4079, #343)
  7202. if (flags & ImGuiItemAddFlags_Focusable)
  7203. ItemFocusable(window, id);
  7204. // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
  7205. if (IsMouseHoveringRect(bb.Min, bb.Max))
  7206. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
  7207. return true;
  7208. }
  7209. // Gets back to previous line and continue with horizontal layout
  7210. // offset_from_start_x == 0 : follow right after previous item
  7211. // offset_from_start_x != 0 : align to specified x position (relative to window/group left)
  7212. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  7213. // spacing_w >= 0 : enforce spacing amount
  7214. void ImGui::SameLine(float offset_from_start_x, float spacing_w)
  7215. {
  7216. ImGuiWindow* window = GetCurrentWindow();
  7217. if (window->SkipItems)
  7218. return;
  7219. ImGuiContext& g = *GImGui;
  7220. if (offset_from_start_x != 0.0f)
  7221. {
  7222. if (spacing_w < 0.0f) spacing_w = 0.0f;
  7223. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
  7224. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  7225. }
  7226. else
  7227. {
  7228. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  7229. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  7230. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  7231. }
  7232. window->DC.CurrLineSize = window->DC.PrevLineSize;
  7233. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  7234. }
  7235. ImVec2 ImGui::GetCursorScreenPos()
  7236. {
  7237. ImGuiWindow* window = GetCurrentWindowRead();
  7238. return window->DC.CursorPos;
  7239. }
  7240. void ImGui::SetCursorScreenPos(const ImVec2& pos)
  7241. {
  7242. ImGuiWindow* window = GetCurrentWindow();
  7243. window->DC.CursorPos = pos;
  7244. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  7245. }
  7246. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  7247. // 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'.
  7248. ImVec2 ImGui::GetCursorPos()
  7249. {
  7250. ImGuiWindow* window = GetCurrentWindowRead();
  7251. return window->DC.CursorPos - window->Pos + window->Scroll;
  7252. }
  7253. float ImGui::GetCursorPosX()
  7254. {
  7255. ImGuiWindow* window = GetCurrentWindowRead();
  7256. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  7257. }
  7258. float ImGui::GetCursorPosY()
  7259. {
  7260. ImGuiWindow* window = GetCurrentWindowRead();
  7261. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  7262. }
  7263. void ImGui::SetCursorPos(const ImVec2& local_pos)
  7264. {
  7265. ImGuiWindow* window = GetCurrentWindow();
  7266. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  7267. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  7268. }
  7269. void ImGui::SetCursorPosX(float x)
  7270. {
  7271. ImGuiWindow* window = GetCurrentWindow();
  7272. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  7273. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  7274. }
  7275. void ImGui::SetCursorPosY(float y)
  7276. {
  7277. ImGuiWindow* window = GetCurrentWindow();
  7278. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  7279. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  7280. }
  7281. ImVec2 ImGui::GetCursorStartPos()
  7282. {
  7283. ImGuiWindow* window = GetCurrentWindowRead();
  7284. return window->DC.CursorStartPos - window->Pos;
  7285. }
  7286. void ImGui::Indent(float indent_w)
  7287. {
  7288. ImGuiContext& g = *GImGui;
  7289. ImGuiWindow* window = GetCurrentWindow();
  7290. window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  7291. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  7292. }
  7293. void ImGui::Unindent(float indent_w)
  7294. {
  7295. ImGuiContext& g = *GImGui;
  7296. ImGuiWindow* window = GetCurrentWindow();
  7297. window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  7298. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  7299. }
  7300. // Affect large frame+labels widgets only.
  7301. void ImGui::SetNextItemWidth(float item_width)
  7302. {
  7303. ImGuiContext& g = *GImGui;
  7304. g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
  7305. g.NextItemData.Width = item_width;
  7306. }
  7307. // FIXME: Remove the == 0.0f behavior?
  7308. void ImGui::PushItemWidth(float item_width)
  7309. {
  7310. ImGuiContext& g = *GImGui;
  7311. ImGuiWindow* window = g.CurrentWindow;
  7312. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
  7313. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  7314. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  7315. }
  7316. void ImGui::PushMultiItemsWidths(int components, float w_full)
  7317. {
  7318. ImGuiContext& g = *GImGui;
  7319. ImGuiWindow* window = g.CurrentWindow;
  7320. const ImGuiStyle& style = g.Style;
  7321. const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
  7322. const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
  7323. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
  7324. window->DC.ItemWidthStack.push_back(w_item_last);
  7325. for (int i = 0; i < components - 2; i++)
  7326. window->DC.ItemWidthStack.push_back(w_item_one);
  7327. window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
  7328. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  7329. }
  7330. void ImGui::PopItemWidth()
  7331. {
  7332. ImGuiWindow* window = GetCurrentWindow();
  7333. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  7334. window->DC.ItemWidthStack.pop_back();
  7335. }
  7336. // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
  7337. // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
  7338. float ImGui::CalcItemWidth()
  7339. {
  7340. ImGuiContext& g = *GImGui;
  7341. ImGuiWindow* window = g.CurrentWindow;
  7342. float w;
  7343. if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
  7344. w = g.NextItemData.Width;
  7345. else
  7346. w = window->DC.ItemWidth;
  7347. if (w < 0.0f)
  7348. {
  7349. float region_max_x = GetContentRegionMaxAbs().x;
  7350. w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
  7351. }
  7352. w = IM_FLOOR(w);
  7353. return w;
  7354. }
  7355. // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
  7356. // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
  7357. // Note that only CalcItemWidth() is publicly exposed.
  7358. // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
  7359. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
  7360. {
  7361. ImGuiWindow* window = GImGui->CurrentWindow;
  7362. ImVec2 region_max;
  7363. if (size.x < 0.0f || size.y < 0.0f)
  7364. region_max = GetContentRegionMaxAbs();
  7365. if (size.x == 0.0f)
  7366. size.x = default_w;
  7367. else if (size.x < 0.0f)
  7368. size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
  7369. if (size.y == 0.0f)
  7370. size.y = default_h;
  7371. else if (size.y < 0.0f)
  7372. size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
  7373. return size;
  7374. }
  7375. float ImGui::GetTextLineHeight()
  7376. {
  7377. ImGuiContext& g = *GImGui;
  7378. return g.FontSize;
  7379. }
  7380. float ImGui::GetTextLineHeightWithSpacing()
  7381. {
  7382. ImGuiContext& g = *GImGui;
  7383. return g.FontSize + g.Style.ItemSpacing.y;
  7384. }
  7385. float ImGui::GetFrameHeight()
  7386. {
  7387. ImGuiContext& g = *GImGui;
  7388. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  7389. }
  7390. float ImGui::GetFrameHeightWithSpacing()
  7391. {
  7392. ImGuiContext& g = *GImGui;
  7393. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  7394. }
  7395. // 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!
  7396. // FIXME: This is in window space (not screen space!).
  7397. ImVec2 ImGui::GetContentRegionMax()
  7398. {
  7399. ImGuiContext& g = *GImGui;
  7400. ImGuiWindow* window = g.CurrentWindow;
  7401. ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
  7402. if (window->DC.CurrentColumns || g.CurrentTable)
  7403. mx.x = window->WorkRect.Max.x - window->Pos.x;
  7404. return mx;
  7405. }
  7406. // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
  7407. ImVec2 ImGui::GetContentRegionMaxAbs()
  7408. {
  7409. ImGuiContext& g = *GImGui;
  7410. ImGuiWindow* window = g.CurrentWindow;
  7411. ImVec2 mx = window->ContentRegionRect.Max;
  7412. if (window->DC.CurrentColumns || g.CurrentTable)
  7413. mx.x = window->WorkRect.Max.x;
  7414. return mx;
  7415. }
  7416. ImVec2 ImGui::GetContentRegionAvail()
  7417. {
  7418. ImGuiWindow* window = GImGui->CurrentWindow;
  7419. return GetContentRegionMaxAbs() - window->DC.CursorPos;
  7420. }
  7421. // In window space (not screen space!)
  7422. ImVec2 ImGui::GetWindowContentRegionMin()
  7423. {
  7424. ImGuiWindow* window = GImGui->CurrentWindow;
  7425. return window->ContentRegionRect.Min - window->Pos;
  7426. }
  7427. ImVec2 ImGui::GetWindowContentRegionMax()
  7428. {
  7429. ImGuiWindow* window = GImGui->CurrentWindow;
  7430. return window->ContentRegionRect.Max - window->Pos;
  7431. }
  7432. float ImGui::GetWindowContentRegionWidth()
  7433. {
  7434. ImGuiWindow* window = GImGui->CurrentWindow;
  7435. return window->ContentRegionRect.GetWidth();
  7436. }
  7437. // 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.)
  7438. // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
  7439. void ImGui::BeginGroup()
  7440. {
  7441. ImGuiContext& g = *GImGui;
  7442. ImGuiWindow* window = g.CurrentWindow;
  7443. g.GroupStack.resize(g.GroupStack.Size + 1);
  7444. ImGuiGroupData& group_data = g.GroupStack.back();
  7445. group_data.WindowID = window->ID;
  7446. group_data.BackupCursorPos = window->DC.CursorPos;
  7447. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  7448. group_data.BackupIndent = window->DC.Indent;
  7449. group_data.BackupGroupOffset = window->DC.GroupOffset;
  7450. group_data.BackupCurrLineSize = window->DC.CurrLineSize;
  7451. group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
  7452. group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
  7453. group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
  7454. group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
  7455. group_data.EmitItem = true;
  7456. window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
  7457. window->DC.Indent = window->DC.GroupOffset;
  7458. window->DC.CursorMaxPos = window->DC.CursorPos;
  7459. window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
  7460. if (g.LogEnabled)
  7461. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  7462. }
  7463. void ImGui::EndGroup()
  7464. {
  7465. ImGuiContext& g = *GImGui;
  7466. ImGuiWindow* window = g.CurrentWindow;
  7467. IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
  7468. ImGuiGroupData& group_data = g.GroupStack.back();
  7469. IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
  7470. ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
  7471. window->DC.CursorPos = group_data.BackupCursorPos;
  7472. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  7473. window->DC.Indent = group_data.BackupIndent;
  7474. window->DC.GroupOffset = group_data.BackupGroupOffset;
  7475. window->DC.CurrLineSize = group_data.BackupCurrLineSize;
  7476. window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
  7477. if (g.LogEnabled)
  7478. g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
  7479. if (!group_data.EmitItem)
  7480. {
  7481. g.GroupStack.pop_back();
  7482. return;
  7483. }
  7484. 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.
  7485. ItemSize(group_bb.GetSize());
  7486. ItemAdd(group_bb, 0);
  7487. // 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.
  7488. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
  7489. // Also if you grep for LastItemId you'll notice it is only used in that context.
  7490. // (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.)
  7491. const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
  7492. const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
  7493. if (group_contains_curr_active_id)
  7494. window->DC.LastItemId = g.ActiveId;
  7495. else if (group_contains_prev_active_id)
  7496. window->DC.LastItemId = g.ActiveIdPreviousFrame;
  7497. window->DC.LastItemRect = group_bb;
  7498. // Forward Hovered flag
  7499. const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
  7500. if (group_contains_curr_hovered_id)
  7501. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
  7502. // Forward Edited flag
  7503. if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
  7504. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
  7505. // Forward Deactivated flag
  7506. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
  7507. if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
  7508. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
  7509. g.GroupStack.pop_back();
  7510. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  7511. }
  7512. //-----------------------------------------------------------------------------
  7513. // [SECTION] SCROLLING
  7514. //-----------------------------------------------------------------------------
  7515. // Helper to snap on edges when aiming at an item very close to the edge,
  7516. // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
  7517. // When we refactor the scrolling API this may be configurable with a flag?
  7518. // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
  7519. static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
  7520. {
  7521. if (target <= snap_min + snap_threshold)
  7522. return ImLerp(snap_min, target, center_ratio);
  7523. if (target >= snap_max - snap_threshold)
  7524. return ImLerp(target, snap_max, center_ratio);
  7525. return target;
  7526. }
  7527. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
  7528. {
  7529. ImVec2 scroll = window->Scroll;
  7530. if (window->ScrollTarget.x < FLT_MAX)
  7531. {
  7532. float decoration_total_width = window->ScrollbarSizes.x;
  7533. float center_x_ratio = window->ScrollTargetCenterRatio.x;
  7534. float scroll_target_x = window->ScrollTarget.x;
  7535. if (window->ScrollTargetEdgeSnapDist.x > 0.0f)
  7536. {
  7537. float snap_x_min = 0.0f;
  7538. float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width;
  7539. scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);
  7540. }
  7541. scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width);
  7542. }
  7543. if (window->ScrollTarget.y < FLT_MAX)
  7544. {
  7545. float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y;
  7546. float center_y_ratio = window->ScrollTargetCenterRatio.y;
  7547. float scroll_target_y = window->ScrollTarget.y;
  7548. if (window->ScrollTargetEdgeSnapDist.y > 0.0f)
  7549. {
  7550. float snap_y_min = 0.0f;
  7551. float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height;
  7552. scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);
  7553. }
  7554. scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height);
  7555. }
  7556. scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
  7557. scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
  7558. if (!window->Collapsed && !window->SkipItems)
  7559. {
  7560. scroll.x = ImMin(scroll.x, window->ScrollMax.x);
  7561. scroll.y = ImMin(scroll.y, window->ScrollMax.y);
  7562. }
  7563. return scroll;
  7564. }
  7565. // Scroll to keep newly navigated item fully into view
  7566. ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
  7567. {
  7568. ImGuiContext& g = *GImGui;
  7569. ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
  7570. //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
  7571. ImVec2 delta_scroll;
  7572. if (!window_rect.Contains(item_rect))
  7573. {
  7574. if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
  7575. SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x - g.Style.ItemSpacing.x, 0.0f);
  7576. else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
  7577. SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
  7578. if (item_rect.Min.y < window_rect.Min.y)
  7579. SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
  7580. else if (item_rect.Max.y >= window_rect.Max.y)
  7581. SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
  7582. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  7583. delta_scroll = next_scroll - window->Scroll;
  7584. }
  7585. // Also scroll parent window to keep us into view if necessary
  7586. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  7587. delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
  7588. return delta_scroll;
  7589. }
  7590. float ImGui::GetScrollX()
  7591. {
  7592. ImGuiWindow* window = GImGui->CurrentWindow;
  7593. return window->Scroll.x;
  7594. }
  7595. float ImGui::GetScrollY()
  7596. {
  7597. ImGuiWindow* window = GImGui->CurrentWindow;
  7598. return window->Scroll.y;
  7599. }
  7600. float ImGui::GetScrollMaxX()
  7601. {
  7602. ImGuiWindow* window = GImGui->CurrentWindow;
  7603. return window->ScrollMax.x;
  7604. }
  7605. float ImGui::GetScrollMaxY()
  7606. {
  7607. ImGuiWindow* window = GImGui->CurrentWindow;
  7608. return window->ScrollMax.y;
  7609. }
  7610. void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
  7611. {
  7612. window->ScrollTarget.x = scroll_x;
  7613. window->ScrollTargetCenterRatio.x = 0.0f;
  7614. window->ScrollTargetEdgeSnapDist.x = 0.0f;
  7615. }
  7616. void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
  7617. {
  7618. window->ScrollTarget.y = scroll_y;
  7619. window->ScrollTargetCenterRatio.y = 0.0f;
  7620. window->ScrollTargetEdgeSnapDist.y = 0.0f;
  7621. }
  7622. void ImGui::SetScrollX(float scroll_x)
  7623. {
  7624. ImGuiContext& g = *GImGui;
  7625. SetScrollX(g.CurrentWindow, scroll_x);
  7626. }
  7627. void ImGui::SetScrollY(float scroll_y)
  7628. {
  7629. ImGuiContext& g = *GImGui;
  7630. SetScrollY(g.CurrentWindow, scroll_y);
  7631. }
  7632. // Note that a local position will vary depending on initial scroll value,
  7633. // This is a little bit confusing so bear with us:
  7634. // - local_pos = (absolution_pos - window->Pos)
  7635. // - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
  7636. // and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
  7637. // - They mostly exists because of legacy API.
  7638. // Following the rules above, when trying to work with scrolling code, consider that:
  7639. // - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
  7640. // - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
  7641. // 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
  7642. void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
  7643. {
  7644. IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
  7645. window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset
  7646. window->ScrollTargetCenterRatio.x = center_x_ratio;
  7647. window->ScrollTargetEdgeSnapDist.x = 0.0f;
  7648. }
  7649. void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
  7650. {
  7651. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  7652. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect;
  7653. local_y -= decoration_up_height;
  7654. window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset
  7655. window->ScrollTargetCenterRatio.y = center_y_ratio;
  7656. window->ScrollTargetEdgeSnapDist.y = 0.0f;
  7657. }
  7658. void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
  7659. {
  7660. ImGuiContext& g = *GImGui;
  7661. SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
  7662. }
  7663. void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
  7664. {
  7665. ImGuiContext& g = *GImGui;
  7666. SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
  7667. }
  7668. // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
  7669. void ImGui::SetScrollHereX(float center_x_ratio)
  7670. {
  7671. ImGuiContext& g = *GImGui;
  7672. ImGuiWindow* window = g.CurrentWindow;
  7673. float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
  7674. float target_pos_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio);
  7675. SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
  7676. // Tweak: snap on edges when aiming at an item very close to the edge
  7677. window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
  7678. }
  7679. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  7680. void ImGui::SetScrollHereY(float center_y_ratio)
  7681. {
  7682. ImGuiContext& g = *GImGui;
  7683. ImGuiWindow* window = g.CurrentWindow;
  7684. float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
  7685. float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
  7686. SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
  7687. // Tweak: snap on edges when aiming at an item very close to the edge
  7688. window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
  7689. }
  7690. //-----------------------------------------------------------------------------
  7691. // [SECTION] TOOLTIPS
  7692. //-----------------------------------------------------------------------------
  7693. void ImGui::BeginTooltip()
  7694. {
  7695. BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
  7696. }
  7697. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
  7698. {
  7699. ImGuiContext& g = *GImGui;
  7700. if (g.DragDropWithinSource || g.DragDropWithinTarget)
  7701. {
  7702. // 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)
  7703. // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
  7704. // 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.
  7705. //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
  7706. ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
  7707. SetNextWindowPos(tooltip_pos);
  7708. SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
  7709. //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
  7710. tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
  7711. }
  7712. char window_name[16];
  7713. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
  7714. if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
  7715. if (ImGuiWindow* window = FindWindowByName(window_name))
  7716. if (window->Active)
  7717. {
  7718. // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
  7719. window->Hidden = true;
  7720. window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
  7721. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
  7722. }
  7723. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
  7724. Begin(window_name, NULL, flags | extra_flags);
  7725. }
  7726. void ImGui::EndTooltip()
  7727. {
  7728. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  7729. End();
  7730. }
  7731. void ImGui::SetTooltipV(const char* fmt, va_list args)
  7732. {
  7733. BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
  7734. TextV(fmt, args);
  7735. EndTooltip();
  7736. }
  7737. void ImGui::SetTooltip(const char* fmt, ...)
  7738. {
  7739. va_list args;
  7740. va_start(args, fmt);
  7741. SetTooltipV(fmt, args);
  7742. va_end(args);
  7743. }
  7744. //-----------------------------------------------------------------------------
  7745. // [SECTION] POPUPS
  7746. //-----------------------------------------------------------------------------
  7747. // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
  7748. bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
  7749. {
  7750. ImGuiContext& g = *GImGui;
  7751. if (popup_flags & ImGuiPopupFlags_AnyPopupId)
  7752. {
  7753. // Return true if any popup is open at the current BeginPopup() level of the popup stack
  7754. // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
  7755. IM_ASSERT(id == 0);
  7756. if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
  7757. return g.OpenPopupStack.Size > 0;
  7758. else
  7759. return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
  7760. }
  7761. else
  7762. {
  7763. if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
  7764. {
  7765. // Return true if the popup is open anywhere in the popup stack
  7766. for (int n = 0; n < g.OpenPopupStack.Size; n++)
  7767. if (g.OpenPopupStack[n].PopupId == id)
  7768. return true;
  7769. return false;
  7770. }
  7771. else
  7772. {
  7773. // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
  7774. return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
  7775. }
  7776. }
  7777. }
  7778. bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
  7779. {
  7780. ImGuiContext& g = *GImGui;
  7781. ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
  7782. if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
  7783. IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
  7784. return IsPopupOpen(id, popup_flags);
  7785. }
  7786. ImGuiWindow* ImGui::GetTopMostPopupModal()
  7787. {
  7788. ImGuiContext& g = *GImGui;
  7789. for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
  7790. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  7791. if (popup->Flags & ImGuiWindowFlags_Modal)
  7792. return popup;
  7793. return NULL;
  7794. }
  7795. void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
  7796. {
  7797. ImGuiContext& g = *GImGui;
  7798. OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags);
  7799. }
  7800. void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
  7801. {
  7802. OpenPopupEx(id, popup_flags);
  7803. }
  7804. // Mark popup as open (toggle toward open state).
  7805. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  7806. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  7807. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  7808. void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
  7809. {
  7810. ImGuiContext& g = *GImGui;
  7811. ImGuiWindow* parent_window = g.CurrentWindow;
  7812. const int current_stack_size = g.BeginPopupStack.Size;
  7813. if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
  7814. if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
  7815. return;
  7816. ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
  7817. popup_ref.PopupId = id;
  7818. popup_ref.Window = NULL;
  7819. popup_ref.SourceWindow = g.NavWindow;
  7820. popup_ref.OpenFrameCount = g.FrameCount;
  7821. popup_ref.OpenParentId = parent_window->IDStack.back();
  7822. popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
  7823. popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
  7824. IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id);
  7825. if (g.OpenPopupStack.Size < current_stack_size + 1)
  7826. {
  7827. g.OpenPopupStack.push_back(popup_ref);
  7828. }
  7829. else
  7830. {
  7831. // 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
  7832. // 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
  7833. // 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.
  7834. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
  7835. {
  7836. g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
  7837. }
  7838. else
  7839. {
  7840. // Close child popups if any, then flag popup for open/reopen
  7841. ClosePopupToLevel(current_stack_size, false);
  7842. g.OpenPopupStack.push_back(popup_ref);
  7843. }
  7844. // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
  7845. // This is equivalent to what ClosePopupToLevel() does.
  7846. //if (g.OpenPopupStack[current_stack_size].PopupId == id)
  7847. // FocusWindow(parent_window);
  7848. }
  7849. }
  7850. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  7851. // This function closes any popups that are over 'ref_window'.
  7852. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
  7853. {
  7854. ImGuiContext& g = *GImGui;
  7855. if (g.OpenPopupStack.Size == 0)
  7856. return;
  7857. // Don't close our own child popup windows.
  7858. int popup_count_to_keep = 0;
  7859. if (ref_window)
  7860. {
  7861. // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
  7862. for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
  7863. {
  7864. ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
  7865. if (!popup.Window)
  7866. continue;
  7867. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  7868. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  7869. continue;
  7870. // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
  7871. // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
  7872. // Window -> Popup1 -> Popup2 -> Popup3
  7873. // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
  7874. // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
  7875. bool ref_window_is_descendent_of_popup = false;
  7876. for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
  7877. if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
  7878. if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree)
  7879. {
  7880. ref_window_is_descendent_of_popup = true;
  7881. break;
  7882. }
  7883. if (!ref_window_is_descendent_of_popup)
  7884. break;
  7885. }
  7886. }
  7887. 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
  7888. {
  7889. IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
  7890. ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
  7891. }
  7892. }
  7893. void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
  7894. {
  7895. ImGuiContext& g = *GImGui;
  7896. IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
  7897. IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
  7898. // Trim open popup stack
  7899. ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
  7900. ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
  7901. g.OpenPopupStack.resize(remaining);
  7902. if (restore_focus_to_window_under_popup)
  7903. {
  7904. if (focus_window && !focus_window->WasActive && popup_window)
  7905. {
  7906. // Fallback
  7907. FocusTopMostWindowUnderOne(popup_window, NULL);
  7908. }
  7909. else
  7910. {
  7911. if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
  7912. focus_window = NavRestoreLastChildNavWindow(focus_window);
  7913. FocusWindow(focus_window);
  7914. }
  7915. }
  7916. }
  7917. // Close the popup we have begin-ed into.
  7918. void ImGui::CloseCurrentPopup()
  7919. {
  7920. ImGuiContext& g = *GImGui;
  7921. int popup_idx = g.BeginPopupStack.Size - 1;
  7922. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  7923. return;
  7924. // Closing a menu closes its top-most parent popup (unless a modal)
  7925. while (popup_idx > 0)
  7926. {
  7927. ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
  7928. ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
  7929. bool close_parent = false;
  7930. if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
  7931. if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
  7932. close_parent = true;
  7933. if (!close_parent)
  7934. break;
  7935. popup_idx--;
  7936. }
  7937. IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
  7938. ClosePopupToLevel(popup_idx, true);
  7939. // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
  7940. // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
  7941. // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
  7942. if (ImGuiWindow* window = g.NavWindow)
  7943. window->DC.NavHideHighlightOneFrame = true;
  7944. }
  7945. // Attention! BeginPopup() adds default flags which BeginPopupEx()!
  7946. bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
  7947. {
  7948. ImGuiContext& g = *GImGui;
  7949. if (!IsPopupOpen(id, ImGuiPopupFlags_None))
  7950. {
  7951. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7952. return false;
  7953. }
  7954. char name[20];
  7955. if (flags & ImGuiWindowFlags_ChildMenu)
  7956. ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
  7957. else
  7958. ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
  7959. flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
  7960. bool is_open = Begin(name, NULL, flags);
  7961. if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
  7962. EndPopup();
  7963. return is_open;
  7964. }
  7965. bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
  7966. {
  7967. ImGuiContext& g = *GImGui;
  7968. if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
  7969. {
  7970. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7971. return false;
  7972. }
  7973. flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
  7974. return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
  7975. }
  7976. // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
  7977. // 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.
  7978. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
  7979. {
  7980. ImGuiContext& g = *GImGui;
  7981. ImGuiWindow* window = g.CurrentWindow;
  7982. const ImGuiID id = window->GetID(name);
  7983. if (!IsPopupOpen(id, ImGuiPopupFlags_None))
  7984. {
  7985. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7986. return false;
  7987. }
  7988. // Center modal windows by default for increased visibility
  7989. // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
  7990. // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
  7991. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
  7992. {
  7993. const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
  7994. SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
  7995. }
  7996. flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
  7997. const bool is_open = Begin(name, p_open, flags);
  7998. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  7999. {
  8000. EndPopup();
  8001. if (is_open)
  8002. ClosePopupToLevel(g.BeginPopupStack.Size, true);
  8003. return false;
  8004. }
  8005. return is_open;
  8006. }
  8007. void ImGui::EndPopup()
  8008. {
  8009. ImGuiContext& g = *GImGui;
  8010. ImGuiWindow* window = g.CurrentWindow;
  8011. IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  8012. IM_ASSERT(g.BeginPopupStack.Size > 0);
  8013. // Make all menus and popups wrap around for now, may need to expose that policy.
  8014. if (g.NavWindow == window)
  8015. NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
  8016. // Child-popups don't need to be laid out
  8017. IM_ASSERT(g.WithinEndChild == false);
  8018. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  8019. g.WithinEndChild = true;
  8020. End();
  8021. g.WithinEndChild = false;
  8022. }
  8023. // Helper to open a popup if mouse button is released over the item
  8024. // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
  8025. void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
  8026. {
  8027. ImGuiWindow* window = GImGui->CurrentWindow;
  8028. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8029. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8030. {
  8031. ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  8032. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  8033. OpenPopupEx(id, popup_flags);
  8034. }
  8035. }
  8036. // This is a helper to handle the simplest case of associating one named popup to one given widget.
  8037. // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
  8038. // - To create a popup with a specific identifier, pass it in str_id.
  8039. // - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
  8040. // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
  8041. // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
  8042. // This is essentially the same as:
  8043. // id = str_id ? GetID(str_id) : GetItemID();
  8044. // OpenPopupOnItemClick(str_id);
  8045. // return BeginPopup(id);
  8046. // Which is essentially the same as:
  8047. // id = str_id ? GetID(str_id) : GetItemID();
  8048. // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
  8049. // OpenPopup(id);
  8050. // return BeginPopup(id);
  8051. // The main difference being that this is tweaked to avoid computing the ID twice.
  8052. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
  8053. {
  8054. ImGuiWindow* window = GImGui->CurrentWindow;
  8055. if (window->SkipItems)
  8056. return false;
  8057. ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
  8058. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  8059. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8060. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8061. OpenPopupEx(id, popup_flags);
  8062. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8063. }
  8064. bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
  8065. {
  8066. ImGuiWindow* window = GImGui->CurrentWindow;
  8067. if (!str_id)
  8068. str_id = "window_context";
  8069. ImGuiID id = window->GetID(str_id);
  8070. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8071. if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  8072. if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
  8073. OpenPopupEx(id, popup_flags);
  8074. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8075. }
  8076. bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
  8077. {
  8078. ImGuiWindow* window = GImGui->CurrentWindow;
  8079. if (!str_id)
  8080. str_id = "void_context";
  8081. ImGuiID id = window->GetID(str_id);
  8082. int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
  8083. if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
  8084. if (GetTopMostPopupModal() == NULL)
  8085. OpenPopupEx(id, popup_flags);
  8086. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  8087. }
  8088. // 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.)
  8089. // 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.
  8090. // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
  8091. // information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
  8092. // this allows us to have tooltips/popups displayed out of the parent viewport.)
  8093. ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
  8094. {
  8095. ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
  8096. //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
  8097. //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
  8098. // Combo Box policy (we want a connecting edge)
  8099. if (policy == ImGuiPopupPositionPolicy_ComboBox)
  8100. {
  8101. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
  8102. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  8103. {
  8104. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  8105. if (n != -1 && dir == *last_dir) // Already tried this direction?
  8106. continue;
  8107. ImVec2 pos;
  8108. if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
  8109. if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
  8110. if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
  8111. if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
  8112. if (!r_outer.Contains(ImRect(pos, pos + size)))
  8113. continue;
  8114. *last_dir = dir;
  8115. return pos;
  8116. }
  8117. }
  8118. // Tooltip and Default popup policy
  8119. // (Always first try the direction we used on the last frame, if any)
  8120. if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
  8121. {
  8122. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
  8123. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  8124. {
  8125. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  8126. if (n != -1 && dir == *last_dir) // Already tried this direction?
  8127. continue;
  8128. 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);
  8129. 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);
  8130. // If there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
  8131. if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
  8132. continue;
  8133. if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
  8134. continue;
  8135. ImVec2 pos;
  8136. pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
  8137. pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
  8138. // Clamp top-left corner of popup
  8139. pos.x = ImMax(pos.x, r_outer.Min.x);
  8140. pos.y = ImMax(pos.y, r_outer.Min.y);
  8141. *last_dir = dir;
  8142. return pos;
  8143. }
  8144. }
  8145. // Fallback when not enough room:
  8146. *last_dir = ImGuiDir_None;
  8147. // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  8148. if (policy == ImGuiPopupPositionPolicy_Tooltip)
  8149. return ref_pos + ImVec2(2, 2);
  8150. // Otherwise try to keep within display
  8151. ImVec2 pos = ref_pos;
  8152. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  8153. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  8154. return pos;
  8155. }
  8156. // Note that this is used for popups, which can overlap the non work-area of individual viewports.
  8157. ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
  8158. {
  8159. ImGuiContext& g = *GImGui;
  8160. ImRect r_screen;
  8161. if (window->ViewportAllowPlatformMonitorExtend >= 0)
  8162. {
  8163. // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
  8164. const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
  8165. r_screen.Min = monitor.WorkPos;
  8166. r_screen.Max = monitor.WorkPos + monitor.WorkSize;
  8167. }
  8168. else
  8169. {
  8170. // Use the full viewport area (not work area) for popups
  8171. r_screen = window->Viewport->GetMainRect();
  8172. }
  8173. ImVec2 padding = g.Style.DisplaySafeAreaPadding;
  8174. r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
  8175. return r_screen;
  8176. }
  8177. ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
  8178. {
  8179. ImGuiContext& g = *GImGui;
  8180. ImRect r_outer = GetWindowAllowedExtentRect(window);
  8181. if (window->Flags & ImGuiWindowFlags_ChildMenu)
  8182. {
  8183. // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
  8184. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  8185. ImGuiWindow* parent_window = window->ParentWindow;
  8186. 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).
  8187. ImRect r_avoid;
  8188. if (parent_window->DC.MenuBarAppending)
  8189. 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
  8190. else
  8191. 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);
  8192. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
  8193. }
  8194. if (window->Flags & ImGuiWindowFlags_Popup)
  8195. {
  8196. ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
  8197. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
  8198. }
  8199. if (window->Flags & ImGuiWindowFlags_Tooltip)
  8200. {
  8201. // Position tooltip (always follows mouse)
  8202. float sc = g.Style.MouseCursorScale;
  8203. ImVec2 ref_pos = NavCalcPreferredRefPos();
  8204. ImRect r_avoid;
  8205. if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
  8206. r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
  8207. else
  8208. 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.
  8209. return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
  8210. }
  8211. IM_ASSERT(0);
  8212. return window->Pos;
  8213. }
  8214. //-----------------------------------------------------------------------------
  8215. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  8216. //-----------------------------------------------------------------------------
  8217. // FIXME-NAV: The existence of SetNavID vs SetFocusID properly needs to be clarified/reworked.
  8218. void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
  8219. {
  8220. ImGuiContext& g = *GImGui;
  8221. IM_ASSERT(g.NavWindow != NULL);
  8222. IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
  8223. g.NavId = id;
  8224. g.NavLayer = nav_layer;
  8225. g.NavFocusScopeId = focus_scope_id;
  8226. g.NavWindow->NavLastIds[nav_layer] = id;
  8227. g.NavWindow->NavRectRel[nav_layer] = rect_rel;
  8228. //g.NavDisableHighlight = false;
  8229. //g.NavDisableMouseHover = g.NavMousePosDirty = true;
  8230. }
  8231. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
  8232. {
  8233. ImGuiContext& g = *GImGui;
  8234. IM_ASSERT(id != 0);
  8235. // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
  8236. // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
  8237. const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
  8238. if (g.NavWindow != window)
  8239. g.NavInitRequest = false;
  8240. g.NavWindow = window;
  8241. g.NavId = id;
  8242. g.NavLayer = nav_layer;
  8243. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  8244. window->NavLastIds[nav_layer] = id;
  8245. if (window->DC.LastItemId == id)
  8246. window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
  8247. if (g.ActiveIdSource == ImGuiInputSource_Nav)
  8248. g.NavDisableMouseHover = true;
  8249. else
  8250. g.NavDisableHighlight = true;
  8251. }
  8252. ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
  8253. {
  8254. if (ImFabs(dx) > ImFabs(dy))
  8255. return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
  8256. return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
  8257. }
  8258. static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
  8259. {
  8260. if (a1 < b0)
  8261. return a1 - b0;
  8262. if (b1 < a0)
  8263. return a0 - b1;
  8264. return 0.0f;
  8265. }
  8266. static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
  8267. {
  8268. if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
  8269. {
  8270. r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
  8271. r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
  8272. }
  8273. else
  8274. {
  8275. r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
  8276. r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
  8277. }
  8278. }
  8279. // Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
  8280. static bool ImGui::NavScoreItem(ImGuiNavItemData* result, ImRect cand)
  8281. {
  8282. ImGuiContext& g = *GImGui;
  8283. ImGuiWindow* window = g.CurrentWindow;
  8284. if (g.NavLayer != window->DC.NavLayerCurrent)
  8285. return false;
  8286. 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)
  8287. g.NavScoringCount++;
  8288. // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
  8289. if (window->ParentWindow == g.NavWindow)
  8290. {
  8291. IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
  8292. if (!window->ClipRect.Overlaps(cand))
  8293. return false;
  8294. cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
  8295. }
  8296. // 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)
  8297. // For example, this ensure that items in one column are not reached when moving vertically from items in another column.
  8298. NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
  8299. // Compute distance between boxes
  8300. // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
  8301. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
  8302. 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
  8303. if (dby != 0.0f && dbx != 0.0f)
  8304. dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
  8305. float dist_box = ImFabs(dbx) + ImFabs(dby);
  8306. // 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)
  8307. float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
  8308. float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
  8309. float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
  8310. // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
  8311. ImGuiDir quadrant;
  8312. float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
  8313. if (dbx != 0.0f || dby != 0.0f)
  8314. {
  8315. // For non-overlapping boxes, use distance between boxes
  8316. dax = dbx;
  8317. day = dby;
  8318. dist_axial = dist_box;
  8319. quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
  8320. }
  8321. else if (dcx != 0.0f || dcy != 0.0f)
  8322. {
  8323. // For overlapping boxes with different centers, use distance between centers
  8324. dax = dcx;
  8325. day = dcy;
  8326. dist_axial = dist_center;
  8327. quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
  8328. }
  8329. else
  8330. {
  8331. // 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)
  8332. quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
  8333. }
  8334. #if IMGUI_DEBUG_NAV_SCORING
  8335. char buf[128];
  8336. if (IsMouseHoveringRect(cand.Min, cand.Max))
  8337. {
  8338. 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]);
  8339. ImDrawList* draw_list = GetForegroundDrawList(window);
  8340. draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
  8341. draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
  8342. draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
  8343. draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
  8344. }
  8345. else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
  8346. {
  8347. if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
  8348. if (quadrant == g.NavMoveDir)
  8349. {
  8350. ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
  8351. ImDrawList* draw_list = GetForegroundDrawList(window);
  8352. draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
  8353. draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
  8354. }
  8355. }
  8356. #endif
  8357. // Is it in the quadrant we're interesting in moving to?
  8358. bool new_best = false;
  8359. if (quadrant == g.NavMoveDir)
  8360. {
  8361. // Does it beat the current best candidate?
  8362. if (dist_box < result->DistBox)
  8363. {
  8364. result->DistBox = dist_box;
  8365. result->DistCenter = dist_center;
  8366. return true;
  8367. }
  8368. if (dist_box == result->DistBox)
  8369. {
  8370. // Try using distance between center points to break ties
  8371. if (dist_center < result->DistCenter)
  8372. {
  8373. result->DistCenter = dist_center;
  8374. new_best = true;
  8375. }
  8376. else if (dist_center == result->DistCenter)
  8377. {
  8378. // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
  8379. // (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),
  8380. // 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.
  8381. if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
  8382. new_best = true;
  8383. }
  8384. }
  8385. }
  8386. // 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
  8387. // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
  8388. // 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.
  8389. // 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.
  8390. // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
  8391. if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
  8392. if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
  8393. if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
  8394. {
  8395. result->DistAxial = dist_axial;
  8396. new_best = true;
  8397. }
  8398. return new_best;
  8399. }
  8400. static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel)
  8401. {
  8402. result->Window = window;
  8403. result->ID = id;
  8404. result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
  8405. result->RectRel = nav_bb_rel;
  8406. }
  8407. // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
  8408. static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
  8409. {
  8410. ImGuiContext& g = *GImGui;
  8411. //if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
  8412. // return;
  8413. const ImGuiItemFlags item_flags = g.CurrentItemFlags;
  8414. const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
  8415. // Process Init Request
  8416. if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
  8417. {
  8418. // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
  8419. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
  8420. {
  8421. g.NavInitResultId = id;
  8422. g.NavInitResultRectRel = nav_bb_rel;
  8423. }
  8424. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
  8425. {
  8426. g.NavInitRequest = false; // Found a match, clear request
  8427. NavUpdateAnyRequestFlag();
  8428. }
  8429. }
  8430. // Process Move Request (scoring for navigation)
  8431. // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
  8432. if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))
  8433. {
  8434. ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  8435. #if IMGUI_DEBUG_NAV_SCORING
  8436. // [DEBUG] Score all items in NavWindow at all times
  8437. if (!g.NavMoveRequest)
  8438. g.NavMoveDir = g.NavMoveDirLast;
  8439. bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
  8440. #else
  8441. bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
  8442. #endif
  8443. if (new_best)
  8444. NavApplyItemToResult(result, window, id, nav_bb_rel);
  8445. // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
  8446. const float VISIBLE_RATIO = 0.70f;
  8447. if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
  8448. 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)
  8449. if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
  8450. NavApplyItemToResult(&g.NavMoveResultLocalVisibleSet, window, id, nav_bb_rel);
  8451. }
  8452. // Update window-relative bounding box of navigated item
  8453. if (g.NavId == id)
  8454. {
  8455. g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
  8456. g.NavLayer = window->DC.NavLayerCurrent;
  8457. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  8458. g.NavIdIsAlive = true;
  8459. window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
  8460. }
  8461. }
  8462. bool ImGui::NavMoveRequestButNoResultYet()
  8463. {
  8464. ImGuiContext& g = *GImGui;
  8465. return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
  8466. }
  8467. void ImGui::NavMoveRequestCancel()
  8468. {
  8469. ImGuiContext& g = *GImGui;
  8470. g.NavMoveRequest = false;
  8471. NavUpdateAnyRequestFlag();
  8472. }
  8473. void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
  8474. {
  8475. ImGuiContext& g = *GImGui;
  8476. IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
  8477. NavMoveRequestCancel();
  8478. g.NavMoveDir = move_dir;
  8479. g.NavMoveClipDir = clip_dir;
  8480. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
  8481. g.NavMoveRequestFlags = move_flags;
  8482. g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
  8483. }
  8484. void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
  8485. {
  8486. ImGuiContext& g = *GImGui;
  8487. // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
  8488. // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
  8489. g.NavWrapRequestWindow = window;
  8490. g.NavWrapRequestFlags = move_flags;
  8491. }
  8492. // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
  8493. // This way we could find the last focused window among our children. It would be much less confusing this way?
  8494. static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
  8495. {
  8496. ImGuiWindow* parent = nav_window;
  8497. while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  8498. parent = parent->ParentWindow;
  8499. if (parent && parent != nav_window)
  8500. parent->NavLastChildNavWindow = nav_window;
  8501. }
  8502. // Restore the last focused child.
  8503. // Call when we are expected to land on the Main Layer (0) after FocusWindow()
  8504. static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
  8505. {
  8506. if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
  8507. return window->NavLastChildNavWindow;
  8508. if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
  8509. if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
  8510. return tab->Window;
  8511. return window;
  8512. }
  8513. void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
  8514. {
  8515. ImGuiContext& g = *GImGui;
  8516. if (layer == ImGuiNavLayer_Main)
  8517. g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);
  8518. ImGuiWindow* window = g.NavWindow;
  8519. if (window->NavLastIds[layer] != 0)
  8520. {
  8521. SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
  8522. g.NavDisableHighlight = false;
  8523. g.NavDisableMouseHover = g.NavMousePosDirty = true;
  8524. }
  8525. else
  8526. {
  8527. g.NavLayer = layer;
  8528. NavInitWindow(window, true);
  8529. }
  8530. }
  8531. static inline void ImGui::NavUpdateAnyRequestFlag()
  8532. {
  8533. ImGuiContext& g = *GImGui;
  8534. g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
  8535. if (g.NavAnyRequest)
  8536. IM_ASSERT(g.NavWindow != NULL);
  8537. }
  8538. // This needs to be called before we submit any widget (aka in or before Begin)
  8539. void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
  8540. {
  8541. // FIXME: ChildWindow test here is wrong for docking
  8542. ImGuiContext& g = *GImGui;
  8543. IM_ASSERT(window == g.NavWindow);
  8544. if (window->Flags & ImGuiWindowFlags_NoNavInputs)
  8545. {
  8546. g.NavId = g.NavFocusScopeId = 0;
  8547. return;
  8548. }
  8549. bool init_for_nav = false;
  8550. if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
  8551. init_for_nav = true;
  8552. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
  8553. if (init_for_nav)
  8554. {
  8555. SetNavID(0, g.NavLayer, 0, ImRect());
  8556. g.NavInitRequest = true;
  8557. g.NavInitRequestFromMove = false;
  8558. g.NavInitResultId = 0;
  8559. g.NavInitResultRectRel = ImRect();
  8560. NavUpdateAnyRequestFlag();
  8561. }
  8562. else
  8563. {
  8564. g.NavId = window->NavLastIds[0];
  8565. g.NavFocusScopeId = 0;
  8566. }
  8567. }
  8568. static ImVec2 ImGui::NavCalcPreferredRefPos()
  8569. {
  8570. ImGuiContext& g = *GImGui;
  8571. if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
  8572. {
  8573. // Mouse (we need a fallback in case the mouse becomes invalid after being used)
  8574. if (IsMousePosValid(&g.IO.MousePos))
  8575. return g.IO.MousePos;
  8576. return g.LastValidMousePos;
  8577. }
  8578. else
  8579. {
  8580. // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
  8581. const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
  8582. ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
  8583. ImGuiViewport* viewport = g.NavWindow->Viewport;
  8584. 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.
  8585. }
  8586. }
  8587. float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
  8588. {
  8589. ImGuiContext& g = *GImGui;
  8590. if (mode == ImGuiInputReadMode_Down)
  8591. return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
  8592. const float t = g.IO.NavInputsDownDuration[n];
  8593. if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
  8594. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
  8595. if (t < 0.0f)
  8596. return 0.0f;
  8597. if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
  8598. return (t == 0.0f) ? 1.0f : 0.0f;
  8599. if (mode == ImGuiInputReadMode_Repeat)
  8600. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
  8601. if (mode == ImGuiInputReadMode_RepeatSlow)
  8602. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
  8603. if (mode == ImGuiInputReadMode_RepeatFast)
  8604. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
  8605. return 0.0f;
  8606. }
  8607. ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
  8608. {
  8609. ImVec2 delta(0.0f, 0.0f);
  8610. if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
  8611. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
  8612. if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
  8613. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
  8614. if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
  8615. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
  8616. if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
  8617. delta *= slow_factor;
  8618. if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
  8619. delta *= fast_factor;
  8620. return delta;
  8621. }
  8622. static void ImGui::NavUpdate()
  8623. {
  8624. ImGuiContext& g = *GImGui;
  8625. ImGuiIO& io = g.IO;
  8626. io.WantSetMousePos = false;
  8627. g.NavWrapRequestWindow = NULL;
  8628. g.NavWrapRequestFlags = ImGuiNavMoveFlags_None;
  8629. #if 0
  8630. if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
  8631. #endif
  8632. // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
  8633. // (do it before we map Keyboard input!)
  8634. bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  8635. bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  8636. if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_Gamepad)
  8637. {
  8638. if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f
  8639. || io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f)
  8640. g.NavInputSource = ImGuiInputSource_Gamepad;
  8641. }
  8642. // Update Keyboard->Nav inputs mapping
  8643. if (nav_keyboard_active)
  8644. {
  8645. #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(io.KeyMap[_KEY])) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_Keyboard; } } while (0)
  8646. NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
  8647. NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
  8648. NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
  8649. NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
  8650. NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
  8651. NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
  8652. NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
  8653. if (io.KeyCtrl)
  8654. io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
  8655. if (io.KeyShift)
  8656. io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
  8657. // AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl)
  8658. // But also even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
  8659. if (io.KeyAlt && !io.KeyCtrl)
  8660. io.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
  8661. // We automatically cancel toggling nav layer when any text has been typed while holding Alt. (See #370)
  8662. if (io.KeyAlt && !io.KeyCtrl && g.NavWindowingToggleLayer && io.InputQueueCharacters.Size > 0)
  8663. g.NavWindowingToggleLayer = false;
  8664. #undef NAV_MAP_KEY
  8665. }
  8666. memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration));
  8667. for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
  8668. io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f;
  8669. // Process navigation init request (select first/default focus)
  8670. if (g.NavInitResultId != 0)
  8671. NavUpdateInitResult();
  8672. g.NavInitRequest = false;
  8673. g.NavInitRequestFromMove = false;
  8674. g.NavInitResultId = 0;
  8675. g.NavJustMovedToId = 0;
  8676. // Process navigation move request
  8677. if (g.NavMoveRequest)
  8678. NavUpdateMoveResult();
  8679. // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
  8680. if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
  8681. {
  8682. IM_ASSERT(g.NavMoveRequest);
  8683. if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
  8684. g.NavDisableHighlight = false;
  8685. g.NavMoveRequestForward = ImGuiNavForward_None;
  8686. }
  8687. // Apply application mouse position movement, after we had a chance to process move request result.
  8688. if (g.NavMousePosDirty && g.NavIdIsAlive)
  8689. {
  8690. // Set mouse position given our knowledge of the navigated item position from last frame
  8691. if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
  8692. if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
  8693. {
  8694. io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
  8695. io.WantSetMousePos = true;
  8696. }
  8697. g.NavMousePosDirty = false;
  8698. }
  8699. g.NavIdIsAlive = false;
  8700. g.NavJustTabbedId = 0;
  8701. IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
  8702. // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
  8703. if (g.NavWindow)
  8704. NavSaveLastChildNavWindowIntoParent(g.NavWindow);
  8705. if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
  8706. g.NavWindow->NavLastChildNavWindow = NULL;
  8707. // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
  8708. NavUpdateWindowing();
  8709. // Set output flags for user application
  8710. io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
  8711. io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
  8712. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  8713. if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
  8714. {
  8715. IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n");
  8716. if (g.ActiveId != 0)
  8717. {
  8718. if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
  8719. ClearActiveID();
  8720. }
  8721. else if (g.NavLayer != ImGuiNavLayer_Main)
  8722. {
  8723. // Leave the "menu" layer
  8724. NavRestoreLayer(ImGuiNavLayer_Main);
  8725. }
  8726. else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
  8727. {
  8728. // Exit child window
  8729. ImGuiWindow* child_window = g.NavWindow;
  8730. ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
  8731. IM_ASSERT(child_window->ChildId != 0);
  8732. ImRect child_rect = child_window->Rect();
  8733. FocusWindow(parent_window);
  8734. SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, ImRect(child_rect.Min - parent_window->Pos, child_rect.Max - parent_window->Pos));
  8735. }
  8736. else if (g.OpenPopupStack.Size > 0)
  8737. {
  8738. // Close open popup/menu
  8739. if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
  8740. ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
  8741. }
  8742. else
  8743. {
  8744. // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
  8745. if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
  8746. g.NavWindow->NavLastIds[0] = 0;
  8747. g.NavId = g.NavFocusScopeId = 0;
  8748. }
  8749. }
  8750. // Process manual activation request
  8751. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
  8752. if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8753. {
  8754. bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
  8755. bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
  8756. if (g.ActiveId == 0 && activate_pressed)
  8757. g.NavActivateId = g.NavId;
  8758. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
  8759. g.NavActivateDownId = g.NavId;
  8760. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
  8761. g.NavActivatePressedId = g.NavId;
  8762. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
  8763. g.NavInputId = g.NavId;
  8764. }
  8765. if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8766. g.NavDisableHighlight = true;
  8767. if (g.NavActivateId != 0)
  8768. IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
  8769. g.NavMoveRequest = false;
  8770. // Process programmatic activation request
  8771. if (g.NavNextActivateId != 0)
  8772. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
  8773. g.NavNextActivateId = 0;
  8774. // Initiate directional inputs request
  8775. if (g.NavMoveRequestForward == ImGuiNavForward_None)
  8776. {
  8777. g.NavMoveDir = ImGuiDir_None;
  8778. g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
  8779. if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8780. {
  8781. const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
  8782. if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
  8783. if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
  8784. if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
  8785. if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
  8786. }
  8787. g.NavMoveClipDir = g.NavMoveDir;
  8788. }
  8789. else
  8790. {
  8791. // 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)
  8792. // (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
  8793. IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
  8794. IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
  8795. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
  8796. g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
  8797. }
  8798. // Update PageUp/PageDown/Home/End scroll
  8799. // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
  8800. float nav_scoring_rect_offset_y = 0.0f;
  8801. if (nav_keyboard_active)
  8802. nav_scoring_rect_offset_y = NavUpdatePageUpPageDown();
  8803. // If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
  8804. if (g.NavMoveDir != ImGuiDir_None)
  8805. {
  8806. g.NavMoveRequest = true;
  8807. g.NavMoveRequestKeyMods = io.KeyMods;
  8808. g.NavMoveDirLast = g.NavMoveDir;
  8809. }
  8810. if (g.NavMoveRequest && g.NavId == 0)
  8811. {
  8812. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
  8813. g.NavInitRequest = g.NavInitRequestFromMove = true;
  8814. // Reassigning with same value, we're being explicit here.
  8815. g.NavInitResultId = 0; // -V1048
  8816. g.NavDisableHighlight = false;
  8817. }
  8818. NavUpdateAnyRequestFlag();
  8819. // Scrolling
  8820. if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
  8821. {
  8822. // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
  8823. ImGuiWindow* window = g.NavWindow;
  8824. 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.
  8825. if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
  8826. {
  8827. if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
  8828. SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
  8829. if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
  8830. SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
  8831. }
  8832. // *Normal* Manual scroll with NavScrollXXX keys
  8833. // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
  8834. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f);
  8835. if (scroll_dir.x != 0.0f && window->ScrollbarX)
  8836. SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
  8837. if (scroll_dir.y != 0.0f)
  8838. SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
  8839. }
  8840. // Reset search results
  8841. g.NavMoveResultLocal.Clear();
  8842. g.NavMoveResultLocalVisibleSet.Clear();
  8843. g.NavMoveResultOther.Clear();
  8844. // When using gamepad, we project the reference nav bounding box into window visible area.
  8845. // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative
  8846. // (can't focus a visible object like we can with the mouse).
  8847. if (g.NavMoveRequest && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main)
  8848. {
  8849. ImGuiWindow* window = g.NavWindow;
  8850. ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1));
  8851. if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
  8852. {
  8853. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel\n");
  8854. float pad = window->CalcFontSize() * 0.5f;
  8855. window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
  8856. window->NavRectRel[g.NavLayer].ClipWithFull(window_rect_rel);
  8857. g.NavId = g.NavFocusScopeId = 0;
  8858. }
  8859. }
  8860. // 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)
  8861. ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
  8862. g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : ImRect(0, 0, 0, 0);
  8863. g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y);
  8864. g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x);
  8865. g.NavScoringRect.Max.x = g.NavScoringRect.Min.x;
  8866. IM_ASSERT(!g.NavScoringRect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
  8867. //GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
  8868. g.NavScoringCount = 0;
  8869. #if IMGUI_DEBUG_NAV_RECTS
  8870. if (g.NavWindow)
  8871. {
  8872. ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
  8873. if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
  8874. 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); }
  8875. }
  8876. #endif
  8877. }
  8878. static void ImGui::NavUpdateInitResult()
  8879. {
  8880. // 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)
  8881. ImGuiContext& g = *GImGui;
  8882. if (!g.NavWindow)
  8883. return;
  8884. // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
  8885. // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
  8886. IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
  8887. SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
  8888. if (g.NavInitRequestFromMove)
  8889. {
  8890. g.NavDisableHighlight = false;
  8891. g.NavDisableMouseHover = g.NavMousePosDirty = true;
  8892. }
  8893. }
  8894. // Apply result from previous frame navigation directional move request
  8895. static void ImGui::NavUpdateMoveResult()
  8896. {
  8897. ImGuiContext& g = *GImGui;
  8898. if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
  8899. {
  8900. // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
  8901. if (g.NavId != 0)
  8902. {
  8903. g.NavDisableHighlight = false;
  8904. g.NavDisableMouseHover = true;
  8905. }
  8906. return;
  8907. }
  8908. // Select which result to use
  8909. ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  8910. // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
  8911. if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
  8912. if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
  8913. result = &g.NavMoveResultLocalVisibleSet;
  8914. // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
  8915. if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
  8916. if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
  8917. result = &g.NavMoveResultOther;
  8918. IM_ASSERT(g.NavWindow && result->Window);
  8919. // Scroll to keep newly navigated item fully into view.
  8920. if (g.NavLayer == ImGuiNavLayer_Main)
  8921. {
  8922. ImVec2 delta_scroll;
  8923. if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
  8924. {
  8925. float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
  8926. delta_scroll.y = result->Window->Scroll.y - scroll_target;
  8927. SetScrollY(result->Window, scroll_target);
  8928. }
  8929. else
  8930. {
  8931. ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
  8932. delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
  8933. }
  8934. // Offset our result position so mouse position can be applied immediately after in NavUpdate()
  8935. result->RectRel.TranslateX(-delta_scroll.x);
  8936. result->RectRel.TranslateY(-delta_scroll.y);
  8937. }
  8938. ClearActiveID();
  8939. g.NavWindow = result->Window;
  8940. if (g.NavId != result->ID)
  8941. {
  8942. // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
  8943. g.NavJustMovedToId = result->ID;
  8944. g.NavJustMovedToFocusScopeId = result->FocusScopeId;
  8945. g.NavJustMovedToKeyMods = g.NavMoveRequestKeyMods;
  8946. }
  8947. IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
  8948. SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
  8949. g.NavDisableHighlight = false;
  8950. g.NavDisableMouseHover = g.NavMousePosDirty = true;
  8951. }
  8952. // Handle PageUp/PageDown/Home/End keys
  8953. static float ImGui::NavUpdatePageUpPageDown()
  8954. {
  8955. ImGuiContext& g = *GImGui;
  8956. ImGuiIO& io = g.IO;
  8957. if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
  8958. return 0.0f;
  8959. if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != ImGuiNavLayer_Main)
  8960. return 0.0f;
  8961. ImGuiWindow* window = g.NavWindow;
  8962. const bool page_up_held = IsKeyDown(io.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
  8963. const bool page_down_held = IsKeyDown(io.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
  8964. const bool home_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
  8965. const bool end_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
  8966. if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
  8967. {
  8968. if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
  8969. {
  8970. // Fallback manual-scroll when window has no navigable item
  8971. if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
  8972. SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
  8973. else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
  8974. SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
  8975. else if (home_pressed)
  8976. SetScrollY(window, 0.0f);
  8977. else if (end_pressed)
  8978. SetScrollY(window, window->ScrollMax.y);
  8979. }
  8980. else
  8981. {
  8982. ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
  8983. const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
  8984. float nav_scoring_rect_offset_y = 0.0f;
  8985. if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
  8986. {
  8987. nav_scoring_rect_offset_y = -page_offset_y;
  8988. 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)
  8989. g.NavMoveClipDir = ImGuiDir_Up;
  8990. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  8991. }
  8992. else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
  8993. {
  8994. nav_scoring_rect_offset_y = +page_offset_y;
  8995. 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)
  8996. g.NavMoveClipDir = ImGuiDir_Down;
  8997. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  8998. }
  8999. else if (home_pressed)
  9000. {
  9001. // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
  9002. // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
  9003. // Preserve current horizontal position if we have any.
  9004. nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
  9005. if (nav_rect_rel.IsInverted())
  9006. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  9007. g.NavMoveDir = ImGuiDir_Down;
  9008. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
  9009. }
  9010. else if (end_pressed)
  9011. {
  9012. nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
  9013. if (nav_rect_rel.IsInverted())
  9014. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  9015. g.NavMoveDir = ImGuiDir_Up;
  9016. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
  9017. }
  9018. return nav_scoring_rect_offset_y;
  9019. }
  9020. }
  9021. return 0.0f;
  9022. }
  9023. static void ImGui::NavEndFrame()
  9024. {
  9025. ImGuiContext& g = *GImGui;
  9026. // Show CTRL+TAB list window
  9027. if (g.NavWindowingTarget != NULL)
  9028. NavUpdateWindowingOverlay();
  9029. // Perform wrap-around in menus
  9030. ImGuiWindow* window = g.NavWrapRequestWindow;
  9031. ImGuiNavMoveFlags move_flags = g.NavWrapRequestFlags;
  9032. if (window != NULL && g.NavWindow == window && NavMoveRequestButNoResultYet() && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == ImGuiNavLayer_Main)
  9033. {
  9034. IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
  9035. ImRect bb_rel = window->NavRectRel[0];
  9036. ImGuiDir clip_dir = g.NavMoveDir;
  9037. if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  9038. {
  9039. bb_rel.Min.x = bb_rel.Max.x =
  9040. ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
  9041. if (move_flags & ImGuiNavMoveFlags_WrapX)
  9042. {
  9043. bb_rel.TranslateY(-bb_rel.GetHeight());
  9044. clip_dir = ImGuiDir_Up;
  9045. }
  9046. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  9047. }
  9048. if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  9049. {
  9050. bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
  9051. if (move_flags & ImGuiNavMoveFlags_WrapX)
  9052. {
  9053. bb_rel.TranslateY(+bb_rel.GetHeight());
  9054. clip_dir = ImGuiDir_Down;
  9055. }
  9056. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  9057. }
  9058. if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  9059. {
  9060. bb_rel.Min.y = bb_rel.Max.y =
  9061. ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
  9062. if (move_flags & ImGuiNavMoveFlags_WrapY)
  9063. {
  9064. bb_rel.TranslateX(-bb_rel.GetWidth());
  9065. clip_dir = ImGuiDir_Left;
  9066. }
  9067. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  9068. }
  9069. if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  9070. {
  9071. bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
  9072. if (move_flags & ImGuiNavMoveFlags_WrapY)
  9073. {
  9074. bb_rel.TranslateX(+bb_rel.GetWidth());
  9075. clip_dir = ImGuiDir_Right;
  9076. }
  9077. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  9078. }
  9079. }
  9080. }
  9081. static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
  9082. {
  9083. ImGuiContext& g = *GImGui;
  9084. IM_UNUSED(g);
  9085. int order = window->FocusOrder;
  9086. IM_ASSERT(g.WindowsFocusOrder[order] == window);
  9087. return order;
  9088. }
  9089. static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
  9090. {
  9091. ImGuiContext& g = *GImGui;
  9092. for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
  9093. if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
  9094. return g.WindowsFocusOrder[i];
  9095. return NULL;
  9096. }
  9097. static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
  9098. {
  9099. ImGuiContext& g = *GImGui;
  9100. IM_ASSERT(g.NavWindowingTarget);
  9101. if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
  9102. return;
  9103. const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
  9104. ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
  9105. if (!window_target)
  9106. window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
  9107. if (window_target) // Don't reset windowing target if there's a single window in the list
  9108. g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
  9109. g.NavWindowingToggleLayer = false;
  9110. }
  9111. // Windowing management mode
  9112. // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
  9113. // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
  9114. static void ImGui::NavUpdateWindowing()
  9115. {
  9116. ImGuiContext& g = *GImGui;
  9117. ImGuiWindow* apply_focus_window = NULL;
  9118. bool apply_toggle_layer = false;
  9119. ImGuiWindow* modal_window = GetTopMostPopupModal();
  9120. bool allow_windowing = (modal_window == NULL);
  9121. if (!allow_windowing)
  9122. g.NavWindowingTarget = NULL;
  9123. // Fade out
  9124. if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
  9125. {
  9126. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
  9127. if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
  9128. g.NavWindowingTargetAnim = NULL;
  9129. }
  9130. // Start CTRL-TAB or Square+L/R window selection
  9131. bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
  9132. bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
  9133. if (start_windowing_with_gamepad || start_windowing_with_keyboard)
  9134. if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
  9135. {
  9136. g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
  9137. g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
  9138. g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
  9139. g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
  9140. }
  9141. // Gamepad update
  9142. g.NavWindowingTimer += g.IO.DeltaTime;
  9143. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
  9144. {
  9145. // 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
  9146. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
  9147. // Select window to focus
  9148. const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
  9149. if (focus_change_dir != 0)
  9150. {
  9151. NavUpdateWindowingHighlightWindow(focus_change_dir);
  9152. g.NavWindowingHighlightAlpha = 1.0f;
  9153. }
  9154. // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
  9155. if (!IsNavInputDown(ImGuiNavInput_Menu))
  9156. {
  9157. g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
  9158. if (g.NavWindowingToggleLayer && g.NavWindow)
  9159. apply_toggle_layer = true;
  9160. else if (!g.NavWindowingToggleLayer)
  9161. apply_focus_window = g.NavWindowingTarget;
  9162. g.NavWindowingTarget = NULL;
  9163. }
  9164. }
  9165. // Keyboard: Focus
  9166. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
  9167. {
  9168. // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
  9169. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
  9170. if (IsKeyPressedMap(ImGuiKey_Tab, true))
  9171. NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
  9172. if (!g.IO.KeyCtrl)
  9173. apply_focus_window = g.NavWindowingTarget;
  9174. }
  9175. // Keyboard: Press and Release ALT to toggle menu layer
  9176. // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of backend clearing releases all keys on ALT-TAB
  9177. if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
  9178. g.NavWindowingToggleLayer = true;
  9179. if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
  9180. if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
  9181. apply_toggle_layer = true;
  9182. // Move window
  9183. if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
  9184. {
  9185. ImVec2 move_delta;
  9186. if (g.NavInputSource == ImGuiInputSource_Keyboard && !g.IO.KeyShift)
  9187. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  9188. if (g.NavInputSource == ImGuiInputSource_Gamepad)
  9189. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
  9190. if (move_delta.x != 0.0f || move_delta.y != 0.0f)
  9191. {
  9192. const float NAV_MOVE_SPEED = 800.0f;
  9193. const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well
  9194. ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
  9195. SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always);
  9196. MarkIniSettingsDirty(moving_window);
  9197. g.NavDisableMouseHover = true;
  9198. }
  9199. }
  9200. // Apply final focus
  9201. if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
  9202. {
  9203. ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
  9204. ClearActiveID();
  9205. g.NavDisableHighlight = false;
  9206. g.NavDisableMouseHover = true;
  9207. apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
  9208. ClosePopupsOverWindow(apply_focus_window, false);
  9209. FocusWindow(apply_focus_window);
  9210. if (apply_focus_window->NavLastIds[0] == 0)
  9211. NavInitWindow(apply_focus_window, false);
  9212. // If the window has ONLY a menu layer (no main layer), select it directly
  9213. // FIXME-NAV: This should be done in NavInit.. or in FocusWindow..
  9214. if (apply_focus_window->DC.NavLayersActiveMask == (1 << ImGuiNavLayer_Menu))
  9215. g.NavLayer = ImGuiNavLayer_Menu;
  9216. // Request OS level focus
  9217. if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
  9218. g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
  9219. }
  9220. if (apply_focus_window)
  9221. g.NavWindowingTarget = NULL;
  9222. // Apply menu/layer toggle
  9223. if (apply_toggle_layer && g.NavWindow)
  9224. {
  9225. ClearActiveID();
  9226. // Move to parent menu if necessary
  9227. ImGuiWindow* new_nav_window = g.NavWindow;
  9228. while (new_nav_window->ParentWindow
  9229. && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
  9230. && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
  9231. && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  9232. new_nav_window = new_nav_window->ParentWindow;
  9233. if (new_nav_window != g.NavWindow)
  9234. {
  9235. ImGuiWindow* old_nav_window = g.NavWindow;
  9236. FocusWindow(new_nav_window);
  9237. new_nav_window->NavLastChildNavWindow = old_nav_window;
  9238. }
  9239. g.NavDisableHighlight = false;
  9240. g.NavDisableMouseHover = true;
  9241. // Reinitialize navigation when entering menu bar with the Alt key.
  9242. const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
  9243. const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
  9244. if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
  9245. g.NavWindow->NavLastIds[new_nav_layer] = 0;
  9246. NavRestoreLayer(new_nav_layer);
  9247. }
  9248. }
  9249. // Window has already passed the IsWindowNavFocusable()
  9250. static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
  9251. {
  9252. if (window->Flags & ImGuiWindowFlags_Popup)
  9253. return "(Popup)";
  9254. if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
  9255. return "(Main menu bar)";
  9256. if (window->DockNodeAsHost)
  9257. return "(Dock node)";
  9258. return "(Untitled)";
  9259. }
  9260. // Overlay displayed when using CTRL+TAB. Called by EndFrame().
  9261. void ImGui::NavUpdateWindowingOverlay()
  9262. {
  9263. ImGuiContext& g = *GImGui;
  9264. IM_ASSERT(g.NavWindowingTarget != NULL);
  9265. if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
  9266. return;
  9267. if (g.NavWindowingListWindow == NULL)
  9268. g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
  9269. const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
  9270. SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
  9271. SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
  9272. PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
  9273. Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
  9274. for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
  9275. {
  9276. ImGuiWindow* window = g.WindowsFocusOrder[n];
  9277. IM_ASSERT(window != NULL); // Fix static analyzers
  9278. if (!IsWindowNavFocusable(window))
  9279. continue;
  9280. const char* label = window->Name;
  9281. if (label == FindRenderedTextEnd(label))
  9282. label = GetFallbackWindowNameForWindowingList(window);
  9283. Selectable(label, g.NavWindowingTarget == window);
  9284. }
  9285. End();
  9286. PopStyleVar();
  9287. }
  9288. //-----------------------------------------------------------------------------
  9289. // [SECTION] DRAG AND DROP
  9290. //-----------------------------------------------------------------------------
  9291. void ImGui::ClearDragDrop()
  9292. {
  9293. ImGuiContext& g = *GImGui;
  9294. g.DragDropActive = false;
  9295. g.DragDropPayload.Clear();
  9296. g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
  9297. g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
  9298. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  9299. g.DragDropAcceptFrameCount = -1;
  9300. g.DragDropPayloadBufHeap.clear();
  9301. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  9302. }
  9303. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
  9304. // If the item has an identifier:
  9305. // - This assume/require the item to be activated (typically via ButtonBehavior).
  9306. // - 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.
  9307. // - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
  9308. // If the item has no identifier:
  9309. // - Currently always assume left mouse button.
  9310. bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
  9311. {
  9312. ImGuiContext& g = *GImGui;
  9313. ImGuiWindow* window = g.CurrentWindow;
  9314. // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
  9315. // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
  9316. ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
  9317. bool source_drag_active = false;
  9318. ImGuiID source_id = 0;
  9319. ImGuiID source_parent_id = 0;
  9320. if (!(flags & ImGuiDragDropFlags_SourceExtern))
  9321. {
  9322. source_id = window->DC.LastItemId;
  9323. if (source_id != 0)
  9324. {
  9325. // Common path: items with ID
  9326. if (g.ActiveId != source_id)
  9327. return false;
  9328. if (g.ActiveIdMouseButton != -1)
  9329. mouse_button = g.ActiveIdMouseButton;
  9330. if (g.IO.MouseDown[mouse_button] == false)
  9331. return false;
  9332. g.ActiveIdAllowOverlap = false;
  9333. }
  9334. else
  9335. {
  9336. // Uncommon path: items without ID
  9337. if (g.IO.MouseDown[mouse_button] == false)
  9338. return false;
  9339. // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
  9340. // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
  9341. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
  9342. {
  9343. IM_ASSERT(0);
  9344. return false;
  9345. }
  9346. // Early out
  9347. if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
  9348. return false;
  9349. // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
  9350. // We build a throwaway ID based on current ID stack + relative AABB of items in window.
  9351. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
  9352. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
  9353. source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
  9354. bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
  9355. if (is_hovered && g.IO.MouseClicked[mouse_button])
  9356. {
  9357. SetActiveID(source_id, window);
  9358. FocusWindow(window);
  9359. }
  9360. if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
  9361. g.ActiveIdAllowOverlap = is_hovered;
  9362. }
  9363. if (g.ActiveId != source_id)
  9364. return false;
  9365. source_parent_id = window->IDStack.back();
  9366. source_drag_active = IsMouseDragging(mouse_button);
  9367. // Disable navigation and key inputs while dragging
  9368. g.ActiveIdUsingNavDirMask = ~(ImU32)0;
  9369. g.ActiveIdUsingNavInputMask = ~(ImU32)0;
  9370. g.ActiveIdUsingKeyInputMask = ~(ImU64)0;
  9371. }
  9372. else
  9373. {
  9374. window = NULL;
  9375. source_id = ImHashStr("#SourceExtern");
  9376. source_drag_active = true;
  9377. }
  9378. if (source_drag_active)
  9379. {
  9380. if (!g.DragDropActive)
  9381. {
  9382. IM_ASSERT(source_id != 0);
  9383. ClearDragDrop();
  9384. ImGuiPayload& payload = g.DragDropPayload;
  9385. payload.SourceId = source_id;
  9386. payload.SourceParentId = source_parent_id;
  9387. g.DragDropActive = true;
  9388. g.DragDropSourceFlags = flags;
  9389. g.DragDropMouseButton = mouse_button;
  9390. if (payload.SourceId == g.ActiveId)
  9391. g.ActiveIdNoClearOnFocusLoss = true;
  9392. }
  9393. g.DragDropSourceFrameCount = g.FrameCount;
  9394. g.DragDropWithinSource = true;
  9395. if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  9396. {
  9397. // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
  9398. // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
  9399. BeginTooltip();
  9400. if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
  9401. {
  9402. ImGuiWindow* tooltip_window = g.CurrentWindow;
  9403. tooltip_window->SkipItems = true;
  9404. tooltip_window->HiddenFramesCanSkipItems = 1;
  9405. }
  9406. }
  9407. if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
  9408. window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
  9409. return true;
  9410. }
  9411. return false;
  9412. }
  9413. void ImGui::EndDragDropSource()
  9414. {
  9415. ImGuiContext& g = *GImGui;
  9416. IM_ASSERT(g.DragDropActive);
  9417. IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
  9418. if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  9419. EndTooltip();
  9420. // Discard the drag if have not called SetDragDropPayload()
  9421. if (g.DragDropPayload.DataFrameCount == -1)
  9422. ClearDragDrop();
  9423. g.DragDropWithinSource = false;
  9424. }
  9425. // Use 'cond' to choose to submit payload on drag start or every frame
  9426. bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
  9427. {
  9428. ImGuiContext& g = *GImGui;
  9429. ImGuiPayload& payload = g.DragDropPayload;
  9430. if (cond == 0)
  9431. cond = ImGuiCond_Always;
  9432. IM_ASSERT(type != NULL);
  9433. IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
  9434. IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
  9435. IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
  9436. IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
  9437. if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
  9438. {
  9439. // Copy payload
  9440. ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
  9441. g.DragDropPayloadBufHeap.resize(0);
  9442. if (data_size > sizeof(g.DragDropPayloadBufLocal))
  9443. {
  9444. // Store in heap
  9445. g.DragDropPayloadBufHeap.resize((int)data_size);
  9446. payload.Data = g.DragDropPayloadBufHeap.Data;
  9447. memcpy(payload.Data, data, data_size);
  9448. }
  9449. else if (data_size > 0)
  9450. {
  9451. // Store locally
  9452. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  9453. payload.Data = g.DragDropPayloadBufLocal;
  9454. memcpy(payload.Data, data, data_size);
  9455. }
  9456. else
  9457. {
  9458. payload.Data = NULL;
  9459. }
  9460. payload.DataSize = (int)data_size;
  9461. }
  9462. payload.DataFrameCount = g.FrameCount;
  9463. return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
  9464. }
  9465. bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
  9466. {
  9467. ImGuiContext& g = *GImGui;
  9468. if (!g.DragDropActive)
  9469. return false;
  9470. ImGuiWindow* window = g.CurrentWindow;
  9471. ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
  9472. if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
  9473. return false;
  9474. IM_ASSERT(id != 0);
  9475. if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
  9476. return false;
  9477. if (window->SkipItems)
  9478. return false;
  9479. IM_ASSERT(g.DragDropWithinTarget == false);
  9480. g.DragDropTargetRect = bb;
  9481. g.DragDropTargetId = id;
  9482. g.DragDropWithinTarget = true;
  9483. return true;
  9484. }
  9485. // We don't use BeginDragDropTargetCustom() and duplicate its code because:
  9486. // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
  9487. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
  9488. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
  9489. bool ImGui::BeginDragDropTarget()
  9490. {
  9491. ImGuiContext& g = *GImGui;
  9492. if (!g.DragDropActive)
  9493. return false;
  9494. ImGuiWindow* window = g.CurrentWindow;
  9495. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  9496. return false;
  9497. ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
  9498. if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
  9499. return false;
  9500. const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
  9501. ImGuiID id = window->DC.LastItemId;
  9502. if (id == 0)
  9503. id = window->GetIDFromRectangle(display_rect);
  9504. if (g.DragDropPayload.SourceId == id)
  9505. return false;
  9506. IM_ASSERT(g.DragDropWithinTarget == false);
  9507. g.DragDropTargetRect = display_rect;
  9508. g.DragDropTargetId = id;
  9509. g.DragDropWithinTarget = true;
  9510. return true;
  9511. }
  9512. bool ImGui::IsDragDropPayloadBeingAccepted()
  9513. {
  9514. ImGuiContext& g = *GImGui;
  9515. return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
  9516. }
  9517. const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
  9518. {
  9519. ImGuiContext& g = *GImGui;
  9520. ImGuiWindow* window = g.CurrentWindow;
  9521. ImGuiPayload& payload = g.DragDropPayload;
  9522. IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
  9523. IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
  9524. if (type != NULL && !payload.IsDataType(type))
  9525. return NULL;
  9526. // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
  9527. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
  9528. const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
  9529. ImRect r = g.DragDropTargetRect;
  9530. float r_surface = r.GetWidth() * r.GetHeight();
  9531. if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
  9532. {
  9533. g.DragDropAcceptFlags = flags;
  9534. g.DragDropAcceptIdCurr = g.DragDropTargetId;
  9535. g.DragDropAcceptIdCurrRectSurface = r_surface;
  9536. }
  9537. // Render default drop visuals
  9538. payload.Preview = was_accepted_previously;
  9539. flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
  9540. if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
  9541. {
  9542. // FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
  9543. r.Expand(3.5f);
  9544. bool push_clip_rect = !window->ClipRect.Contains(r);
  9545. if (push_clip_rect) window->DrawList->PushClipRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1));
  9546. window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
  9547. if (push_clip_rect) window->DrawList->PopClipRect();
  9548. }
  9549. g.DragDropAcceptFrameCount = g.FrameCount;
  9550. 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()
  9551. if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
  9552. return NULL;
  9553. return &payload;
  9554. }
  9555. const ImGuiPayload* ImGui::GetDragDropPayload()
  9556. {
  9557. ImGuiContext& g = *GImGui;
  9558. return g.DragDropActive ? &g.DragDropPayload : NULL;
  9559. }
  9560. // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
  9561. void ImGui::EndDragDropTarget()
  9562. {
  9563. ImGuiContext& g = *GImGui;
  9564. IM_ASSERT(g.DragDropActive);
  9565. IM_ASSERT(g.DragDropWithinTarget);
  9566. g.DragDropWithinTarget = false;
  9567. }
  9568. //-----------------------------------------------------------------------------
  9569. // [SECTION] LOGGING/CAPTURING
  9570. //-----------------------------------------------------------------------------
  9571. // All text output from the interface can be captured into tty/file/clipboard.
  9572. // By default, tree nodes are automatically opened during logging.
  9573. //-----------------------------------------------------------------------------
  9574. // Pass text data straight to log (without being displayed)
  9575. static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
  9576. {
  9577. if (g.LogFile)
  9578. {
  9579. g.LogBuffer.Buf.resize(0);
  9580. g.LogBuffer.appendfv(fmt, args);
  9581. ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
  9582. }
  9583. else
  9584. {
  9585. g.LogBuffer.appendfv(fmt, args);
  9586. }
  9587. }
  9588. void ImGui::LogText(const char* fmt, ...)
  9589. {
  9590. ImGuiContext& g = *GImGui;
  9591. if (!g.LogEnabled)
  9592. return;
  9593. va_list args;
  9594. va_start(args, fmt);
  9595. LogTextV(g, fmt, args);
  9596. va_end(args);
  9597. }
  9598. void ImGui::LogTextV(const char* fmt, va_list args)
  9599. {
  9600. ImGuiContext& g = *GImGui;
  9601. if (!g.LogEnabled)
  9602. return;
  9603. LogTextV(g, fmt, args);
  9604. }
  9605. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  9606. // We split text into individual lines to add current tree level padding
  9607. // FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
  9608. void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
  9609. {
  9610. ImGuiContext& g = *GImGui;
  9611. ImGuiWindow* window = g.CurrentWindow;
  9612. const char* prefix = g.LogNextPrefix;
  9613. const char* suffix = g.LogNextSuffix;
  9614. g.LogNextPrefix = g.LogNextSuffix = NULL;
  9615. if (!text_end)
  9616. text_end = FindRenderedTextEnd(text, text_end);
  9617. const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
  9618. if (ref_pos)
  9619. g.LogLinePosY = ref_pos->y;
  9620. if (log_new_line)
  9621. {
  9622. LogText(IM_NEWLINE);
  9623. g.LogLineFirstItem = true;
  9624. }
  9625. if (prefix)
  9626. LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
  9627. // Re-adjust padding if we have popped out of our starting depth
  9628. if (g.LogDepthRef > window->DC.TreeDepth)
  9629. g.LogDepthRef = window->DC.TreeDepth;
  9630. const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
  9631. const char* text_remaining = text;
  9632. for (;;)
  9633. {
  9634. // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
  9635. // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
  9636. const char* line_start = text_remaining;
  9637. const char* line_end = ImStreolRange(line_start, text_end);
  9638. const bool is_last_line = (line_end == text_end);
  9639. if (line_start != line_end || !is_last_line)
  9640. {
  9641. const int line_length = (int)(line_end - line_start);
  9642. const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
  9643. LogText("%*s%.*s", indentation, "", line_length, line_start);
  9644. g.LogLineFirstItem = false;
  9645. if (*line_end == '\n')
  9646. {
  9647. LogText(IM_NEWLINE);
  9648. g.LogLineFirstItem = true;
  9649. }
  9650. }
  9651. if (is_last_line)
  9652. break;
  9653. text_remaining = line_end + 1;
  9654. }
  9655. if (suffix)
  9656. LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
  9657. }
  9658. // Start logging/capturing text output
  9659. void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
  9660. {
  9661. ImGuiContext& g = *GImGui;
  9662. ImGuiWindow* window = g.CurrentWindow;
  9663. IM_ASSERT(g.LogEnabled == false);
  9664. IM_ASSERT(g.LogFile == NULL);
  9665. IM_ASSERT(g.LogBuffer.empty());
  9666. g.LogEnabled = true;
  9667. g.LogType = type;
  9668. g.LogNextPrefix = g.LogNextSuffix = NULL;
  9669. g.LogDepthRef = window->DC.TreeDepth;
  9670. g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
  9671. g.LogLinePosY = FLT_MAX;
  9672. g.LogLineFirstItem = true;
  9673. }
  9674. // Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
  9675. void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
  9676. {
  9677. ImGuiContext& g = *GImGui;
  9678. g.LogNextPrefix = prefix;
  9679. g.LogNextSuffix = suffix;
  9680. }
  9681. void ImGui::LogToTTY(int auto_open_depth)
  9682. {
  9683. ImGuiContext& g = *GImGui;
  9684. if (g.LogEnabled)
  9685. return;
  9686. IM_UNUSED(auto_open_depth);
  9687. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9688. LogBegin(ImGuiLogType_TTY, auto_open_depth);
  9689. g.LogFile = stdout;
  9690. #endif
  9691. }
  9692. // Start logging/capturing text output to given file
  9693. void ImGui::LogToFile(int auto_open_depth, const char* filename)
  9694. {
  9695. ImGuiContext& g = *GImGui;
  9696. if (g.LogEnabled)
  9697. return;
  9698. // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
  9699. // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
  9700. // By opening the file in binary mode "ab" we have consistent output everywhere.
  9701. if (!filename)
  9702. filename = g.IO.LogFilename;
  9703. if (!filename || !filename[0])
  9704. return;
  9705. ImFileHandle f = ImFileOpen(filename, "ab");
  9706. if (!f)
  9707. {
  9708. IM_ASSERT(0);
  9709. return;
  9710. }
  9711. LogBegin(ImGuiLogType_File, auto_open_depth);
  9712. g.LogFile = f;
  9713. }
  9714. // Start logging/capturing text output to clipboard
  9715. void ImGui::LogToClipboard(int auto_open_depth)
  9716. {
  9717. ImGuiContext& g = *GImGui;
  9718. if (g.LogEnabled)
  9719. return;
  9720. LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
  9721. }
  9722. void ImGui::LogToBuffer(int auto_open_depth)
  9723. {
  9724. ImGuiContext& g = *GImGui;
  9725. if (g.LogEnabled)
  9726. return;
  9727. LogBegin(ImGuiLogType_Buffer, auto_open_depth);
  9728. }
  9729. void ImGui::LogFinish()
  9730. {
  9731. ImGuiContext& g = *GImGui;
  9732. if (!g.LogEnabled)
  9733. return;
  9734. LogText(IM_NEWLINE);
  9735. switch (g.LogType)
  9736. {
  9737. case ImGuiLogType_TTY:
  9738. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9739. fflush(g.LogFile);
  9740. #endif
  9741. break;
  9742. case ImGuiLogType_File:
  9743. ImFileClose(g.LogFile);
  9744. break;
  9745. case ImGuiLogType_Buffer:
  9746. break;
  9747. case ImGuiLogType_Clipboard:
  9748. if (!g.LogBuffer.empty())
  9749. SetClipboardText(g.LogBuffer.begin());
  9750. break;
  9751. case ImGuiLogType_None:
  9752. IM_ASSERT(0);
  9753. break;
  9754. }
  9755. g.LogEnabled = false;
  9756. g.LogType = ImGuiLogType_None;
  9757. g.LogFile = NULL;
  9758. g.LogBuffer.clear();
  9759. }
  9760. // Helper to display logging buttons
  9761. // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
  9762. void ImGui::LogButtons()
  9763. {
  9764. ImGuiContext& g = *GImGui;
  9765. PushID("LogButtons");
  9766. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9767. const bool log_to_tty = Button("Log To TTY"); SameLine();
  9768. #else
  9769. const bool log_to_tty = false;
  9770. #endif
  9771. const bool log_to_file = Button("Log To File"); SameLine();
  9772. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  9773. PushAllowKeyboardFocus(false);
  9774. SetNextItemWidth(80.0f);
  9775. SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
  9776. PopAllowKeyboardFocus();
  9777. PopID();
  9778. // Start logging at the end of the function so that the buttons don't appear in the log
  9779. if (log_to_tty)
  9780. LogToTTY();
  9781. if (log_to_file)
  9782. LogToFile();
  9783. if (log_to_clipboard)
  9784. LogToClipboard();
  9785. }
  9786. //-----------------------------------------------------------------------------
  9787. // [SECTION] SETTINGS
  9788. //-----------------------------------------------------------------------------
  9789. // - UpdateSettings() [Internal]
  9790. // - MarkIniSettingsDirty() [Internal]
  9791. // - CreateNewWindowSettings() [Internal]
  9792. // - FindWindowSettings() [Internal]
  9793. // - FindOrCreateWindowSettings() [Internal]
  9794. // - FindSettingsHandler() [Internal]
  9795. // - ClearIniSettings() [Internal]
  9796. // - LoadIniSettingsFromDisk()
  9797. // - LoadIniSettingsFromMemory()
  9798. // - SaveIniSettingsToDisk()
  9799. // - SaveIniSettingsToMemory()
  9800. // - WindowSettingsHandler_***() [Internal]
  9801. //-----------------------------------------------------------------------------
  9802. // Called by NewFrame()
  9803. void ImGui::UpdateSettings()
  9804. {
  9805. // Load settings on first frame (if not explicitly loaded manually before)
  9806. ImGuiContext& g = *GImGui;
  9807. if (!g.SettingsLoaded)
  9808. {
  9809. IM_ASSERT(g.SettingsWindows.empty());
  9810. if (g.IO.IniFilename)
  9811. LoadIniSettingsFromDisk(g.IO.IniFilename);
  9812. g.SettingsLoaded = true;
  9813. }
  9814. // Save settings (with a delay after the last modification, so we don't spam disk too much)
  9815. if (g.SettingsDirtyTimer > 0.0f)
  9816. {
  9817. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  9818. if (g.SettingsDirtyTimer <= 0.0f)
  9819. {
  9820. if (g.IO.IniFilename != NULL)
  9821. SaveIniSettingsToDisk(g.IO.IniFilename);
  9822. else
  9823. g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
  9824. g.SettingsDirtyTimer = 0.0f;
  9825. }
  9826. }
  9827. }
  9828. void ImGui::MarkIniSettingsDirty()
  9829. {
  9830. ImGuiContext& g = *GImGui;
  9831. if (g.SettingsDirtyTimer <= 0.0f)
  9832. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  9833. }
  9834. void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
  9835. {
  9836. ImGuiContext& g = *GImGui;
  9837. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  9838. if (g.SettingsDirtyTimer <= 0.0f)
  9839. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  9840. }
  9841. ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
  9842. {
  9843. ImGuiContext& g = *GImGui;
  9844. #if !IMGUI_DEBUG_INI_SETTINGS
  9845. // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  9846. // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
  9847. if (const char* p = strstr(name, "###"))
  9848. name = p;
  9849. #endif
  9850. const size_t name_len = strlen(name);
  9851. // Allocate chunk
  9852. const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
  9853. ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
  9854. IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
  9855. settings->ID = ImHashStr(name, name_len);
  9856. memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
  9857. return settings;
  9858. }
  9859. ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
  9860. {
  9861. ImGuiContext& g = *GImGui;
  9862. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  9863. if (settings->ID == id)
  9864. return settings;
  9865. return NULL;
  9866. }
  9867. ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
  9868. {
  9869. if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
  9870. return settings;
  9871. return CreateNewWindowSettings(name);
  9872. }
  9873. ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
  9874. {
  9875. ImGuiContext& g = *GImGui;
  9876. const ImGuiID type_hash = ImHashStr(type_name);
  9877. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  9878. if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
  9879. return &g.SettingsHandlers[handler_n];
  9880. return NULL;
  9881. }
  9882. void ImGui::ClearIniSettings()
  9883. {
  9884. ImGuiContext& g = *GImGui;
  9885. g.SettingsIniData.clear();
  9886. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  9887. if (g.SettingsHandlers[handler_n].ClearAllFn)
  9888. g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
  9889. }
  9890. void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
  9891. {
  9892. size_t file_data_size = 0;
  9893. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
  9894. if (!file_data)
  9895. return;
  9896. LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
  9897. IM_FREE(file_data);
  9898. }
  9899. // Zero-tolerance, no error reporting, cheap .ini parsing
  9900. void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
  9901. {
  9902. ImGuiContext& g = *GImGui;
  9903. IM_ASSERT(g.Initialized);
  9904. //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
  9905. //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
  9906. // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
  9907. // 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..
  9908. if (ini_size == 0)
  9909. ini_size = strlen(ini_data);
  9910. g.SettingsIniData.Buf.resize((int)ini_size + 1);
  9911. char* const buf = g.SettingsIniData.Buf.Data;
  9912. char* const buf_end = buf + ini_size;
  9913. memcpy(buf, ini_data, ini_size);
  9914. buf_end[0] = 0;
  9915. // Call pre-read handlers
  9916. // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
  9917. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  9918. if (g.SettingsHandlers[handler_n].ReadInitFn)
  9919. g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
  9920. void* entry_data = NULL;
  9921. ImGuiSettingsHandler* entry_handler = NULL;
  9922. char* line_end = NULL;
  9923. for (char* line = buf; line < buf_end; line = line_end + 1)
  9924. {
  9925. // Skip new lines markers, then find end of the line
  9926. while (*line == '\n' || *line == '\r')
  9927. line++;
  9928. line_end = line;
  9929. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  9930. line_end++;
  9931. line_end[0] = 0;
  9932. if (line[0] == ';')
  9933. continue;
  9934. if (line[0] == '[' && line_end > line && line_end[-1] == ']')
  9935. {
  9936. // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
  9937. line_end[-1] = 0;
  9938. const char* name_end = line_end - 1;
  9939. const char* type_start = line + 1;
  9940. char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
  9941. const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
  9942. if (!type_end || !name_start)
  9943. continue;
  9944. *type_end = 0; // Overwrite first ']'
  9945. name_start++; // Skip second '['
  9946. entry_handler = FindSettingsHandler(type_start);
  9947. entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
  9948. }
  9949. else if (entry_handler != NULL && entry_data != NULL)
  9950. {
  9951. // Let type handler parse the line
  9952. entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
  9953. }
  9954. }
  9955. g.SettingsLoaded = true;
  9956. // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
  9957. memcpy(buf, ini_data, ini_size);
  9958. // Call post-read handlers
  9959. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  9960. if (g.SettingsHandlers[handler_n].ApplyAllFn)
  9961. g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
  9962. }
  9963. void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
  9964. {
  9965. ImGuiContext& g = *GImGui;
  9966. g.SettingsDirtyTimer = 0.0f;
  9967. if (!ini_filename)
  9968. return;
  9969. size_t ini_data_size = 0;
  9970. const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
  9971. ImFileHandle f = ImFileOpen(ini_filename, "wt");
  9972. if (!f)
  9973. return;
  9974. ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
  9975. ImFileClose(f);
  9976. }
  9977. // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
  9978. const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
  9979. {
  9980. ImGuiContext& g = *GImGui;
  9981. g.SettingsDirtyTimer = 0.0f;
  9982. g.SettingsIniData.Buf.resize(0);
  9983. g.SettingsIniData.Buf.push_back(0);
  9984. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  9985. {
  9986. ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
  9987. handler->WriteAllFn(&g, handler, &g.SettingsIniData);
  9988. }
  9989. if (out_size)
  9990. *out_size = (size_t)g.SettingsIniData.size();
  9991. return g.SettingsIniData.c_str();
  9992. }
  9993. static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  9994. {
  9995. ImGuiContext& g = *ctx;
  9996. for (int i = 0; i != g.Windows.Size; i++)
  9997. g.Windows[i]->SettingsOffset = -1;
  9998. g.SettingsWindows.clear();
  9999. }
  10000. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  10001. {
  10002. ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
  10003. ImGuiID id = settings->ID;
  10004. *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
  10005. settings->ID = id;
  10006. settings->WantApply = true;
  10007. return (void*)settings;
  10008. }
  10009. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  10010. {
  10011. ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
  10012. int x, y;
  10013. int i;
  10014. ImU32 u1;
  10015. if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
  10016. else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
  10017. else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
  10018. else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
  10019. else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
  10020. else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
  10021. else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
  10022. else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
  10023. }
  10024. // Apply to existing windows (if any)
  10025. static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  10026. {
  10027. ImGuiContext& g = *ctx;
  10028. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10029. if (settings->WantApply)
  10030. {
  10031. if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
  10032. ApplyWindowSettings(window, settings);
  10033. settings->WantApply = false;
  10034. }
  10035. }
  10036. static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  10037. {
  10038. // Gather data from windows that were active during this session
  10039. // (if a window wasn't opened in this session we preserve its settings)
  10040. ImGuiContext& g = *ctx;
  10041. for (int i = 0; i != g.Windows.Size; i++)
  10042. {
  10043. ImGuiWindow* window = g.Windows[i];
  10044. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  10045. continue;
  10046. ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
  10047. if (!settings)
  10048. {
  10049. settings = ImGui::CreateNewWindowSettings(window->Name);
  10050. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  10051. }
  10052. IM_ASSERT(settings->ID == window->ID);
  10053. settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
  10054. settings->Size = ImVec2ih(window->SizeFull);
  10055. settings->ViewportId = window->ViewportId;
  10056. settings->ViewportPos = ImVec2ih(window->ViewportPos);
  10057. IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
  10058. settings->DockId = window->DockId;
  10059. settings->ClassId = window->WindowClass.ClassId;
  10060. settings->DockOrder = window->DockOrder;
  10061. settings->Collapsed = window->Collapsed;
  10062. }
  10063. // Write to text buffer
  10064. buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
  10065. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10066. {
  10067. const char* settings_name = settings->GetName();
  10068. buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
  10069. if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
  10070. {
  10071. buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
  10072. buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
  10073. }
  10074. if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
  10075. buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
  10076. if (settings->Size.x != 0 || settings->Size.y != 0)
  10077. buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
  10078. buf->appendf("Collapsed=%d\n", settings->Collapsed);
  10079. if (settings->DockId != 0)
  10080. {
  10081. if (settings->DockOrder == -1)
  10082. buf->appendf("DockId=0x%08X\n", settings->DockId);
  10083. else
  10084. buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
  10085. if (settings->ClassId != 0)
  10086. buf->appendf("ClassId=0x%08X\n", settings->ClassId);
  10087. }
  10088. buf->append("\n");
  10089. }
  10090. }
  10091. //-----------------------------------------------------------------------------
  10092. // [SECTION] VIEWPORTS, PLATFORM WINDOWS
  10093. //-----------------------------------------------------------------------------
  10094. // - GetMainViewport()
  10095. // - FindViewportByID()
  10096. // - FindViewportByPlatformHandle()
  10097. // - SetCurrentViewport() [Internal]
  10098. // - SetWindowViewport() [Internal]
  10099. // - GetWindowAlwaysWantOwnViewport() [Internal]
  10100. // - UpdateTryMergeWindowIntoHostViewport() [Internal]
  10101. // - UpdateTryMergeWindowIntoHostViewports() [Internal]
  10102. // - TranslateWindowsInViewport() [Internal]
  10103. // - ScaleWindowsInViewport() [Internal]
  10104. // - FindHoveredViewportFromPlatformWindowStack() [Internal]
  10105. // - UpdateViewportsNewFrame() [Internal]
  10106. // - UpdateViewportsEndFrame() [Internal]
  10107. // - AddUpdateViewport() [Internal]
  10108. // - UpdateSelectWindowViewport() [Internal]
  10109. // - UpdatePlatformWindows()
  10110. // - RenderPlatformWindowsDefault()
  10111. // - FindPlatformMonitorForPos() [Internal]
  10112. // - FindPlatformMonitorForRect() [Internal]
  10113. // - UpdateViewportPlatformMonitor() [Internal]
  10114. // - DestroyPlatformWindow() [Internal]
  10115. // - DestroyPlatformWindows()
  10116. //-----------------------------------------------------------------------------
  10117. ImGuiViewport* ImGui::GetMainViewport()
  10118. {
  10119. ImGuiContext& g = *GImGui;
  10120. return g.Viewports[0];
  10121. }
  10122. ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
  10123. {
  10124. ImGuiContext& g = *GImGui;
  10125. for (int n = 0; n < g.Viewports.Size; n++)
  10126. if (g.Viewports[n]->ID == id)
  10127. return g.Viewports[n];
  10128. return NULL;
  10129. }
  10130. ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
  10131. {
  10132. ImGuiContext& g = *GImGui;
  10133. for (int i = 0; i != g.Viewports.Size; i++)
  10134. if (g.Viewports[i]->PlatformHandle == platform_handle)
  10135. return g.Viewports[i];
  10136. return NULL;
  10137. }
  10138. void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
  10139. {
  10140. ImGuiContext& g = *GImGui;
  10141. (void)current_window;
  10142. if (viewport)
  10143. viewport->LastFrameActive = g.FrameCount;
  10144. if (g.CurrentViewport == viewport)
  10145. return;
  10146. g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
  10147. g.CurrentViewport = viewport;
  10148. //IMGUI_DEBUG_LOG_VIEWPORT("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
  10149. // Notify platform layer of viewport changes
  10150. // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
  10151. if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
  10152. g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
  10153. }
  10154. static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
  10155. {
  10156. window->Viewport = viewport;
  10157. window->ViewportId = viewport->ID;
  10158. window->ViewportOwned = (viewport->Window == window);
  10159. }
  10160. static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
  10161. {
  10162. // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
  10163. ImGuiContext& g = *GImGui;
  10164. if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
  10165. if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
  10166. if (!window->DockIsActive)
  10167. if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
  10168. if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
  10169. return true;
  10170. return false;
  10171. }
  10172. static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
  10173. {
  10174. ImGuiContext& g = *GImGui;
  10175. if (window->Viewport == viewport)
  10176. return false;
  10177. if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
  10178. return false;
  10179. if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0)
  10180. return false;
  10181. if (!viewport->GetMainRect().Contains(window->Rect()))
  10182. return false;
  10183. if (GetWindowAlwaysWantOwnViewport(window))
  10184. return false;
  10185. for (int n = 0; n < g.Windows.Size; n++)
  10186. {
  10187. ImGuiWindow* window_behind = g.Windows[n];
  10188. if (window_behind == window)
  10189. break;
  10190. if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
  10191. if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
  10192. return false;
  10193. }
  10194. // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
  10195. ImGuiViewportP* old_viewport = window->Viewport;
  10196. if (window->ViewportOwned)
  10197. for (int n = 0; n < g.Windows.Size; n++)
  10198. if (g.Windows[n]->Viewport == old_viewport)
  10199. SetWindowViewport(g.Windows[n], viewport);
  10200. SetWindowViewport(window, viewport);
  10201. BringWindowToDisplayFront(window);
  10202. return true;
  10203. }
  10204. // FIXME: handle 0 to N host viewports
  10205. static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
  10206. {
  10207. ImGuiContext& g = *GImGui;
  10208. return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
  10209. }
  10210. // Translate Dear ImGui windows when a Host Viewport has been moved
  10211. // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
  10212. void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
  10213. {
  10214. ImGuiContext& g = *GImGui;
  10215. IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
  10216. // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
  10217. // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
  10218. // 2) If it's not going to fit into the new size, keep it at same absolute position.
  10219. // One problem with this is that most Win32 applications doesn't update their render while dragging,
  10220. // and so the window will appear to teleport when releasing the mouse.
  10221. const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
  10222. ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
  10223. ImVec2 delta_pos = new_pos - old_pos;
  10224. for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
  10225. if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
  10226. TranslateWindow(g.Windows[window_n], delta_pos);
  10227. }
  10228. // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
  10229. void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
  10230. {
  10231. ImGuiContext& g = *GImGui;
  10232. if (viewport->Window)
  10233. {
  10234. ScaleWindow(viewport->Window, scale);
  10235. }
  10236. else
  10237. {
  10238. for (int i = 0; i != g.Windows.Size; i++)
  10239. if (g.Windows[i]->Viewport == viewport)
  10240. ScaleWindow(g.Windows[i], scale);
  10241. }
  10242. }
  10243. // If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
  10244. // A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
  10245. // B) It requires Platform_GetWindowFocus to be implemented by backend.
  10246. static ImGuiViewportP* FindHoveredViewportFromPlatformWindowStack(const ImVec2 mouse_platform_pos)
  10247. {
  10248. ImGuiContext& g = *GImGui;
  10249. ImGuiViewportP* best_candidate = NULL;
  10250. for (int n = 0; n < g.Viewports.Size; n++)
  10251. {
  10252. ImGuiViewportP* viewport = g.Viewports[n];
  10253. if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
  10254. if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
  10255. best_candidate = viewport;
  10256. }
  10257. return best_candidate;
  10258. }
  10259. // Update viewports and monitor infos
  10260. // Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
  10261. static void ImGui::UpdateViewportsNewFrame()
  10262. {
  10263. ImGuiContext& g = *GImGui;
  10264. IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
  10265. // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
  10266. const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
  10267. if (viewports_enabled)
  10268. {
  10269. for (int n = 0; n < g.Viewports.Size; n++)
  10270. {
  10271. ImGuiViewportP* viewport = g.Viewports[n];
  10272. const bool platform_funcs_available = viewport->PlatformWindowCreated;
  10273. if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
  10274. {
  10275. bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
  10276. if (minimized)
  10277. viewport->Flags |= ImGuiViewportFlags_Minimized;
  10278. else
  10279. viewport->Flags &= ~ImGuiViewportFlags_Minimized;
  10280. }
  10281. }
  10282. }
  10283. // Create/update main viewport with current platform position.
  10284. // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
  10285. ImGuiViewportP* main_viewport = g.Viewports[0];
  10286. IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
  10287. IM_ASSERT(main_viewport->Window == NULL);
  10288. ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
  10289. ImVec2 main_viewport_size = g.IO.DisplaySize;
  10290. if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized))
  10291. {
  10292. main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
  10293. main_viewport_size = main_viewport->Size;
  10294. }
  10295. AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
  10296. g.CurrentDpiScale = 0.0f;
  10297. g.CurrentViewport = NULL;
  10298. g.MouseViewport = NULL;
  10299. for (int n = 0; n < g.Viewports.Size; n++)
  10300. {
  10301. ImGuiViewportP* viewport = g.Viewports[n];
  10302. viewport->Idx = n;
  10303. // Erase unused viewports
  10304. if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
  10305. {
  10306. // Clear references to this viewport in windows (window->ViewportId becomes the master data)
  10307. for (int window_n = 0; window_n < g.Windows.Size; window_n++)
  10308. if (g.Windows[window_n]->Viewport == viewport)
  10309. {
  10310. g.Windows[window_n]->Viewport = NULL;
  10311. g.Windows[window_n]->ViewportOwned = false;
  10312. }
  10313. if (viewport == g.MouseLastHoveredViewport)
  10314. g.MouseLastHoveredViewport = NULL;
  10315. g.Viewports.erase(g.Viewports.Data + n);
  10316. // Destroy
  10317. IMGUI_DEBUG_LOG_VIEWPORT("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
  10318. DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
  10319. IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
  10320. IM_DELETE(viewport);
  10321. n--;
  10322. continue;
  10323. }
  10324. const bool platform_funcs_available = viewport->PlatformWindowCreated;
  10325. if (viewports_enabled)
  10326. {
  10327. // Update Position and Size (from Platform Window to ImGui) if requested.
  10328. // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
  10329. if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
  10330. {
  10331. // Viewport->WorkPos and WorkSize will be updated below
  10332. if (viewport->PlatformRequestMove)
  10333. viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
  10334. if (viewport->PlatformRequestResize)
  10335. viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
  10336. }
  10337. }
  10338. // Update/copy monitor info
  10339. UpdateViewportPlatformMonitor(viewport);
  10340. // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
  10341. viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
  10342. viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
  10343. viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
  10344. viewport->UpdateWorkRect();
  10345. // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
  10346. viewport->Alpha = 1.0f;
  10347. // Translate imgui windows when a Host Viewport has been moved
  10348. // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
  10349. const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
  10350. if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
  10351. TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
  10352. // Update DPI scale
  10353. float new_dpi_scale;
  10354. if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
  10355. new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
  10356. else if (viewport->PlatformMonitor != -1)
  10357. new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
  10358. else
  10359. new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
  10360. if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
  10361. {
  10362. float scale_factor = new_dpi_scale / viewport->DpiScale;
  10363. if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
  10364. ScaleWindowsInViewport(viewport, scale_factor);
  10365. //if (viewport == GetMainViewport())
  10366. // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
  10367. // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
  10368. // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
  10369. // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
  10370. //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
  10371. // g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
  10372. }
  10373. viewport->DpiScale = new_dpi_scale;
  10374. }
  10375. // Update fallback monitor
  10376. if (g.PlatformIO.Monitors.Size == 0)
  10377. {
  10378. ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
  10379. monitor->MainPos = main_viewport->Pos;
  10380. monitor->MainSize = main_viewport->Size;
  10381. monitor->WorkPos = main_viewport->WorkPos;
  10382. monitor->WorkSize = main_viewport->WorkSize;
  10383. monitor->DpiScale = main_viewport->DpiScale;
  10384. }
  10385. if (!viewports_enabled)
  10386. {
  10387. g.MouseViewport = main_viewport;
  10388. return;
  10389. }
  10390. // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
  10391. // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
  10392. ImGuiViewportP* viewport_hovered = NULL;
  10393. if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
  10394. {
  10395. viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
  10396. if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
  10397. {
  10398. // Backend failed at honoring its contract if it returned a viewport with the _NoInputs flag.
  10399. IM_ASSERT(0);
  10400. viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
  10401. }
  10402. }
  10403. else
  10404. {
  10405. // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
  10406. // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
  10407. // B) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
  10408. viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
  10409. }
  10410. if (viewport_hovered != NULL)
  10411. g.MouseLastHoveredViewport = viewport_hovered;
  10412. else if (g.MouseLastHoveredViewport == NULL)
  10413. g.MouseLastHoveredViewport = g.Viewports[0];
  10414. // Update mouse reference viewport
  10415. // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
  10416. if (g.MovingWindow)
  10417. g.MouseViewport = g.MovingWindow->Viewport;
  10418. else
  10419. g.MouseViewport = g.MouseLastHoveredViewport;
  10420. // When dragging something, always refer to the last hovered viewport.
  10421. // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
  10422. // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
  10423. // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
  10424. // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
  10425. const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
  10426. if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
  10427. viewport_hovered = g.MouseLastHoveredViewport;
  10428. if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
  10429. if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
  10430. g.MouseViewport = viewport_hovered;
  10431. IM_ASSERT(g.MouseViewport != NULL);
  10432. }
  10433. // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
  10434. static void ImGui::UpdateViewportsEndFrame()
  10435. {
  10436. ImGuiContext& g = *GImGui;
  10437. g.PlatformIO.Viewports.resize(0);
  10438. for (int i = 0; i < g.Viewports.Size; i++)
  10439. {
  10440. ImGuiViewportP* viewport = g.Viewports[i];
  10441. viewport->LastPos = viewport->Pos;
  10442. if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
  10443. if (i > 0) // Always include main viewport in the list
  10444. continue;
  10445. if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
  10446. continue;
  10447. if (i > 0)
  10448. IM_ASSERT(viewport->Window != NULL);
  10449. g.PlatformIO.Viewports.push_back(viewport);
  10450. }
  10451. g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
  10452. }
  10453. // FIXME: We should ideally refactor the system to call this every frame (we currently don't)
  10454. ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
  10455. {
  10456. ImGuiContext& g = *GImGui;
  10457. IM_ASSERT(id != 0);
  10458. flags |= ImGuiViewportFlags_IsPlatformWindow;
  10459. if (window != NULL)
  10460. {
  10461. if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
  10462. flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
  10463. if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
  10464. flags |= ImGuiViewportFlags_NoInputs;
  10465. if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
  10466. flags |= ImGuiViewportFlags_NoFocusOnAppearing;
  10467. }
  10468. ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
  10469. if (viewport)
  10470. {
  10471. if (!viewport->PlatformRequestMove)
  10472. viewport->Pos = pos;
  10473. if (!viewport->PlatformRequestResize)
  10474. viewport->Size = size;
  10475. viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
  10476. }
  10477. else
  10478. {
  10479. // New viewport
  10480. viewport = IM_NEW(ImGuiViewportP)();
  10481. viewport->ID = id;
  10482. viewport->Idx = g.Viewports.Size;
  10483. viewport->Pos = viewport->LastPos = pos;
  10484. viewport->Size = size;
  10485. viewport->Flags = flags;
  10486. UpdateViewportPlatformMonitor(viewport);
  10487. g.Viewports.push_back(viewport);
  10488. IMGUI_DEBUG_LOG_VIEWPORT("Add Viewport %08X (%s)\n", id, window->Name);
  10489. // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
  10490. // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
  10491. g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
  10492. g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
  10493. g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
  10494. g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
  10495. // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
  10496. // This is so we can select an appropriate font size on the first frame of our window lifetime
  10497. if (viewport->PlatformMonitor != -1)
  10498. viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
  10499. }
  10500. viewport->Window = window;
  10501. viewport->LastFrameActive = g.FrameCount;
  10502. viewport->UpdateWorkRect();
  10503. IM_ASSERT(window == NULL || viewport->ID == window->ID);
  10504. if (window != NULL)
  10505. window->ViewportOwned = true;
  10506. return viewport;
  10507. }
  10508. // FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
  10509. static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window)
  10510. {
  10511. ImGuiContext& g = *GImGui;
  10512. ImGuiWindowFlags flags = window->Flags;
  10513. window->ViewportAllowPlatformMonitorExtend = -1;
  10514. // Restore main viewport if multi-viewport is not supported by the backend
  10515. ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
  10516. if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
  10517. {
  10518. SetWindowViewport(window, main_viewport);
  10519. return;
  10520. }
  10521. window->ViewportOwned = false;
  10522. // Appearing popups reset their viewport so they can inherit again
  10523. if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
  10524. {
  10525. window->Viewport = NULL;
  10526. window->ViewportId = 0;
  10527. }
  10528. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
  10529. {
  10530. // By default inherit from parent window
  10531. if (window->Viewport == NULL && window->ParentWindow && !window->ParentWindow->IsFallbackWindow)
  10532. window->Viewport = window->ParentWindow->Viewport;
  10533. // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
  10534. if (window->Viewport == NULL && window->ViewportId != 0)
  10535. {
  10536. window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
  10537. if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
  10538. window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
  10539. }
  10540. }
  10541. bool lock_viewport = false;
  10542. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
  10543. {
  10544. // Code explicitly request a viewport
  10545. window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
  10546. window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
  10547. lock_viewport = true;
  10548. }
  10549. else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
  10550. {
  10551. // Always inherit viewport from parent window
  10552. window->Viewport = window->ParentWindow->Viewport;
  10553. }
  10554. else if (flags & ImGuiWindowFlags_Tooltip)
  10555. {
  10556. window->Viewport = g.MouseViewport;
  10557. }
  10558. else if (GetWindowAlwaysWantOwnViewport(window))
  10559. {
  10560. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
  10561. }
  10562. else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
  10563. {
  10564. if (window->Viewport != NULL && window->Viewport->Window == window)
  10565. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
  10566. }
  10567. else
  10568. {
  10569. // Merge into host viewport?
  10570. // We cannot test window->ViewportOwned as it set lower in the function.
  10571. bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0);
  10572. if (try_to_merge_into_host_viewport)
  10573. UpdateTryMergeWindowIntoHostViewports(window);
  10574. }
  10575. // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
  10576. if (window->Viewport == NULL)
  10577. if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
  10578. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
  10579. // Mark window as allowed to protrude outside of its viewport and into the current monitor
  10580. if (!lock_viewport)
  10581. {
  10582. if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  10583. {
  10584. // We need to take account of the possibility that mouse may become invalid.
  10585. // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
  10586. ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
  10587. bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
  10588. bool mouse_valid = IsMousePosValid(&mouse_ref);
  10589. if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
  10590. window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
  10591. else
  10592. window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
  10593. }
  10594. else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow))
  10595. {
  10596. // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
  10597. const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
  10598. if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
  10599. {
  10600. // Steal/transfer ownership
  10601. IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
  10602. window->Viewport->Window = window;
  10603. window->Viewport->ID = window->ID;
  10604. window->Viewport->LastNameHash = 0;
  10605. }
  10606. else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
  10607. {
  10608. // New viewport
  10609. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
  10610. }
  10611. }
  10612. else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
  10613. {
  10614. // Regular (non-child, non-popup) windows by default are also allowed to protrude
  10615. // Child windows are kept contained within their parent.
  10616. window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
  10617. }
  10618. }
  10619. // Update flags
  10620. window->ViewportOwned = (window == window->Viewport->Window);
  10621. window->ViewportId = window->Viewport->ID;
  10622. // If the OS window has a title bar, hide our imgui title bar
  10623. //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
  10624. // window->Flags |= ImGuiWindowFlags_NoTitleBar;
  10625. }
  10626. // Called by user at the end of the main loop, after EndFrame()
  10627. // This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
  10628. void ImGui::UpdatePlatformWindows()
  10629. {
  10630. ImGuiContext& g = *GImGui;
  10631. IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
  10632. IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
  10633. g.FrameCountPlatformEnded = g.FrameCount;
  10634. if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
  10635. return;
  10636. // Create/resize/destroy platform windows to match each active viewport.
  10637. // Skip the main viewport (index 0), which is always fully handled by the application!
  10638. for (int i = 1; i < g.Viewports.Size; i++)
  10639. {
  10640. ImGuiViewportP* viewport = g.Viewports[i];
  10641. // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
  10642. // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
  10643. bool destroy_platform_window = false;
  10644. destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
  10645. destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
  10646. if (destroy_platform_window)
  10647. {
  10648. DestroyPlatformWindow(viewport);
  10649. continue;
  10650. }
  10651. // New windows that appears directly in a new viewport won't always have a size on their first frame
  10652. if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
  10653. continue;
  10654. // Create window
  10655. bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
  10656. if (is_new_platform_window)
  10657. {
  10658. IMGUI_DEBUG_LOG_VIEWPORT("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
  10659. g.PlatformIO.Platform_CreateWindow(viewport);
  10660. if (g.PlatformIO.Renderer_CreateWindow != NULL)
  10661. g.PlatformIO.Renderer_CreateWindow(viewport);
  10662. viewport->LastNameHash = 0;
  10663. viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
  10664. viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
  10665. viewport->PlatformWindowCreated = true;
  10666. }
  10667. // Apply Position and Size (from ImGui to Platform/Renderer backends)
  10668. if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
  10669. g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
  10670. if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
  10671. g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
  10672. if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
  10673. g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
  10674. viewport->LastPlatformPos = viewport->Pos;
  10675. viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
  10676. // Update title bar (if it changed)
  10677. if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
  10678. {
  10679. const char* title_begin = window_for_title->Name;
  10680. char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
  10681. const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
  10682. if (viewport->LastNameHash != title_hash)
  10683. {
  10684. char title_end_backup_c = *title_end;
  10685. *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
  10686. g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
  10687. *title_end = title_end_backup_c;
  10688. viewport->LastNameHash = title_hash;
  10689. }
  10690. }
  10691. // Update alpha (if it changed)
  10692. if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
  10693. g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
  10694. viewport->LastAlpha = viewport->Alpha;
  10695. // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
  10696. if (g.PlatformIO.Platform_UpdateWindow)
  10697. g.PlatformIO.Platform_UpdateWindow(viewport);
  10698. if (is_new_platform_window)
  10699. {
  10700. // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
  10701. if (g.FrameCount < 3)
  10702. viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
  10703. // Show window
  10704. g.PlatformIO.Platform_ShowWindow(viewport);
  10705. // Even without focus, we assume the window becomes front-most.
  10706. // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
  10707. if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
  10708. viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
  10709. }
  10710. // Clear request flags
  10711. viewport->ClearRequestFlags();
  10712. }
  10713. // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
  10714. // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
  10715. // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab.
  10716. if (g.PlatformIO.Platform_GetWindowFocus != NULL)
  10717. {
  10718. ImGuiViewportP* focused_viewport = NULL;
  10719. for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
  10720. {
  10721. ImGuiViewportP* viewport = g.Viewports[n];
  10722. if (viewport->PlatformWindowCreated)
  10723. if (g.PlatformIO.Platform_GetWindowFocus(viewport))
  10724. focused_viewport = viewport;
  10725. }
  10726. // Store a tag so we can infer z-order easily from all our windows
  10727. // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
  10728. // will keep the front most stamp instead of losing it back to their parent viewport.
  10729. if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
  10730. {
  10731. if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
  10732. focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
  10733. g.PlatformLastFocusedViewportId = focused_viewport->ID;
  10734. }
  10735. }
  10736. }
  10737. // This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
  10738. // Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
  10739. // The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
  10740. //
  10741. // ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  10742. // for (int i = 1; i < platform_io.Viewports.Size; i++)
  10743. // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
  10744. // MyRenderFunction(platform_io.Viewports[i], my_args);
  10745. // for (int i = 1; i < platform_io.Viewports.Size; i++)
  10746. // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
  10747. // MySwapBufferFunction(platform_io.Viewports[i], my_args);
  10748. //
  10749. void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
  10750. {
  10751. // Skip the main viewport (index 0), which is always fully handled by the application!
  10752. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  10753. for (int i = 1; i < platform_io.Viewports.Size; i++)
  10754. {
  10755. ImGuiViewport* viewport = platform_io.Viewports[i];
  10756. if (viewport->Flags & ImGuiViewportFlags_Minimized)
  10757. continue;
  10758. if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
  10759. if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
  10760. }
  10761. for (int i = 1; i < platform_io.Viewports.Size; i++)
  10762. {
  10763. ImGuiViewport* viewport = platform_io.Viewports[i];
  10764. if (viewport->Flags & ImGuiViewportFlags_Minimized)
  10765. continue;
  10766. if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
  10767. if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
  10768. }
  10769. }
  10770. static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
  10771. {
  10772. ImGuiContext& g = *GImGui;
  10773. for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
  10774. {
  10775. const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
  10776. if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
  10777. return monitor_n;
  10778. }
  10779. return -1;
  10780. }
  10781. // Search for the monitor with the largest intersection area with the given rectangle
  10782. // We generally try to avoid searching loops but the monitor count should be very small here
  10783. // FIXME-OPT: We could test the last monitor used for that viewport first, and early
  10784. static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
  10785. {
  10786. ImGuiContext& g = *GImGui;
  10787. const int monitor_count = g.PlatformIO.Monitors.Size;
  10788. if (monitor_count <= 1)
  10789. return monitor_count - 1;
  10790. // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
  10791. // This is necessary for tooltips which always resize down to zero at first.
  10792. const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
  10793. int best_monitor_n = -1;
  10794. float best_monitor_surface = 0.001f;
  10795. for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
  10796. {
  10797. const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
  10798. const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
  10799. if (monitor_rect.Contains(rect))
  10800. return monitor_n;
  10801. ImRect overlapping_rect = rect;
  10802. overlapping_rect.ClipWithFull(monitor_rect);
  10803. float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
  10804. if (overlapping_surface < best_monitor_surface)
  10805. continue;
  10806. best_monitor_surface = overlapping_surface;
  10807. best_monitor_n = monitor_n;
  10808. }
  10809. return best_monitor_n;
  10810. }
  10811. // Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
  10812. static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
  10813. {
  10814. viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
  10815. }
  10816. // Return value is always != NULL, but don't hold on it across frames.
  10817. const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
  10818. {
  10819. ImGuiContext& g = *GImGui;
  10820. ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
  10821. int monitor_idx = viewport->PlatformMonitor;
  10822. if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
  10823. return &g.PlatformIO.Monitors[monitor_idx];
  10824. return &g.FallbackMonitor;
  10825. }
  10826. void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
  10827. {
  10828. ImGuiContext& g = *GImGui;
  10829. if (viewport->PlatformWindowCreated)
  10830. {
  10831. if (g.PlatformIO.Renderer_DestroyWindow)
  10832. g.PlatformIO.Renderer_DestroyWindow(viewport);
  10833. if (g.PlatformIO.Platform_DestroyWindow)
  10834. g.PlatformIO.Platform_DestroyWindow(viewport);
  10835. IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
  10836. // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
  10837. // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
  10838. if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
  10839. viewport->PlatformWindowCreated = false;
  10840. }
  10841. else
  10842. {
  10843. IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
  10844. }
  10845. viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
  10846. viewport->ClearRequestFlags();
  10847. }
  10848. void ImGui::DestroyPlatformWindows()
  10849. {
  10850. // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
  10851. // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
  10852. // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
  10853. // code to operator a consistent manner.
  10854. // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
  10855. // crashing if it doesn't have data stored.
  10856. ImGuiContext& g = *GImGui;
  10857. for (int i = 0; i < g.Viewports.Size; i++)
  10858. DestroyPlatformWindow(g.Viewports[i]);
  10859. }
  10860. //-----------------------------------------------------------------------------
  10861. // [SECTION] DOCKING
  10862. //-----------------------------------------------------------------------------
  10863. // Docking: Internal Types
  10864. // Docking: Forward Declarations
  10865. // Docking: ImGuiDockContext
  10866. // Docking: ImGuiDockContext Docking/Undocking functions
  10867. // Docking: ImGuiDockNode
  10868. // Docking: ImGuiDockNode Tree manipulation functions
  10869. // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
  10870. // Docking: Builder Functions
  10871. // Docking: Begin/End Support Functions (called from Begin/End)
  10872. // Docking: Settings
  10873. //-----------------------------------------------------------------------------
  10874. //-----------------------------------------------------------------------------
  10875. // Typical Docking call flow: (root level is generally public API):
  10876. //-----------------------------------------------------------------------------
  10877. // - NewFrame() new dear imgui frame
  10878. // | DockContextNewFrameUpdateUndocking() - process queued undocking requests
  10879. // | - DockContextProcessUndockWindow() - process one window undocking request
  10880. // | - DockContextProcessUndockNode() - process one whole node undocking request
  10881. // | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes
  10882. // | - update g.HoveredDockNode - [debug] update node hovered by mouse
  10883. // | - DockContextProcessDock() - process one docking request
  10884. // | - DockNodeUpdate()
  10885. // | - DockNodeUpdateForRootNode()
  10886. // | - DockNodeUpdateVisibleFlagAndInactiveChilds()
  10887. // | - DockNodeFindInfo()
  10888. // | - destroy unused node or tab bar
  10889. // | - create dock node host window
  10890. // | - Begin() etc.
  10891. // | - DockNodeStartMouseMovingWindow()
  10892. // | - DockNodeTreeUpdatePosSize()
  10893. // | - DockNodeTreeUpdateSplitter()
  10894. // | - draw node background
  10895. // | - DockNodeUpdateTabBar() - create/update tab bar for a docking node
  10896. // | - DockNodeAddTabBar()
  10897. // | - DockNodeUpdateWindowMenu()
  10898. // | - DockNodeCalcTabBarLayout()
  10899. // | - BeginTabBarEx()
  10900. // | - TabItemEx() calls
  10901. // | - EndTabBar()
  10902. // | - BeginDockableDragDropTarget()
  10903. // | - DockNodeUpdate() - recurse into child nodes...
  10904. //-----------------------------------------------------------------------------
  10905. // - DockSpace() user submit a dockspace into a window
  10906. // | Begin(Child) - create a child window
  10907. // | DockNodeUpdate() - call main dock node update function
  10908. // | End(Child)
  10909. // | ItemSize()
  10910. //-----------------------------------------------------------------------------
  10911. // - Begin()
  10912. // | BeginDocked()
  10913. // | BeginDockableDragDropSource()
  10914. // | BeginDockableDragDropTarget()
  10915. // | - DockNodePreviewDockRender()
  10916. //-----------------------------------------------------------------------------
  10917. //-----------------------------------------------------------------------------
  10918. // Docking: Internal Types
  10919. //-----------------------------------------------------------------------------
  10920. // - ImGuiDockRequestType
  10921. // - ImGuiDockRequest
  10922. // - ImGuiDockPreviewData
  10923. // - ImGuiDockNodeSettings
  10924. // - ImGuiDockContext
  10925. //-----------------------------------------------------------------------------
  10926. enum ImGuiDockRequestType
  10927. {
  10928. ImGuiDockRequestType_None = 0,
  10929. ImGuiDockRequestType_Dock,
  10930. ImGuiDockRequestType_Undock,
  10931. ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
  10932. };
  10933. struct ImGuiDockRequest
  10934. {
  10935. ImGuiDockRequestType Type;
  10936. ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
  10937. ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
  10938. ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
  10939. ImGuiDir DockSplitDir;
  10940. float DockSplitRatio;
  10941. bool DockSplitOuter;
  10942. ImGuiWindow* UndockTargetWindow;
  10943. ImGuiDockNode* UndockTargetNode;
  10944. ImGuiDockRequest()
  10945. {
  10946. Type = ImGuiDockRequestType_None;
  10947. DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
  10948. DockTargetNode = UndockTargetNode = NULL;
  10949. DockSplitDir = ImGuiDir_None;
  10950. DockSplitRatio = 0.5f;
  10951. DockSplitOuter = false;
  10952. }
  10953. };
  10954. struct ImGuiDockPreviewData
  10955. {
  10956. ImGuiDockNode FutureNode;
  10957. bool IsDropAllowed;
  10958. bool IsCenterAvailable;
  10959. bool IsSidesAvailable; // Hold your breath, grammar freaks..
  10960. bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
  10961. ImGuiDockNode* SplitNode;
  10962. ImGuiDir SplitDir;
  10963. float SplitRatio;
  10964. ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
  10965. ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
  10966. };
  10967. // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
  10968. struct ImGuiDockNodeSettings
  10969. {
  10970. ImGuiID ID;
  10971. ImGuiID ParentNodeId;
  10972. ImGuiID ParentWindowId;
  10973. ImGuiID SelectedTabId;
  10974. signed char SplitAxis;
  10975. char Depth;
  10976. ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
  10977. ImVec2ih Pos;
  10978. ImVec2ih Size;
  10979. ImVec2ih SizeRef;
  10980. ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
  10981. };
  10982. //-----------------------------------------------------------------------------
  10983. // Docking: Forward Declarations
  10984. //-----------------------------------------------------------------------------
  10985. namespace ImGui
  10986. {
  10987. // ImGuiDockContext
  10988. static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
  10989. static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
  10990. static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
  10991. static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
  10992. static void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true);
  10993. static void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
  10994. static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
  10995. static ImGuiDockNode* DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id);
  10996. static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
  10997. static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
  10998. static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
  10999. // ImGuiDockNode
  11000. static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
  11001. static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
  11002. static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
  11003. static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
  11004. static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
  11005. static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
  11006. static void DockNodeHideHostWindow(ImGuiDockNode* node);
  11007. static void DockNodeUpdate(ImGuiDockNode* node);
  11008. static void DockNodeUpdateForRootNode(ImGuiDockNode* node);
  11009. static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node);
  11010. static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
  11011. static void DockNodeAddTabBar(ImGuiDockNode* node);
  11012. static void DockNodeRemoveTabBar(ImGuiDockNode* node);
  11013. static ImGuiID DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
  11014. static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
  11015. static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
  11016. static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
  11017. static void DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
  11018. static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
  11019. static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
  11020. static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
  11021. static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
  11022. static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
  11023. static int DockNodeGetTabOrder(ImGuiWindow* window);
  11024. // ImGuiDockNode tree manipulations
  11025. static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
  11026. static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
  11027. static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes = false);
  11028. static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
  11029. static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
  11030. static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
  11031. // Settings
  11032. static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
  11033. static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
  11034. static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
  11035. static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
  11036. static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
  11037. static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
  11038. static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
  11039. static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
  11040. }
  11041. //-----------------------------------------------------------------------------
  11042. // Docking: ImGuiDockContext
  11043. //-----------------------------------------------------------------------------
  11044. // The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
  11045. // or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
  11046. // At boot time only, we run a simple GC to remove nodes that have no references.
  11047. // Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
  11048. // we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
  11049. // This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
  11050. //-----------------------------------------------------------------------------
  11051. // - DockContextInitialize()
  11052. // - DockContextShutdown()
  11053. // - DockContextClearNodes()
  11054. // - DockContextRebuildNodes()
  11055. // - DockContextNewFrameUpdateUndocking()
  11056. // - DockContextNewFrameUpdateDocking()
  11057. // - DockContextFindNodeByID()
  11058. // - DockContextBindNodeToWindow()
  11059. // - DockContextGenNodeID()
  11060. // - DockContextAddNode()
  11061. // - DockContextRemoveNode()
  11062. // - ImGuiDockContextPruneNodeData
  11063. // - DockContextPruneUnusedSettingsNodes()
  11064. // - DockContextBuildNodesFromSettings()
  11065. // - DockContextBuildAddWindowsToNodes()
  11066. //-----------------------------------------------------------------------------
  11067. void ImGui::DockContextInitialize(ImGuiContext* ctx)
  11068. {
  11069. ImGuiContext& g = *ctx;
  11070. // Add .ini handle for persistent docking data
  11071. ImGuiSettingsHandler ini_handler;
  11072. ini_handler.TypeName = "Docking";
  11073. ini_handler.TypeHash = ImHashStr("Docking");
  11074. ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
  11075. ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
  11076. ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
  11077. ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
  11078. ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
  11079. ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
  11080. g.SettingsHandlers.push_back(ini_handler);
  11081. }
  11082. void ImGui::DockContextShutdown(ImGuiContext* ctx)
  11083. {
  11084. ImGuiDockContext* dc = &ctx->DockContext;
  11085. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  11086. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  11087. IM_DELETE(node);
  11088. }
  11089. void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
  11090. {
  11091. IM_UNUSED(ctx);
  11092. IM_ASSERT(ctx == GImGui);
  11093. DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
  11094. DockBuilderRemoveNodeChildNodes(root_id);
  11095. }
  11096. // [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
  11097. // (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
  11098. void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
  11099. {
  11100. IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n");
  11101. ImGuiDockContext* dc = &ctx->DockContext;
  11102. SaveIniSettingsToMemory();
  11103. ImGuiID root_id = 0; // Rebuild all
  11104. DockContextClearNodes(ctx, root_id, false);
  11105. DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
  11106. DockContextBuildAddWindowsToNodes(ctx, root_id);
  11107. }
  11108. // Docking context update function, called by NewFrame()
  11109. void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
  11110. {
  11111. ImGuiContext& g = *ctx;
  11112. ImGuiDockContext* dc = &ctx->DockContext;
  11113. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  11114. {
  11115. if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
  11116. DockContextClearNodes(ctx, 0, true);
  11117. return;
  11118. }
  11119. // Setting NoSplit at runtime merges all nodes
  11120. if (g.IO.ConfigDockingNoSplit)
  11121. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  11122. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  11123. if (node->IsRootNode() && node->IsSplitNode())
  11124. {
  11125. DockBuilderRemoveNodeChildNodes(node->ID);
  11126. //dc->WantFullRebuild = true;
  11127. }
  11128. // Process full rebuild
  11129. #if 0
  11130. if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
  11131. dc->WantFullRebuild = true;
  11132. #endif
  11133. if (dc->WantFullRebuild)
  11134. {
  11135. DockContextRebuildNodes(ctx);
  11136. dc->WantFullRebuild = false;
  11137. }
  11138. // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
  11139. for (int n = 0; n < dc->Requests.Size; n++)
  11140. {
  11141. ImGuiDockRequest* req = &dc->Requests[n];
  11142. if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
  11143. DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
  11144. else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
  11145. DockContextProcessUndockNode(ctx, req->UndockTargetNode);
  11146. }
  11147. }
  11148. // Docking context update function, called by NewFrame()
  11149. void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
  11150. {
  11151. ImGuiContext& g = *ctx;
  11152. ImGuiDockContext* dc = &ctx->DockContext;
  11153. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  11154. return;
  11155. // [DEBUG] Store hovered dock node.
  11156. // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
  11157. // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
  11158. g.HoveredDockNode = NULL;
  11159. if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
  11160. {
  11161. if (hovered_window->DockNodeAsHost)
  11162. g.HoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
  11163. else if (hovered_window->RootWindow->DockNode)
  11164. g.HoveredDockNode = hovered_window->RootWindow->DockNode;
  11165. }
  11166. // Process Docking requests
  11167. for (int n = 0; n < dc->Requests.Size; n++)
  11168. if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
  11169. DockContextProcessDock(ctx, &dc->Requests[n]);
  11170. dc->Requests.resize(0);
  11171. // Create windows for each automatic docking nodes
  11172. // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
  11173. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  11174. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  11175. if (node->IsFloatingNode())
  11176. DockNodeUpdate(node);
  11177. }
  11178. static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
  11179. {
  11180. return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
  11181. }
  11182. ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
  11183. {
  11184. // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
  11185. // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry. We should poke in ctx->Nodes to find a suitable ID faster.
  11186. ImGuiID id = 0x0001;
  11187. while (DockContextFindNodeByID(ctx, id) != NULL)
  11188. id++;
  11189. return id;
  11190. }
  11191. static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
  11192. {
  11193. // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
  11194. if (id == 0)
  11195. id = DockContextGenNodeID(ctx);
  11196. else
  11197. IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
  11198. // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
  11199. IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id);
  11200. ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
  11201. ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
  11202. return node;
  11203. }
  11204. static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
  11205. {
  11206. ImGuiContext& g = *ctx;
  11207. ImGuiDockContext* dc = &ctx->DockContext;
  11208. IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID);
  11209. IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
  11210. IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
  11211. IM_ASSERT(node->Windows.Size == 0);
  11212. if (node->HostWindow)
  11213. node->HostWindow->DockNodeAsHost = NULL;
  11214. ImGuiDockNode* parent_node = node->ParentNode;
  11215. const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
  11216. if (merge)
  11217. {
  11218. IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
  11219. ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
  11220. DockNodeTreeMerge(&g, parent_node, sibling_node);
  11221. }
  11222. else
  11223. {
  11224. for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
  11225. if (parent_node->ChildNodes[n] == node)
  11226. node->ParentNode->ChildNodes[n] = NULL;
  11227. dc->Nodes.SetVoidPtr(node->ID, NULL);
  11228. IM_DELETE(node);
  11229. }
  11230. }
  11231. static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
  11232. {
  11233. const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
  11234. const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
  11235. return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
  11236. }
  11237. // Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
  11238. struct ImGuiDockContextPruneNodeData
  11239. {
  11240. int CountWindows, CountChildWindows, CountChildNodes;
  11241. ImGuiID RootId;
  11242. ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
  11243. };
  11244. // Garbage collect unused nodes (run once at init time)
  11245. static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
  11246. {
  11247. ImGuiContext& g = *ctx;
  11248. ImGuiDockContext* dc = &ctx->DockContext;
  11249. IM_ASSERT(g.Windows.Size == 0);
  11250. ImPool<ImGuiDockContextPruneNodeData> pool;
  11251. pool.Reserve(dc->NodesSettings.Size);
  11252. // Count child nodes and compute RootID
  11253. for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
  11254. {
  11255. ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
  11256. ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
  11257. pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
  11258. if (settings->ParentNodeId)
  11259. pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
  11260. }
  11261. // Count reference to dock ids from dockspaces
  11262. // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
  11263. for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
  11264. {
  11265. ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
  11266. if (settings->ParentWindowId != 0)
  11267. if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId))
  11268. if (window_settings->DockId)
  11269. if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
  11270. data->CountChildNodes++;
  11271. }
  11272. // Count reference to dock ids from window settings
  11273. // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
  11274. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  11275. if (ImGuiID dock_id = settings->DockId)
  11276. if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
  11277. {
  11278. data->CountWindows++;
  11279. if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
  11280. data_root->CountChildWindows++;
  11281. }
  11282. // Prune
  11283. for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
  11284. {
  11285. ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
  11286. ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
  11287. if (data->CountWindows > 1)
  11288. continue;
  11289. ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
  11290. bool remove = false;
  11291. remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
  11292. remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
  11293. remove |= (data_root->CountChildWindows == 0);
  11294. if (remove)
  11295. {
  11296. IMGUI_DEBUG_LOG_DOCKING("DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
  11297. DockSettingsRemoveNodeReferences(&settings->ID, 1);
  11298. settings->ID = 0;
  11299. }
  11300. }
  11301. }
  11302. static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
  11303. {
  11304. // Build nodes
  11305. for (int node_n = 0; node_n < node_settings_count; node_n++)
  11306. {
  11307. ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
  11308. if (settings->ID == 0)
  11309. continue;
  11310. ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
  11311. node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
  11312. node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
  11313. node->Size = ImVec2(settings->Size.x, settings->Size.y);
  11314. node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
  11315. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
  11316. if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
  11317. node->ParentNode->ChildNodes[0] = node;
  11318. else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
  11319. node->ParentNode->ChildNodes[1] = node;
  11320. node->SelectedTabId = settings->SelectedTabId;
  11321. node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
  11322. node->LocalFlags |= (settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
  11323. // Bind host window immediately if it already exist (in case of a rebuild)
  11324. // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
  11325. char host_window_title[20];
  11326. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  11327. node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
  11328. }
  11329. }
  11330. void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
  11331. {
  11332. // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
  11333. ImGuiContext& g = *ctx;
  11334. for (int n = 0; n < g.Windows.Size; n++)
  11335. {
  11336. ImGuiWindow* window = g.Windows[n];
  11337. if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
  11338. continue;
  11339. if (window->DockNode != NULL)
  11340. continue;
  11341. ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
  11342. IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
  11343. if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
  11344. DockNodeAddWindow(node, window, true);
  11345. }
  11346. }
  11347. //-----------------------------------------------------------------------------
  11348. // Docking: ImGuiDockContext Docking/Undocking functions
  11349. //-----------------------------------------------------------------------------
  11350. // - DockContextQueueDock()
  11351. // - DockContextQueueUndockWindow()
  11352. // - DockContextQueueUndockNode()
  11353. // - DockContextQueueNotifyRemovedNode()
  11354. // - DockContextProcessDock()
  11355. // - DockContextProcessUndockWindow()
  11356. // - DockContextProcessUndockNode()
  11357. // - DockContextCalcDropPosForDocking()
  11358. //-----------------------------------------------------------------------------
  11359. void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
  11360. {
  11361. IM_ASSERT(target != payload);
  11362. ImGuiDockRequest req;
  11363. req.Type = ImGuiDockRequestType_Dock;
  11364. req.DockTargetWindow = target;
  11365. req.DockTargetNode = target_node;
  11366. req.DockPayload = payload;
  11367. req.DockSplitDir = split_dir;
  11368. req.DockSplitRatio = split_ratio;
  11369. req.DockSplitOuter = split_outer;
  11370. ctx->DockContext.Requests.push_back(req);
  11371. }
  11372. void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
  11373. {
  11374. ImGuiDockRequest req;
  11375. req.Type = ImGuiDockRequestType_Undock;
  11376. req.UndockTargetWindow = window;
  11377. ctx->DockContext.Requests.push_back(req);
  11378. }
  11379. void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
  11380. {
  11381. ImGuiDockRequest req;
  11382. req.Type = ImGuiDockRequestType_Undock;
  11383. req.UndockTargetNode = node;
  11384. ctx->DockContext.Requests.push_back(req);
  11385. }
  11386. void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
  11387. {
  11388. ImGuiDockContext* dc = &ctx->DockContext;
  11389. for (int n = 0; n < dc->Requests.Size; n++)
  11390. if (dc->Requests[n].DockTargetNode == node)
  11391. dc->Requests[n].Type = ImGuiDockRequestType_None;
  11392. }
  11393. void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
  11394. {
  11395. IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
  11396. IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
  11397. ImGuiContext& g = *ctx;
  11398. IM_UNUSED(g);
  11399. ImGuiWindow* payload_window = req->DockPayload; // Optional
  11400. ImGuiWindow* target_window = req->DockTargetWindow;
  11401. ImGuiDockNode* node = req->DockTargetNode;
  11402. if (payload_window)
  11403. IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window ? payload_window->Name : "NULL", req->DockSplitDir);
  11404. else
  11405. IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
  11406. // Decide which Tab will be selected at the end of the operation
  11407. ImGuiID next_selected_id = 0;
  11408. ImGuiDockNode* payload_node = NULL;
  11409. if (payload_window)
  11410. {
  11411. payload_node = payload_window->DockNodeAsHost;
  11412. payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
  11413. if (payload_node && payload_node->IsLeafNode())
  11414. next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
  11415. if (payload_node == NULL)
  11416. next_selected_id = payload_window->ID;
  11417. }
  11418. // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
  11419. // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
  11420. if (node)
  11421. IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
  11422. if (node && target_window && node == target_window->DockNodeAsHost)
  11423. IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
  11424. // Create new node and add existing window to it
  11425. if (node == NULL)
  11426. {
  11427. node = DockContextAddNode(ctx, 0);
  11428. node->Pos = target_window->Pos;
  11429. node->Size = target_window->Size;
  11430. if (target_window->DockNodeAsHost == NULL)
  11431. {
  11432. DockNodeAddWindow(node, target_window, true);
  11433. node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
  11434. target_window->DockIsActive = true;
  11435. }
  11436. }
  11437. ImGuiDir split_dir = req->DockSplitDir;
  11438. if (split_dir != ImGuiDir_None)
  11439. {
  11440. // Split into two, one side will be our payload node unless we are dropping a loose window
  11441. const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  11442. const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
  11443. const float split_ratio = req->DockSplitRatio;
  11444. DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here!
  11445. ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
  11446. new_node->HostWindow = node->HostWindow;
  11447. node = new_node;
  11448. }
  11449. node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar;
  11450. if (node != payload_node)
  11451. {
  11452. // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
  11453. if (node->Windows.Size > 0 && node->TabBar == NULL)
  11454. {
  11455. DockNodeAddTabBar(node);
  11456. for (int n = 0; n < node->Windows.Size; n++)
  11457. TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
  11458. }
  11459. if (payload_node != NULL)
  11460. {
  11461. // Transfer full payload node (with 1+ child windows or child nodes)
  11462. if (payload_node->IsSplitNode())
  11463. {
  11464. if (node->Windows.Size > 0)
  11465. {
  11466. // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
  11467. // In this situation, we move the windows of the target node into the currently visible node of the payload.
  11468. // This allows us to preserve some of the underlying dock tree settings nicely.
  11469. IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
  11470. ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
  11471. if (visible_node->TabBar)
  11472. IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
  11473. DockNodeMoveWindows(node, visible_node);
  11474. DockNodeMoveWindows(visible_node, node);
  11475. DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
  11476. }
  11477. if (node->IsCentralNode())
  11478. {
  11479. // Central node property needs to be moved to a leaf node, pick the last focused one.
  11480. // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
  11481. ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
  11482. IM_ASSERT(last_focused_node != NULL);
  11483. ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
  11484. IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
  11485. last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  11486. node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode;
  11487. last_focused_root_node->CentralNode = last_focused_node;
  11488. }
  11489. IM_ASSERT(node->Windows.Size == 0);
  11490. DockNodeMoveChildNodes(node, payload_node);
  11491. }
  11492. else
  11493. {
  11494. const ImGuiID payload_dock_id = payload_node->ID;
  11495. DockNodeMoveWindows(node, payload_node);
  11496. DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
  11497. }
  11498. DockContextRemoveNode(ctx, payload_node, true);
  11499. }
  11500. else if (payload_window)
  11501. {
  11502. // Transfer single window
  11503. const ImGuiID payload_dock_id = payload_window->DockId;
  11504. node->VisibleWindow = payload_window;
  11505. DockNodeAddWindow(node, payload_window, true);
  11506. if (payload_dock_id != 0)
  11507. DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
  11508. }
  11509. }
  11510. else
  11511. {
  11512. // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
  11513. node->WantHiddenTabBarUpdate = true;
  11514. }
  11515. // Update selection immediately
  11516. if (ImGuiTabBar* tab_bar = node->TabBar)
  11517. tab_bar->NextSelectedTabId = next_selected_id;
  11518. MarkIniSettingsDirty();
  11519. }
  11520. // Problem:
  11521. // Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
  11522. // than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
  11523. // with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
  11524. // due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
  11525. // Solution:
  11526. // When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
  11527. // Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
  11528. static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
  11529. {
  11530. if (ref_viewport == NULL)
  11531. return size;
  11532. ImGuiContext& g = *GImGui;
  11533. ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
  11534. if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
  11535. {
  11536. const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
  11537. max_size = ImFloor(monitor->WorkSize * 0.90f);
  11538. }
  11539. return ImMin(size, max_size);
  11540. }
  11541. void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
  11542. {
  11543. IMGUI_DEBUG_LOG_DOCKING("DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
  11544. IM_UNUSED(ctx);
  11545. if (window->DockNode)
  11546. DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
  11547. else
  11548. window->DockId = 0;
  11549. window->Collapsed = false;
  11550. window->DockIsActive = false;
  11551. window->DockTabIsVisible = false;
  11552. window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
  11553. MarkIniSettingsDirty();
  11554. }
  11555. void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
  11556. {
  11557. IMGUI_DEBUG_LOG_DOCKING("DockContextProcessUndockNode node %08X\n", node->ID);
  11558. IM_ASSERT(node->IsLeafNode());
  11559. IM_ASSERT(node->Windows.Size >= 1);
  11560. if (node->IsRootNode() || node->IsCentralNode())
  11561. {
  11562. // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
  11563. ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
  11564. new_node->Pos = node->Pos;
  11565. new_node->Size = node->Size;
  11566. new_node->SizeRef = node->SizeRef;
  11567. DockNodeMoveWindows(new_node, node);
  11568. DockSettingsRenameNodeReferences(node->ID, new_node->ID);
  11569. for (int n = 0; n < new_node->Windows.Size; n++)
  11570. UpdateWindowParentAndRootLinks(new_node->Windows[n], new_node->Windows[n]->Flags, NULL);
  11571. node = new_node;
  11572. }
  11573. else
  11574. {
  11575. // Otherwise extract our node and merge our sibling back into the parent node.
  11576. IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
  11577. int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
  11578. node->ParentNode->ChildNodes[index_in_parent] = NULL;
  11579. DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
  11580. node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
  11581. node->ParentNode = NULL;
  11582. }
  11583. node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
  11584. node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
  11585. node->WantMouseMove = true;
  11586. MarkIniSettingsDirty();
  11587. }
  11588. // This is mostly used for automation.
  11589. bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
  11590. {
  11591. // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
  11592. // (which would be functionally identical) we only show the outer one. Reflect this here.
  11593. if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
  11594. split_outer = true;
  11595. ImGuiDockPreviewData split_data;
  11596. DockNodePreviewDockSetup(target, target_node, payload, &split_data, false, split_outer);
  11597. if (split_data.DropRectsDraw[split_dir+1].IsInverted())
  11598. return false;
  11599. *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
  11600. return true;
  11601. }
  11602. //-----------------------------------------------------------------------------
  11603. // Docking: ImGuiDockNode
  11604. //-----------------------------------------------------------------------------
  11605. // - DockNodeGetTabOrder()
  11606. // - DockNodeAddWindow()
  11607. // - DockNodeRemoveWindow()
  11608. // - DockNodeMoveChildNodes()
  11609. // - DockNodeMoveWindows()
  11610. // - DockNodeApplyPosSizeToWindows()
  11611. // - DockNodeHideHostWindow()
  11612. // - ImGuiDockNodeFindInfoResults
  11613. // - DockNodeFindInfo()
  11614. // - DockNodeFindWindowByID()
  11615. // - DockNodeUpdateVisibleFlagAndInactiveChilds()
  11616. // - DockNodeUpdateVisibleFlag()
  11617. // - DockNodeStartMouseMovingWindow()
  11618. // - DockNodeUpdate()
  11619. // - DockNodeUpdateWindowMenu()
  11620. // - DockNodeBeginAmendTabBar()
  11621. // - DockNodeEndAmendTabBar()
  11622. // - DockNodeUpdateTabBar()
  11623. // - DockNodeAddTabBar()
  11624. // - DockNodeRemoveTabBar()
  11625. // - DockNodeIsDropAllowedOne()
  11626. // - DockNodeIsDropAllowed()
  11627. // - DockNodeCalcTabBarLayout()
  11628. // - DockNodeCalcSplitRects()
  11629. // - DockNodeCalcDropRectsAndTestMousePos()
  11630. // - DockNodePreviewDockSetup()
  11631. // - DockNodePreviewDockRender()
  11632. //-----------------------------------------------------------------------------
  11633. ImGuiDockNode::ImGuiDockNode(ImGuiID id)
  11634. {
  11635. ID = id;
  11636. SharedFlags = LocalFlags = ImGuiDockNodeFlags_None;
  11637. ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
  11638. TabBar = NULL;
  11639. SplitAxis = ImGuiAxis_None;
  11640. State = ImGuiDockNodeState_Unknown;
  11641. HostWindow = VisibleWindow = NULL;
  11642. CentralNode = OnlyNodeWithWindows = NULL;
  11643. LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
  11644. LastFocusedNodeId = 0;
  11645. SelectedTabId = 0;
  11646. WantCloseTabId = 0;
  11647. AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
  11648. AuthorityForViewport = ImGuiDataAuthority_Auto;
  11649. IsVisible = true;
  11650. IsFocused = HasCloseButton = HasWindowMenuButton = false;
  11651. WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
  11652. MarkedForPosSizeWrite = false;
  11653. }
  11654. ImGuiDockNode::~ImGuiDockNode()
  11655. {
  11656. IM_DELETE(TabBar);
  11657. TabBar = NULL;
  11658. ChildNodes[0] = ChildNodes[1] = NULL;
  11659. }
  11660. int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
  11661. {
  11662. ImGuiTabBar* tab_bar = window->DockNode->TabBar;
  11663. if (tab_bar == NULL)
  11664. return -1;
  11665. ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->ID);
  11666. return tab ? tab_bar->GetTabOrder(tab) : -1;
  11667. }
  11668. static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
  11669. {
  11670. window->Hidden = true;
  11671. window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
  11672. }
  11673. static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
  11674. {
  11675. ImGuiContext& g = *GImGui; (void)g;
  11676. if (window->DockNode)
  11677. {
  11678. // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
  11679. IM_ASSERT(window->DockNode->ID != node->ID);
  11680. DockNodeRemoveWindow(window->DockNode, window, 0);
  11681. }
  11682. IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
  11683. IMGUI_DEBUG_LOG_DOCKING("DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
  11684. // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
  11685. // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
  11686. // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
  11687. if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
  11688. DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
  11689. node->Windows.push_back(window);
  11690. node->WantHiddenTabBarUpdate = true;
  11691. window->DockNode = node;
  11692. window->DockId = node->ID;
  11693. window->DockIsActive = (node->Windows.Size > 1);
  11694. window->DockTabWantClose = false;
  11695. // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
  11696. // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
  11697. if (node->HostWindow == NULL && node->IsFloatingNode())
  11698. {
  11699. if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
  11700. node->AuthorityForPos = ImGuiDataAuthority_Window;
  11701. if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
  11702. node->AuthorityForSize = ImGuiDataAuthority_Window;
  11703. if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
  11704. node->AuthorityForViewport = ImGuiDataAuthority_Window;
  11705. }
  11706. // Add to tab bar if requested
  11707. if (add_to_tab_bar)
  11708. {
  11709. if (node->TabBar == NULL)
  11710. {
  11711. DockNodeAddTabBar(node);
  11712. node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
  11713. // Add existing windows
  11714. for (int n = 0; n < node->Windows.Size - 1; n++)
  11715. TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
  11716. }
  11717. TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
  11718. }
  11719. DockNodeUpdateVisibleFlag(node);
  11720. // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
  11721. if (node->HostWindow)
  11722. UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
  11723. }
  11724. static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
  11725. {
  11726. ImGuiContext& g = *GImGui;
  11727. IM_ASSERT(window->DockNode == node);
  11728. //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
  11729. //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
  11730. IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
  11731. IMGUI_DEBUG_LOG_DOCKING("DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
  11732. window->DockNode = NULL;
  11733. window->DockIsActive = window->DockTabWantClose = false;
  11734. window->DockId = save_dock_id;
  11735. UpdateWindowParentAndRootLinks(window, window->Flags & ~ImGuiWindowFlags_ChildWindow, NULL); // Update immediately
  11736. // Remove window
  11737. bool erased = false;
  11738. for (int n = 0; n < node->Windows.Size; n++)
  11739. if (node->Windows[n] == window)
  11740. {
  11741. node->Windows.erase(node->Windows.Data + n);
  11742. erased = true;
  11743. break;
  11744. }
  11745. IM_ASSERT(erased);
  11746. if (node->VisibleWindow == window)
  11747. node->VisibleWindow = NULL;
  11748. // Remove tab and possibly tab bar
  11749. node->WantHiddenTabBarUpdate = true;
  11750. if (node->TabBar)
  11751. {
  11752. TabBarRemoveTab(node->TabBar, window->ID);
  11753. const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
  11754. if (node->Windows.Size < tab_count_threshold_for_tab_bar)
  11755. DockNodeRemoveTabBar(node);
  11756. }
  11757. if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
  11758. {
  11759. // Automatic dock node delete themselves if they are not holding at least one tab
  11760. DockContextRemoveNode(&g, node, true);
  11761. return;
  11762. }
  11763. if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
  11764. {
  11765. ImGuiWindow* remaining_window = node->Windows[0];
  11766. if (node->HostWindow->ViewportOwned && node->IsRootNode())
  11767. {
  11768. // Transfer viewport back to the remaining loose window
  11769. IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
  11770. node->HostWindow->Viewport->Window = remaining_window;
  11771. node->HostWindow->Viewport->ID = remaining_window->ID;
  11772. }
  11773. remaining_window->Collapsed = node->HostWindow->Collapsed;
  11774. }
  11775. // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
  11776. DockNodeUpdateVisibleFlag(node);
  11777. }
  11778. static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
  11779. {
  11780. IM_ASSERT(dst_node->Windows.Size == 0);
  11781. dst_node->ChildNodes[0] = src_node->ChildNodes[0];
  11782. dst_node->ChildNodes[1] = src_node->ChildNodes[1];
  11783. if (dst_node->ChildNodes[0])
  11784. dst_node->ChildNodes[0]->ParentNode = dst_node;
  11785. if (dst_node->ChildNodes[1])
  11786. dst_node->ChildNodes[1]->ParentNode = dst_node;
  11787. dst_node->SplitAxis = src_node->SplitAxis;
  11788. dst_node->SizeRef = src_node->SizeRef;
  11789. src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
  11790. }
  11791. static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
  11792. {
  11793. // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
  11794. IM_ASSERT(src_node && dst_node && dst_node != src_node);
  11795. ImGuiTabBar* src_tab_bar = src_node->TabBar;
  11796. if (src_tab_bar != NULL)
  11797. IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
  11798. // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
  11799. bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
  11800. if (move_tab_bar)
  11801. {
  11802. dst_node->TabBar = src_node->TabBar;
  11803. src_node->TabBar = NULL;
  11804. }
  11805. for (int n = 0; n < src_node->Windows.Size; n++)
  11806. {
  11807. // DockNode's TabBar may have non-window Tabs manually appended by user
  11808. if (ImGuiWindow* window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n])
  11809. {
  11810. window->DockNode = NULL;
  11811. window->DockIsActive = false;
  11812. DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true);
  11813. }
  11814. }
  11815. src_node->Windows.clear();
  11816. if (!move_tab_bar && src_node->TabBar)
  11817. {
  11818. if (dst_node->TabBar)
  11819. dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
  11820. DockNodeRemoveTabBar(src_node);
  11821. }
  11822. }
  11823. static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
  11824. {
  11825. for (int n = 0; n < node->Windows.Size; n++)
  11826. {
  11827. SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
  11828. SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
  11829. }
  11830. }
  11831. static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
  11832. {
  11833. if (node->HostWindow)
  11834. {
  11835. if (node->HostWindow->DockNodeAsHost == node)
  11836. node->HostWindow->DockNodeAsHost = NULL;
  11837. node->HostWindow = NULL;
  11838. }
  11839. if (node->Windows.Size == 1)
  11840. {
  11841. node->VisibleWindow = node->Windows[0];
  11842. node->Windows[0]->DockIsActive = false;
  11843. }
  11844. if (node->TabBar)
  11845. DockNodeRemoveTabBar(node);
  11846. }
  11847. // Search function called once by root node in DockNodeUpdate()
  11848. struct ImGuiDockNodeFindInfoResults
  11849. {
  11850. ImGuiDockNode* CentralNode;
  11851. ImGuiDockNode* FirstNodeWithWindows;
  11852. int CountNodesWithWindows;
  11853. //ImGuiWindowClass WindowClassForMerges;
  11854. ImGuiDockNodeFindInfoResults() { CentralNode = FirstNodeWithWindows = NULL; CountNodesWithWindows = 0; }
  11855. };
  11856. static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeFindInfoResults* results)
  11857. {
  11858. if (node->Windows.Size > 0)
  11859. {
  11860. if (results->FirstNodeWithWindows == NULL)
  11861. results->FirstNodeWithWindows = node;
  11862. results->CountNodesWithWindows++;
  11863. }
  11864. if (node->IsCentralNode())
  11865. {
  11866. IM_ASSERT(results->CentralNode == NULL); // Should be only one
  11867. IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
  11868. results->CentralNode = node;
  11869. }
  11870. if (results->CountNodesWithWindows > 1 && results->CentralNode != NULL)
  11871. return;
  11872. if (node->ChildNodes[0])
  11873. DockNodeFindInfo(node->ChildNodes[0], results);
  11874. if (node->ChildNodes[1])
  11875. DockNodeFindInfo(node->ChildNodes[1], results);
  11876. }
  11877. static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
  11878. {
  11879. IM_ASSERT(id != 0);
  11880. for (int n = 0; n < node->Windows.Size; n++)
  11881. if (node->Windows[n]->ID == id)
  11882. return node->Windows[n];
  11883. return NULL;
  11884. }
  11885. // - Remove inactive windows/nodes.
  11886. // - Update visibility flag.
  11887. static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node)
  11888. {
  11889. ImGuiContext& g = *GImGui;
  11890. IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
  11891. // Inherit most flags
  11892. if (node->ParentNode)
  11893. node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
  11894. // Recurse into children
  11895. // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
  11896. // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
  11897. // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
  11898. if (node->ChildNodes[0])
  11899. DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[0]);
  11900. if (node->ChildNodes[1])
  11901. DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[1]);
  11902. // Remove inactive windows
  11903. // Merge node flags overrides stored in windows
  11904. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  11905. {
  11906. ImGuiWindow* window = node->Windows[window_n];
  11907. IM_ASSERT(window->DockNode == node);
  11908. bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
  11909. bool remove = false;
  11910. remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
  11911. remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
  11912. remove |= (window->DockTabWantClose);
  11913. if (remove)
  11914. {
  11915. window->DockTabWantClose = false;
  11916. if (node->Windows.Size == 1 && !node->IsCentralNode())
  11917. {
  11918. DockNodeHideHostWindow(node);
  11919. node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
  11920. DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
  11921. return;
  11922. }
  11923. DockNodeRemoveWindow(node, window, node->ID);
  11924. window_n--;
  11925. }
  11926. else
  11927. {
  11928. // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
  11929. node->LocalFlags &= ~window->WindowClass.DockNodeFlagsOverrideClear;
  11930. node->LocalFlags |= window->WindowClass.DockNodeFlagsOverrideSet;
  11931. }
  11932. }
  11933. // Auto-hide tab bar option
  11934. ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
  11935. if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
  11936. node->WantHiddenTabBarToggle = true;
  11937. node->WantHiddenTabBarUpdate = false;
  11938. // Cancel toggling if we know our tab bar is enforced to be hidden at all times
  11939. if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
  11940. node->WantHiddenTabBarToggle = false;
  11941. // Apply toggles at a single point of the frame (here!)
  11942. if (node->Windows.Size > 1)
  11943. node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar;
  11944. else if (node->WantHiddenTabBarToggle)
  11945. node->LocalFlags ^= ImGuiDockNodeFlags_HiddenTabBar;
  11946. node->WantHiddenTabBarToggle = false;
  11947. DockNodeUpdateVisibleFlag(node);
  11948. }
  11949. static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
  11950. {
  11951. // Update visibility flag
  11952. bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
  11953. is_visible |= (node->Windows.Size > 0);
  11954. is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
  11955. is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
  11956. node->IsVisible = is_visible;
  11957. }
  11958. static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
  11959. {
  11960. ImGuiContext& g = *GImGui;
  11961. IM_ASSERT(node->WantMouseMove == true);
  11962. StartMouseMovingWindow(window);
  11963. g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
  11964. g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
  11965. node->WantMouseMove = false;
  11966. }
  11967. // Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
  11968. static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
  11969. {
  11970. DockNodeUpdateVisibleFlagAndInactiveChilds(node);
  11971. // FIXME-DOCK: Merge this scan into the one above.
  11972. // - Setup central node pointers
  11973. // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
  11974. ImGuiDockNodeFindInfoResults results;
  11975. DockNodeFindInfo(node, &results);
  11976. node->CentralNode = results.CentralNode;
  11977. node->OnlyNodeWithWindows = (results.CountNodesWithWindows == 1) ? results.FirstNodeWithWindows : NULL;
  11978. if (node->LastFocusedNodeId == 0 && results.FirstNodeWithWindows != NULL)
  11979. node->LastFocusedNodeId = results.FirstNodeWithWindows->ID;
  11980. // Copy the window class from of our first window so it can be used for proper dock filtering.
  11981. // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
  11982. // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
  11983. if (ImGuiDockNode* first_node_with_windows = results.FirstNodeWithWindows)
  11984. {
  11985. node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
  11986. for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
  11987. if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
  11988. {
  11989. node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
  11990. break;
  11991. }
  11992. }
  11993. }
  11994. static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
  11995. {
  11996. ImGuiContext& g = *GImGui;
  11997. IM_ASSERT(node->LastFrameActive != g.FrameCount);
  11998. node->LastFrameAlive = g.FrameCount;
  11999. node->MarkedForPosSizeWrite = false;
  12000. node->CentralNode = node->OnlyNodeWithWindows = NULL;
  12001. if (node->IsRootNode())
  12002. DockNodeUpdateForRootNode(node);
  12003. // Remove tab bar if not needed
  12004. if (node->TabBar && node->IsNoTabBar())
  12005. DockNodeRemoveTabBar(node);
  12006. // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
  12007. bool want_to_hide_host_window = false;
  12008. if (node->Windows.Size <= 1 && node->IsFloatingNode() && node->IsLeafNode())
  12009. if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
  12010. want_to_hide_host_window = true;
  12011. if (want_to_hide_host_window)
  12012. {
  12013. if (node->Windows.Size == 1)
  12014. {
  12015. // Floating window pos/size is authoritative
  12016. ImGuiWindow* single_window = node->Windows[0];
  12017. node->Pos = single_window->Pos;
  12018. node->Size = single_window->SizeFull;
  12019. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
  12020. // Transfer focus immediately so when we revert to a regular window it is immediately selected
  12021. if (node->HostWindow && g.NavWindow == node->HostWindow)
  12022. FocusWindow(single_window);
  12023. if (node->HostWindow)
  12024. {
  12025. single_window->Viewport = node->HostWindow->Viewport;
  12026. single_window->ViewportId = node->HostWindow->ViewportId;
  12027. if (node->HostWindow->ViewportOwned)
  12028. {
  12029. single_window->Viewport->Window = single_window;
  12030. single_window->ViewportOwned = true;
  12031. }
  12032. }
  12033. }
  12034. DockNodeHideHostWindow(node);
  12035. node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
  12036. node->WantCloseAll = false;
  12037. node->WantCloseTabId = 0;
  12038. node->HasCloseButton = node->HasWindowMenuButton = false;
  12039. node->LastFrameActive = g.FrameCount;
  12040. if (node->WantMouseMove && node->Windows.Size == 1)
  12041. DockNodeStartMouseMovingWindow(node, node->Windows[0]);
  12042. return;
  12043. }
  12044. // In some circumstance we will defer creating the host window (so everything will be kept hidden),
  12045. // while the expected visible window is resizing itself.
  12046. // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
  12047. // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
  12048. // N+0: Begin(): window created (with no known size), node is created
  12049. // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
  12050. // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
  12051. // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
  12052. // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
  12053. // In reality it isn't very important as user quickly ends up with size data in .ini file.
  12054. if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
  12055. {
  12056. IM_ASSERT(node->Windows.Size > 0);
  12057. ImGuiWindow* ref_window = NULL;
  12058. if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
  12059. ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
  12060. if (ref_window == NULL)
  12061. ref_window = node->Windows[0];
  12062. if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
  12063. {
  12064. node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
  12065. return;
  12066. }
  12067. }
  12068. const ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
  12069. // Decide if the node will have a close button and a window menu button
  12070. node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
  12071. node->HasCloseButton = false;
  12072. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  12073. {
  12074. // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
  12075. ImGuiWindow* window = node->Windows[window_n];
  12076. node->HasCloseButton |= window->HasCloseButton;
  12077. window->DockIsActive = (node->Windows.Size > 1);
  12078. }
  12079. if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
  12080. node->HasCloseButton = false;
  12081. // Bind or create host window
  12082. ImGuiWindow* host_window = NULL;
  12083. bool beginned_into_host_window = false;
  12084. if (node->IsDockSpace())
  12085. {
  12086. // [Explicit root dockspace node]
  12087. IM_ASSERT(node->HostWindow);
  12088. host_window = node->HostWindow;
  12089. }
  12090. else
  12091. {
  12092. // [Automatic root or child nodes]
  12093. if (node->IsRootNode() && node->IsVisible)
  12094. {
  12095. ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
  12096. // Sync Pos
  12097. if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
  12098. SetNextWindowPos(ref_window->Pos);
  12099. else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
  12100. SetNextWindowPos(node->Pos);
  12101. // Sync Size
  12102. if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
  12103. SetNextWindowSize(ref_window->SizeFull);
  12104. else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
  12105. SetNextWindowSize(node->Size);
  12106. // Sync Collapsed
  12107. if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
  12108. SetNextWindowCollapsed(ref_window->Collapsed);
  12109. // Sync Viewport
  12110. if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
  12111. SetNextWindowViewport(ref_window->ViewportId);
  12112. SetNextWindowClass(&node->WindowClass);
  12113. // Begin into the host window
  12114. char window_label[20];
  12115. DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
  12116. ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
  12117. window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
  12118. window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
  12119. window_flags |= ImGuiWindowFlags_NoTitleBar;
  12120. PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
  12121. Begin(window_label, NULL, window_flags);
  12122. PopStyleVar();
  12123. beginned_into_host_window = true;
  12124. node->HostWindow = host_window = g.CurrentWindow;
  12125. host_window->DockNodeAsHost = node;
  12126. host_window->DC.CursorPos = host_window->Pos;
  12127. node->Pos = host_window->Pos;
  12128. node->Size = host_window->Size;
  12129. // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
  12130. // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
  12131. // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
  12132. // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
  12133. // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
  12134. // after the dock host window, losing their top-most status.
  12135. if (node->HostWindow->Appearing)
  12136. BringWindowToDisplayFront(node->HostWindow);
  12137. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
  12138. }
  12139. else if (node->ParentNode)
  12140. {
  12141. node->HostWindow = host_window = node->ParentNode->HostWindow;
  12142. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
  12143. }
  12144. if (node->WantMouseMove && node->HostWindow)
  12145. DockNodeStartMouseMovingWindow(node, node->HostWindow);
  12146. }
  12147. // Update focused node (the one whose title bar is highlight) within a node tree
  12148. if (node->IsSplitNode())
  12149. IM_ASSERT(node->TabBar == NULL);
  12150. if (node->IsRootNode())
  12151. if (g.NavWindow && g.NavWindow->RootWindow->DockNode && g.NavWindow->RootWindow->ParentWindow == host_window)
  12152. node->LastFocusedNodeId = g.NavWindow->RootWindow->DockNode->ID;
  12153. // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
  12154. // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
  12155. const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
  12156. if (render_dockspace_bg)
  12157. {
  12158. host_window->DrawList->ChannelsSplit(2);
  12159. host_window->DrawList->ChannelsSetCurrent(1);
  12160. }
  12161. // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
  12162. ImGuiDockNode* central_node = node->CentralNode;
  12163. const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
  12164. bool central_node_hole_register_hit_test_hole = central_node_hole;
  12165. if (central_node_hole)
  12166. if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
  12167. if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
  12168. central_node_hole_register_hit_test_hole = false;
  12169. if (central_node_hole_register_hit_test_hole)
  12170. {
  12171. // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
  12172. // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
  12173. // covering passthru node we'd have a gap on the edge not covered by the hole)
  12174. IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
  12175. ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
  12176. ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
  12177. ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
  12178. if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
  12179. if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
  12180. if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
  12181. if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
  12182. //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
  12183. if (central_node_hole && !hole_rect.IsInverted())
  12184. {
  12185. SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
  12186. SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
  12187. }
  12188. }
  12189. // Update position/size, process and draw resizing splitters
  12190. if (node->IsRootNode() && host_window)
  12191. {
  12192. DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
  12193. DockNodeTreeUpdateSplitter(node);
  12194. }
  12195. // Draw empty node background (currently can only be the Central Node)
  12196. if (host_window && node->IsEmpty() && node->IsVisible && !(node_flags & ImGuiDockNodeFlags_PassthruCentralNode))
  12197. host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_DockingEmptyBg));
  12198. // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
  12199. if (render_dockspace_bg && node->IsVisible)
  12200. {
  12201. host_window->DrawList->ChannelsSetCurrent(0);
  12202. if (central_node_hole)
  12203. RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
  12204. else
  12205. host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
  12206. host_window->DrawList->ChannelsMerge();
  12207. }
  12208. // Draw and populate Tab Bar
  12209. if (host_window && node->Windows.Size > 0)
  12210. {
  12211. DockNodeUpdateTabBar(node, host_window);
  12212. }
  12213. else
  12214. {
  12215. node->WantCloseAll = false;
  12216. node->WantCloseTabId = 0;
  12217. node->IsFocused = false;
  12218. }
  12219. if (node->TabBar && node->TabBar->SelectedTabId)
  12220. node->SelectedTabId = node->TabBar->SelectedTabId;
  12221. else if (node->Windows.Size > 0)
  12222. node->SelectedTabId = node->Windows[0]->ID;
  12223. // Draw payload drop target
  12224. if (host_window && node->IsVisible)
  12225. if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
  12226. BeginDockableDragDropTarget(host_window);
  12227. // We update this after DockNodeUpdateTabBar()
  12228. node->LastFrameActive = g.FrameCount;
  12229. // Recurse into children
  12230. // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
  12231. if (host_window)
  12232. {
  12233. if (node->ChildNodes[0])
  12234. DockNodeUpdate(node->ChildNodes[0]);
  12235. if (node->ChildNodes[1])
  12236. DockNodeUpdate(node->ChildNodes[1]);
  12237. // Render outer borders last (after the tab bar)
  12238. if (node->IsRootNode())
  12239. RenderWindowOuterBorders(host_window);
  12240. }
  12241. // End host window
  12242. if (beginned_into_host_window) //-V1020
  12243. End();
  12244. }
  12245. // Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
  12246. static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
  12247. {
  12248. ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
  12249. ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
  12250. if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
  12251. return d;
  12252. return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
  12253. }
  12254. static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
  12255. {
  12256. // Try to position the menu so it is more likely to stays within the same viewport
  12257. ImGuiContext& g = *GImGui;
  12258. ImGuiID ret_tab_id = 0;
  12259. if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
  12260. SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
  12261. else
  12262. SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
  12263. if (BeginPopup("#WindowMenu"))
  12264. {
  12265. node->IsFocused = true;
  12266. if (tab_bar->Tabs.Size == 1)
  12267. {
  12268. if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar()))
  12269. node->WantHiddenTabBarToggle = true;
  12270. }
  12271. else
  12272. {
  12273. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
  12274. {
  12275. ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  12276. if (tab->Flags & ImGuiTabItemFlags_Button)
  12277. continue;
  12278. if (Selectable(tab_bar->GetTabName(tab), tab->ID == tab_bar->SelectedTabId))
  12279. ret_tab_id = tab->ID;
  12280. SameLine();
  12281. Text(" ");
  12282. }
  12283. }
  12284. EndPopup();
  12285. }
  12286. return ret_tab_id;
  12287. }
  12288. // User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
  12289. bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
  12290. {
  12291. if (node->TabBar == NULL || node->HostWindow == NULL)
  12292. return false;
  12293. if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
  12294. return false;
  12295. Begin(node->HostWindow->Name);
  12296. PushOverrideID(node->ID);
  12297. bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
  12298. IM_UNUSED(ret);
  12299. IM_ASSERT(ret);
  12300. return true;
  12301. }
  12302. void ImGui::DockNodeEndAmendTabBar()
  12303. {
  12304. EndTabBar();
  12305. PopID();
  12306. End();
  12307. }
  12308. // Submit the tab bar corresponding to a dock node and various housekeeping details.
  12309. static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
  12310. {
  12311. ImGuiContext& g = *GImGui;
  12312. ImGuiStyle& style = g.Style;
  12313. const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
  12314. const bool closed_all = node->WantCloseAll && node_was_active;
  12315. const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
  12316. node->WantCloseAll = false;
  12317. node->WantCloseTabId = 0;
  12318. // Decide if we should use a focused title bar color
  12319. bool is_focused = false;
  12320. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  12321. if (g.NavWindowingTarget)
  12322. is_focused = (g.NavWindowingTarget->DockNode == node);
  12323. else if (g.NavWindow && g.NavWindow->RootWindowForTitleBarHighlight == host_window->RootWindowDockTree && root_node->LastFocusedNodeId == node->ID)
  12324. is_focused = true;
  12325. // Hidden tab bar will show a triangle on the upper-left (in Begin)
  12326. if (node->IsHiddenTabBar() || node->IsNoTabBar())
  12327. {
  12328. node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
  12329. node->IsFocused = is_focused;
  12330. if (is_focused)
  12331. node->LastFrameFocused = g.FrameCount;
  12332. if (node->VisibleWindow)
  12333. {
  12334. // Notify root of visible window (used to display title in OS task bar)
  12335. if (is_focused || root_node->VisibleWindow == NULL)
  12336. root_node->VisibleWindow = node->VisibleWindow;
  12337. if (node->TabBar)
  12338. node->TabBar->VisibleTabId = node->VisibleWindow->ID;
  12339. }
  12340. return;
  12341. }
  12342. // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
  12343. bool backup_skip_item = host_window->SkipItems;
  12344. if (!node->IsDockSpace())
  12345. {
  12346. host_window->SkipItems = false;
  12347. host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  12348. }
  12349. // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
  12350. // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
  12351. // as docked windows themselves will override the stack with their own root ID.
  12352. PushOverrideID(node->ID);
  12353. ImGuiTabBar* tab_bar = node->TabBar;
  12354. bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
  12355. if (tab_bar == NULL)
  12356. {
  12357. DockNodeAddTabBar(node);
  12358. tab_bar = node->TabBar;
  12359. }
  12360. ImGuiID focus_tab_id = 0;
  12361. node->IsFocused = is_focused;
  12362. const ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
  12363. const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
  12364. // In a dock node, the Collapse Button turns into the Window Menu button.
  12365. // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
  12366. if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
  12367. {
  12368. if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar))
  12369. focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
  12370. is_focused |= node->IsFocused;
  12371. }
  12372. // Layout
  12373. ImRect title_bar_rect, tab_bar_rect;
  12374. ImVec2 window_menu_button_pos;
  12375. ImVec2 close_button_pos;
  12376. DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
  12377. // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
  12378. const int tabs_count_old = tab_bar->Tabs.Size;
  12379. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  12380. {
  12381. ImGuiWindow* window = node->Windows[window_n];
  12382. if (TabBarFindTabByID(tab_bar, window->ID) == NULL)
  12383. TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
  12384. }
  12385. // Title bar
  12386. if (is_focused)
  12387. node->LastFrameFocused = g.FrameCount;
  12388. ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  12389. host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, ImDrawFlags_RoundCornersTop);
  12390. // Docking/Collapse button
  12391. if (has_window_menu_button)
  12392. {
  12393. if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
  12394. OpenPopup("#WindowMenu");
  12395. if (IsItemActive())
  12396. focus_tab_id = tab_bar->SelectedTabId;
  12397. }
  12398. // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
  12399. int tabs_unsorted_start = tab_bar->Tabs.Size;
  12400. for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
  12401. {
  12402. // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
  12403. tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
  12404. tabs_unsorted_start = tab_n;
  12405. }
  12406. if (tab_bar->Tabs.Size > tabs_unsorted_start)
  12407. {
  12408. IMGUI_DEBUG_LOG_DOCKING("In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
  12409. for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
  12410. IMGUI_DEBUG_LOG_DOCKING(" - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
  12411. if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
  12412. ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
  12413. }
  12414. // Apply NavWindow focus back to the tab bar
  12415. if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
  12416. tab_bar->SelectedTabId = g.NavWindow->RootWindow->ID;
  12417. // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
  12418. if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
  12419. tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
  12420. else if (tab_bar->Tabs.Size > tabs_count_old)
  12421. tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->ID;
  12422. // Begin tab bar
  12423. ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
  12424. tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
  12425. if (!host_window->Collapsed && is_focused)
  12426. tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
  12427. BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
  12428. //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
  12429. // Backup style colors
  12430. ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
  12431. for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
  12432. backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
  12433. // Submit actual tabs
  12434. node->VisibleWindow = NULL;
  12435. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  12436. {
  12437. ImGuiWindow* window = node->Windows[window_n];
  12438. if ((closed_all || closed_one == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
  12439. continue;
  12440. if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
  12441. {
  12442. ImGuiTabItemFlags tab_item_flags = 0;
  12443. tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
  12444. if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
  12445. tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
  12446. if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
  12447. tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
  12448. // Apply stored style overrides for the window
  12449. for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
  12450. g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
  12451. bool tab_open = true;
  12452. TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
  12453. if (!tab_open)
  12454. node->WantCloseTabId = window->ID;
  12455. if (tab_bar->VisibleTabId == window->ID)
  12456. node->VisibleWindow = window;
  12457. // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
  12458. window->DockTabItemStatusFlags = host_window->DC.LastItemStatusFlags;
  12459. window->DockTabItemRect = host_window->DC.LastItemRect;
  12460. // Update navigation ID on menu layer
  12461. if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
  12462. host_window->NavLastIds[1] = window->ID;
  12463. }
  12464. }
  12465. // Restore style colors
  12466. for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
  12467. g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
  12468. // Notify root of visible window (used to display title in OS task bar)
  12469. if (node->VisibleWindow)
  12470. if (is_focused || root_node->VisibleWindow == NULL)
  12471. root_node->VisibleWindow = node->VisibleWindow;
  12472. // Close button (after VisibleWindow was updated)
  12473. // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->ID may be != from tab_bar->SelectedTabId
  12474. const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
  12475. const bool close_button_is_visible = node->HasCloseButton;
  12476. //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
  12477. if (close_button_is_visible)
  12478. {
  12479. if (!close_button_is_enabled)
  12480. {
  12481. PushItemFlag(ImGuiItemFlags_Disabled, true);
  12482. PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
  12483. }
  12484. if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
  12485. if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->VisibleTabId))
  12486. {
  12487. node->WantCloseTabId = tab->ID;
  12488. TabBarCloseTab(tab_bar, tab);
  12489. }
  12490. //if (IsItemActive())
  12491. // focus_tab_id = tab_bar->SelectedTabId;
  12492. if (!close_button_is_enabled)
  12493. {
  12494. PopStyleColor();
  12495. PopItemFlag();
  12496. }
  12497. }
  12498. // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
  12499. // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
  12500. ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
  12501. if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
  12502. {
  12503. bool held;
  12504. ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
  12505. if (g.HoveredId == title_bar_id)
  12506. {
  12507. // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
  12508. // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
  12509. host_window->DC.LastItemId = title_bar_id;
  12510. SetItemAllowOverlap();
  12511. }
  12512. if (held)
  12513. {
  12514. if (IsMouseClicked(0))
  12515. focus_tab_id = tab_bar->SelectedTabId;
  12516. // Forward moving request to selected window
  12517. if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
  12518. StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
  12519. }
  12520. }
  12521. // Forward focus from host node to selected window
  12522. //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
  12523. // focus_tab_id = tab_bar->SelectedTabId;
  12524. // When clicked on a tab we requested focus to the docked child
  12525. // This overrides the value set by "forward focus from host node to selected window".
  12526. if (tab_bar->NextSelectedTabId)
  12527. focus_tab_id = tab_bar->NextSelectedTabId;
  12528. // Apply navigation focus
  12529. if (focus_tab_id != 0)
  12530. if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
  12531. if (tab->Window)
  12532. {
  12533. FocusWindow(tab->Window);
  12534. NavInitWindow(tab->Window, false);
  12535. }
  12536. EndTabBar();
  12537. PopID();
  12538. // Restore SkipItems flag
  12539. if (!node->IsDockSpace())
  12540. {
  12541. host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  12542. host_window->SkipItems = backup_skip_item;
  12543. }
  12544. }
  12545. static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
  12546. {
  12547. IM_ASSERT(node->TabBar == NULL);
  12548. node->TabBar = IM_NEW(ImGuiTabBar);
  12549. }
  12550. static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
  12551. {
  12552. if (node->TabBar == NULL)
  12553. return;
  12554. IM_DELETE(node->TabBar);
  12555. node->TabBar = NULL;
  12556. }
  12557. static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
  12558. {
  12559. if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
  12560. return false;
  12561. ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
  12562. ImGuiWindowClass* payload_class = &payload->WindowClass;
  12563. if (host_class->ClassId != payload_class->ClassId)
  12564. {
  12565. if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
  12566. return true;
  12567. if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
  12568. return true;
  12569. return false;
  12570. }
  12571. return true;
  12572. }
  12573. static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
  12574. {
  12575. if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode())
  12576. return true;
  12577. const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
  12578. for (int payload_n = 0; payload_n < payload_count; payload_n++)
  12579. {
  12580. ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
  12581. if (DockNodeIsDropAllowedOne(payload, host_window))
  12582. return true;
  12583. }
  12584. return false;
  12585. }
  12586. // window menu button == collapse button when not in a dock node.
  12587. // FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
  12588. static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
  12589. {
  12590. ImGuiContext& g = *GImGui;
  12591. ImGuiStyle& style = g.Style;
  12592. ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
  12593. if (out_title_rect) { *out_title_rect = r; }
  12594. r.Min.x += style.WindowBorderSize;
  12595. r.Max.x -= style.WindowBorderSize;
  12596. float button_sz = g.FontSize;
  12597. ImVec2 window_menu_button_pos = r.Min;
  12598. r.Min.x += style.FramePadding.x;
  12599. r.Max.x -= style.FramePadding.x;
  12600. if (node->HasCloseButton)
  12601. {
  12602. r.Max.x -= button_sz;
  12603. if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
  12604. }
  12605. if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
  12606. {
  12607. r.Min.x += button_sz + style.ItemInnerSpacing.x;
  12608. }
  12609. else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
  12610. {
  12611. r.Max.x -= button_sz + style.FramePadding.x;
  12612. window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
  12613. }
  12614. if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
  12615. if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
  12616. }
  12617. void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
  12618. {
  12619. ImGuiContext& g = *GImGui;
  12620. const float dock_spacing = g.Style.ItemInnerSpacing.x;
  12621. const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  12622. pos_new[axis ^ 1] = pos_old[axis ^ 1];
  12623. size_new[axis ^ 1] = size_old[axis ^ 1];
  12624. // Distribute size on given axis (with a desired size or equally)
  12625. const float w_avail = size_old[axis] - dock_spacing;
  12626. if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
  12627. {
  12628. size_new[axis] = size_new_desired[axis];
  12629. size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
  12630. }
  12631. else
  12632. {
  12633. size_new[axis] = IM_FLOOR(w_avail * 0.5f);
  12634. size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
  12635. }
  12636. // Position each node
  12637. if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
  12638. {
  12639. pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
  12640. }
  12641. else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
  12642. {
  12643. pos_new[axis] = pos_old[axis];
  12644. pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
  12645. }
  12646. }
  12647. // Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
  12648. bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
  12649. {
  12650. ImGuiContext& g = *GImGui;
  12651. const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
  12652. const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
  12653. float hs_w; // Half-size, longer axis
  12654. float hs_h; // Half-size, smaller axis
  12655. ImVec2 off; // Distance from edge or center
  12656. if (outer_docking)
  12657. {
  12658. //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
  12659. //hs_h = ImFloor(hs_w * 0.15f);
  12660. //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
  12661. hs_w = ImFloor(hs_for_central_nodes * 1.50f);
  12662. hs_h = ImFloor(hs_for_central_nodes * 0.80f);
  12663. off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
  12664. }
  12665. else
  12666. {
  12667. hs_w = ImFloor(hs_for_central_nodes);
  12668. hs_h = ImFloor(hs_for_central_nodes * 0.90f);
  12669. off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
  12670. }
  12671. ImVec2 c = ImFloor(parent.GetCenter());
  12672. if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
  12673. else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
  12674. else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
  12675. else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
  12676. else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
  12677. if (test_mouse_pos == NULL)
  12678. return false;
  12679. ImRect hit_r = out_r;
  12680. if (!outer_docking)
  12681. {
  12682. // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
  12683. hit_r.Expand(ImFloor(hs_w * 0.30f));
  12684. ImVec2 mouse_delta = (*test_mouse_pos - c);
  12685. float mouse_delta_len2 = ImLengthSqr(mouse_delta);
  12686. float r_threshold_center = hs_w * 1.4f;
  12687. float r_threshold_sides = hs_w * (1.4f + 1.2f);
  12688. if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
  12689. return (dir == ImGuiDir_None);
  12690. if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
  12691. return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
  12692. }
  12693. return hit_r.Contains(*test_mouse_pos);
  12694. }
  12695. // host_node may be NULL if the window doesn't have a DockNode already.
  12696. // FIXME-DOCK: This is misnamed since it's also doing the filtering.
  12697. static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
  12698. {
  12699. ImGuiContext& g = *GImGui;
  12700. // There is an edge case when docking into a dockspace which only has inactive nodes.
  12701. // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
  12702. // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
  12703. ImGuiDockNode* root_payload_as_host = root_payload->DockNodeAsHost;
  12704. ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
  12705. if (ref_node_for_rect)
  12706. IM_ASSERT(ref_node_for_rect->IsVisible);
  12707. // Filter, figure out where we are allowed to dock
  12708. ImGuiDockNodeFlags src_node_flags = root_payload_as_host ? root_payload_as_host->GetMergedFlags() : root_payload->WindowClass.DockNodeFlagsOverrideSet;
  12709. ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->GetMergedFlags() : host_window->WindowClass.DockNodeFlagsOverrideSet;
  12710. data->IsCenterAvailable = true;
  12711. if (is_outer_docking)
  12712. data->IsCenterAvailable = false;
  12713. else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
  12714. data->IsCenterAvailable = false;
  12715. else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
  12716. data->IsCenterAvailable = false;
  12717. else if ((!host_node || !host_node->IsEmpty()) && root_payload_as_host && root_payload_as_host->IsSplitNode() && (root_payload_as_host->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
  12718. data->IsCenterAvailable = false;
  12719. else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther))
  12720. data->IsCenterAvailable = false;
  12721. data->IsSidesAvailable = true;
  12722. if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
  12723. data->IsSidesAvailable = false;
  12724. else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
  12725. data->IsSidesAvailable = false;
  12726. else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
  12727. data->IsSidesAvailable = false;
  12728. // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
  12729. data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton);
  12730. data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
  12731. data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
  12732. data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
  12733. // Calculate drop shapes geometry for allowed splitting directions
  12734. IM_ASSERT(ImGuiDir_None == -1);
  12735. data->SplitNode = host_node;
  12736. data->SplitDir = ImGuiDir_None;
  12737. data->IsSplitDirExplicit = false;
  12738. if (!host_window->Collapsed)
  12739. for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
  12740. {
  12741. if (dir == ImGuiDir_None && !data->IsCenterAvailable)
  12742. continue;
  12743. if (dir != ImGuiDir_None && !data->IsSidesAvailable)
  12744. continue;
  12745. if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
  12746. {
  12747. data->SplitDir = (ImGuiDir)dir;
  12748. data->IsSplitDirExplicit = true;
  12749. }
  12750. }
  12751. // We only allow and preview docking when hovering over a drop rect or over the title bar
  12752. data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
  12753. if (!is_explicit_target && !data->IsSplitDirExplicit)
  12754. data->IsDropAllowed = false;
  12755. // Calculate split area
  12756. data->SplitRatio = 0.0f;
  12757. if (data->SplitDir != ImGuiDir_None)
  12758. {
  12759. ImGuiDir split_dir = data->SplitDir;
  12760. ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  12761. ImVec2 pos_new, pos_old = data->FutureNode.Pos;
  12762. ImVec2 size_new, size_old = data->FutureNode.Size;
  12763. DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, root_payload->Size);
  12764. // Calculate split ratio so we can pass it down the docking request
  12765. float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
  12766. data->FutureNode.Pos = pos_new;
  12767. data->FutureNode.Size = size_new;
  12768. data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
  12769. }
  12770. }
  12771. static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
  12772. {
  12773. ImGuiContext& g = *GImGui;
  12774. IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
  12775. // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
  12776. // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
  12777. const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
  12778. // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
  12779. int overlay_draw_lists_count = 0;
  12780. ImDrawList* overlay_draw_lists[2];
  12781. overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
  12782. if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
  12783. overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
  12784. // Draw main preview rectangle
  12785. const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
  12786. const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
  12787. const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
  12788. const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
  12789. // Display area preview
  12790. const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
  12791. if (data->IsDropAllowed)
  12792. {
  12793. ImRect overlay_rect = data->FutureNode.Rect();
  12794. if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
  12795. overlay_rect.Min.y += GetFrameHeight();
  12796. if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
  12797. for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
  12798. overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding);
  12799. }
  12800. // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
  12801. if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
  12802. {
  12803. // Compute target tab bar geometry so we can locate our preview tabs
  12804. ImRect tab_bar_rect;
  12805. DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
  12806. ImVec2 tab_pos = tab_bar_rect.Min;
  12807. if (host_node && host_node->TabBar)
  12808. {
  12809. if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
  12810. tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
  12811. else
  12812. tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x;
  12813. }
  12814. else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
  12815. {
  12816. tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window->Name, host_window->HasCloseButton).x; // Account for slight offset which will be added when changing from title bar to tab bar
  12817. }
  12818. // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
  12819. if (root_payload->DockNodeAsHost)
  12820. IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
  12821. ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
  12822. const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
  12823. for (int payload_n = 0; payload_n < payload_count; payload_n++)
  12824. {
  12825. // DockNode's TabBar may have non-window Tabs manually appended by user
  12826. ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
  12827. if (tab_bar_with_payload && payload_window == NULL)
  12828. continue;
  12829. if (!DockNodeIsDropAllowedOne(payload_window, host_window))
  12830. continue;
  12831. // Calculate the tab bounding box for each payload window
  12832. ImVec2 tab_size = TabItemCalcSize(payload_window->Name, payload_window->HasCloseButton);
  12833. ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
  12834. tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
  12835. const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
  12836. const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
  12837. PushStyleColor(ImGuiCol_Text, overlay_col_text);
  12838. for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
  12839. {
  12840. ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
  12841. if (!tab_bar_rect.Contains(tab_bb))
  12842. overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
  12843. TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
  12844. TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
  12845. if (!tab_bar_rect.Contains(tab_bb))
  12846. overlay_draw_lists[overlay_n]->PopClipRect();
  12847. }
  12848. PopStyleColor();
  12849. }
  12850. }
  12851. // Display drop boxes
  12852. const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
  12853. for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
  12854. {
  12855. if (!data->DropRectsDraw[dir + 1].IsInverted())
  12856. {
  12857. ImRect draw_r = data->DropRectsDraw[dir + 1];
  12858. ImRect draw_r_in = draw_r;
  12859. draw_r_in.Expand(-2.0f);
  12860. ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
  12861. for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
  12862. {
  12863. ImVec2 center = ImFloor(draw_r_in.GetCenter());
  12864. overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
  12865. overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
  12866. if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
  12867. overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
  12868. if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
  12869. overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
  12870. }
  12871. }
  12872. // Stop after ImGuiDir_None
  12873. if ((host_node && (host_node->GetMergedFlags() & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
  12874. return;
  12875. }
  12876. }
  12877. //-----------------------------------------------------------------------------
  12878. // Docking: ImGuiDockNode Tree manipulation functions
  12879. //-----------------------------------------------------------------------------
  12880. // - DockNodeTreeSplit()
  12881. // - DockNodeTreeMerge()
  12882. // - DockNodeTreeUpdatePosSize()
  12883. // - DockNodeTreeUpdateSplitterFindTouchingNode()
  12884. // - DockNodeTreeUpdateSplitter()
  12885. // - DockNodeTreeFindFallbackLeafNode()
  12886. // - DockNodeTreeFindNodeByPos()
  12887. //-----------------------------------------------------------------------------
  12888. void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
  12889. {
  12890. ImGuiContext& g = *GImGui;
  12891. IM_ASSERT(split_axis != ImGuiAxis_None);
  12892. ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
  12893. child_0->ParentNode = parent_node;
  12894. ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
  12895. child_1->ParentNode = parent_node;
  12896. ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
  12897. DockNodeMoveChildNodes(child_inheritor, parent_node);
  12898. parent_node->ChildNodes[0] = child_0;
  12899. parent_node->ChildNodes[1] = child_1;
  12900. parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
  12901. parent_node->SplitAxis = split_axis;
  12902. parent_node->VisibleWindow = NULL;
  12903. parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
  12904. float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
  12905. size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
  12906. IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
  12907. child_0->SizeRef = child_1->SizeRef = parent_node->Size;
  12908. child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
  12909. child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
  12910. DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
  12911. DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
  12912. DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
  12913. // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
  12914. child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
  12915. child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
  12916. child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12917. parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12918. if (child_inheritor->IsCentralNode())
  12919. DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
  12920. }
  12921. void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
  12922. {
  12923. // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
  12924. ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
  12925. ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
  12926. IM_ASSERT(child_0 || child_1);
  12927. IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
  12928. if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
  12929. {
  12930. IM_ASSERT(parent_node->TabBar == NULL);
  12931. IM_ASSERT(parent_node->Windows.Size == 0);
  12932. }
  12933. IMGUI_DEBUG_LOG_DOCKING("DockNodeTreeMerge 0x%08X & 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
  12934. ImVec2 backup_last_explicit_size = parent_node->SizeRef;
  12935. DockNodeMoveChildNodes(parent_node, merge_lead_child);
  12936. if (child_0)
  12937. {
  12938. DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
  12939. DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
  12940. }
  12941. if (child_1)
  12942. {
  12943. DockNodeMoveWindows(parent_node, child_1);
  12944. DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
  12945. }
  12946. DockNodeApplyPosSizeToWindows(parent_node);
  12947. parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
  12948. parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
  12949. parent_node->SizeRef = backup_last_explicit_size;
  12950. // Flags transfer
  12951. parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
  12952. parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12953. parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12954. if (child_0)
  12955. {
  12956. ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
  12957. IM_DELETE(child_0);
  12958. }
  12959. if (child_1)
  12960. {
  12961. ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
  12962. IM_DELETE(child_1);
  12963. }
  12964. }
  12965. // Update Pos/Size for a node hierarchy (don't affect child Windows yet)
  12966. void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes)
  12967. {
  12968. // During the regular dock node update we write to all nodes.
  12969. // 'only_write_to_marked_nodes' is only set when turning a node visible mid-frame and we need its size right-away.
  12970. const bool write_to_node = (only_write_to_marked_nodes == false) || (node->MarkedForPosSizeWrite);
  12971. if (write_to_node)
  12972. {
  12973. node->Pos = pos;
  12974. node->Size = size;
  12975. }
  12976. if (node->IsLeafNode())
  12977. return;
  12978. ImGuiDockNode* child_0 = node->ChildNodes[0];
  12979. ImGuiDockNode* child_1 = node->ChildNodes[1];
  12980. ImVec2 child_0_pos = pos, child_1_pos = pos;
  12981. ImVec2 child_0_size = size, child_1_size = size;
  12982. if (child_0->IsVisible && child_1->IsVisible)
  12983. {
  12984. const float spacing = DOCKING_SPLITTER_SIZE;
  12985. const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
  12986. const float size_avail = ImMax(size[axis] - spacing, 0.0f);
  12987. // Size allocation policy
  12988. // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
  12989. ImGuiContext& g = *GImGui;
  12990. const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
  12991. // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
  12992. if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
  12993. {
  12994. child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
  12995. child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
  12996. IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
  12997. }
  12998. else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
  12999. {
  13000. child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
  13001. child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
  13002. IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
  13003. }
  13004. else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
  13005. {
  13006. // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
  13007. // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
  13008. float ratio_0 = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
  13009. child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * ratio_0);
  13010. child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
  13011. IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
  13012. }
  13013. // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
  13014. else if (child_1->IsCentralNode() && child_0->SizeRef[axis] != 0.0f)
  13015. {
  13016. child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
  13017. child_1_size[axis] = (size_avail - child_0_size[axis]);
  13018. }
  13019. else if (child_0->IsCentralNode() && child_1->SizeRef[axis] != 0.0f)
  13020. {
  13021. child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
  13022. child_0_size[axis] = (size_avail - child_1_size[axis]);
  13023. }
  13024. else
  13025. {
  13026. // 4) Otherwise distribute according to the relative ratio of each SizeRef value
  13027. float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
  13028. child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5F));
  13029. child_1_size[axis] = (size_avail - child_0_size[axis]);
  13030. }
  13031. child_1_pos[axis] += spacing + child_0_size[axis];
  13032. }
  13033. child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
  13034. if (child_0->IsVisible)
  13035. DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
  13036. if (child_1->IsVisible)
  13037. DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
  13038. }
  13039. static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
  13040. {
  13041. if (node->IsLeafNode())
  13042. {
  13043. touching_nodes->push_back(node);
  13044. return;
  13045. }
  13046. if (node->ChildNodes[0]->IsVisible)
  13047. if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
  13048. DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
  13049. if (node->ChildNodes[1]->IsVisible)
  13050. if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
  13051. DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
  13052. }
  13053. void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
  13054. {
  13055. if (node->IsLeafNode())
  13056. return;
  13057. ImGuiContext& g = *GImGui;
  13058. ImGuiDockNode* child_0 = node->ChildNodes[0];
  13059. ImGuiDockNode* child_1 = node->ChildNodes[1];
  13060. if (child_0->IsVisible && child_1->IsVisible)
  13061. {
  13062. // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
  13063. const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
  13064. IM_ASSERT(axis != ImGuiAxis_None);
  13065. ImRect bb;
  13066. bb.Min = child_0->Pos;
  13067. bb.Max = child_1->Pos;
  13068. bb.Min[axis] += child_0->Size[axis];
  13069. bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
  13070. //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
  13071. const ImGuiDockNodeFlags merged_flags = child_0->GetMergedFlags() | child_1->GetMergedFlags();
  13072. const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
  13073. if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
  13074. {
  13075. ImGuiWindow* window = g.CurrentWindow;
  13076. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
  13077. }
  13078. else
  13079. {
  13080. //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
  13081. //bb.Max[axis] -= 1;
  13082. PushID(node->ID);
  13083. // Gather list of nodes that are touching the splitter line. Find resizing limits based on those nodes.
  13084. ImVector<ImGuiDockNode*> touching_nodes[2];
  13085. float min_size = g.Style.WindowMinSize[axis];
  13086. float resize_limits[2];
  13087. resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
  13088. resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
  13089. ImGuiID splitter_id = GetID("##Splitter");
  13090. if (g.ActiveId == splitter_id)
  13091. {
  13092. // Only process when splitter is active
  13093. DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
  13094. DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
  13095. for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
  13096. resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
  13097. for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
  13098. resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
  13099. /*
  13100. // [DEBUG] Render limits
  13101. ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
  13102. for (int n = 0; n < 2; n++)
  13103. if (axis == ImGuiAxis_X)
  13104. draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
  13105. else
  13106. draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
  13107. */
  13108. }
  13109. // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
  13110. float cur_size_0 = child_0->Size[axis];
  13111. float cur_size_1 = child_1->Size[axis];
  13112. float min_size_0 = resize_limits[0] - child_0->Pos[axis];
  13113. float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
  13114. if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER))
  13115. {
  13116. if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
  13117. {
  13118. child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
  13119. child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
  13120. child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
  13121. // Lock the size of every node that is a sibling of the node we are touching
  13122. // This might be less desirable if we can merge sibling of a same axis into the same parental level.
  13123. for (int side_n = 0; side_n < 2; side_n++)
  13124. for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
  13125. {
  13126. ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
  13127. //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
  13128. //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
  13129. while (touching_node->ParentNode != node)
  13130. {
  13131. if (touching_node->ParentNode->SplitAxis == axis)
  13132. {
  13133. // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
  13134. ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
  13135. node_to_preserve->WantLockSizeOnce = true;
  13136. //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
  13137. //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
  13138. }
  13139. touching_node = touching_node->ParentNode;
  13140. }
  13141. }
  13142. DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
  13143. DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
  13144. MarkIniSettingsDirty();
  13145. }
  13146. }
  13147. PopID();
  13148. }
  13149. }
  13150. if (child_0->IsVisible)
  13151. DockNodeTreeUpdateSplitter(child_0);
  13152. if (child_1->IsVisible)
  13153. DockNodeTreeUpdateSplitter(child_1);
  13154. }
  13155. ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
  13156. {
  13157. if (node->IsLeafNode())
  13158. return node;
  13159. if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
  13160. return leaf_node;
  13161. if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
  13162. return leaf_node;
  13163. return NULL;
  13164. }
  13165. ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
  13166. {
  13167. if (!node->IsVisible)
  13168. return NULL;
  13169. const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
  13170. ImRect r(node->Pos, node->Pos + node->Size);
  13171. r.Expand(dock_spacing * 0.5f);
  13172. bool inside = r.Contains(pos);
  13173. if (!inside)
  13174. return NULL;
  13175. if (node->IsLeafNode())
  13176. return node;
  13177. if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
  13178. return hovered_node;
  13179. if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
  13180. return hovered_node;
  13181. return NULL;
  13182. }
  13183. //-----------------------------------------------------------------------------
  13184. // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
  13185. //-----------------------------------------------------------------------------
  13186. // - SetWindowDock() [Internal]
  13187. // - DockSpace()
  13188. // - DockSpaceOverViewport()
  13189. //-----------------------------------------------------------------------------
  13190. // [Internal] Called via SetNextWindowDockID()
  13191. void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
  13192. {
  13193. // Test condition (NB: bit 0 is always true) and clear flags for next time
  13194. if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
  13195. return;
  13196. window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  13197. if (window->DockId == dock_id)
  13198. return;
  13199. // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
  13200. ImGuiContext* ctx = GImGui;
  13201. if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
  13202. if (new_node->IsSplitNode())
  13203. {
  13204. // Policy: Find central node or latest focused node. We first move back to our root node.
  13205. new_node = DockNodeGetRootNode(new_node);
  13206. if (new_node->CentralNode)
  13207. {
  13208. IM_ASSERT(new_node->CentralNode->IsCentralNode());
  13209. dock_id = new_node->CentralNode->ID;
  13210. }
  13211. else
  13212. {
  13213. dock_id = new_node->LastFocusedNodeId;
  13214. }
  13215. }
  13216. if (window->DockId == dock_id)
  13217. return;
  13218. if (window->DockNode)
  13219. DockNodeRemoveWindow(window->DockNode, window, 0);
  13220. window->DockId = dock_id;
  13221. }
  13222. // Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
  13223. // The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
  13224. // DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
  13225. ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
  13226. {
  13227. ImGuiContext* ctx = GImGui;
  13228. ImGuiContext& g = *ctx;
  13229. ImGuiWindow* window = GetCurrentWindow();
  13230. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  13231. return 0;
  13232. // Early out if parent window is hidden/collapsed
  13233. // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
  13234. // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
  13235. if (window->SkipItems)
  13236. flags |= ImGuiDockNodeFlags_KeepAliveOnly;
  13237. IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
  13238. IM_ASSERT(id != 0);
  13239. ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
  13240. if (!node)
  13241. {
  13242. IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X created\n", id);
  13243. node = DockContextAddNode(ctx, id);
  13244. node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  13245. }
  13246. if (window_class && window_class->ClassId != node->WindowClass.ClassId)
  13247. IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
  13248. node->SharedFlags = flags;
  13249. node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
  13250. // When a DockSpace transitioned form implicit to explicit this may be called a second time
  13251. // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
  13252. if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
  13253. {
  13254. IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
  13255. node->LocalFlags |= ImGuiDockNodeFlags_DockSpace;
  13256. return id;
  13257. }
  13258. node->LocalFlags |= ImGuiDockNodeFlags_DockSpace;
  13259. // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
  13260. if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
  13261. {
  13262. node->LastFrameAlive = g.FrameCount;
  13263. return id;
  13264. }
  13265. const ImVec2 content_avail = GetContentRegionAvail();
  13266. ImVec2 size = ImFloor(size_arg);
  13267. if (size.x <= 0.0f)
  13268. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  13269. if (size.y <= 0.0f)
  13270. size.y = ImMax(content_avail.y + size.y, 4.0f);
  13271. IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
  13272. node->Pos = window->DC.CursorPos;
  13273. node->Size = node->SizeRef = size;
  13274. SetNextWindowPos(node->Pos);
  13275. SetNextWindowSize(node->Size);
  13276. g.NextWindowData.PosUndock = false;
  13277. // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
  13278. // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
  13279. ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
  13280. window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
  13281. window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
  13282. window_flags |= ImGuiWindowFlags_NoBackground;
  13283. char title[256];
  13284. ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
  13285. PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
  13286. Begin(title, NULL, window_flags);
  13287. PopStyleVar();
  13288. ImGuiWindow* host_window = g.CurrentWindow;
  13289. host_window->DockNodeAsHost = node;
  13290. host_window->ChildId = window->GetID(title);
  13291. node->HostWindow = host_window;
  13292. node->OnlyNodeWithWindows = NULL;
  13293. IM_ASSERT(node->IsRootNode());
  13294. // We need to handle the rare case were a central node is missing.
  13295. // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
  13296. // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
  13297. // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
  13298. // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
  13299. // as it doesn't make sense for an empty dockspace to not have this property.
  13300. if (node->IsLeafNode() && !node->IsCentralNode())
  13301. node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  13302. // Update the node
  13303. DockNodeUpdate(node);
  13304. End();
  13305. ItemSize(size);
  13306. return id;
  13307. }
  13308. // Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
  13309. // The limitation with this call is that your window won't have a menu bar.
  13310. // Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
  13311. // But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
  13312. ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
  13313. {
  13314. if (viewport == NULL)
  13315. viewport = GetMainViewport();
  13316. SetNextWindowPos(viewport->WorkPos);
  13317. SetNextWindowSize(viewport->WorkSize);
  13318. SetNextWindowViewport(viewport->ID);
  13319. ImGuiWindowFlags host_window_flags = 0;
  13320. host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
  13321. host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
  13322. if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
  13323. host_window_flags |= ImGuiWindowFlags_NoBackground;
  13324. char label[32];
  13325. ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
  13326. PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  13327. PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
  13328. PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
  13329. Begin(label, NULL, host_window_flags);
  13330. PopStyleVar(3);
  13331. ImGuiID dockspace_id = GetID("DockSpace");
  13332. DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
  13333. End();
  13334. return dockspace_id;
  13335. }
  13336. //-----------------------------------------------------------------------------
  13337. // Docking: Builder Functions
  13338. //-----------------------------------------------------------------------------
  13339. // Very early end-user API to manipulate dock nodes.
  13340. // Only available in imgui_internal.h. Expect this API to change/break!
  13341. // It is expected that those functions are all called _before_ the dockspace node submission.
  13342. //-----------------------------------------------------------------------------
  13343. // - DockBuilderDockWindow()
  13344. // - DockBuilderGetNode()
  13345. // - DockBuilderSetNodePos()
  13346. // - DockBuilderSetNodeSize()
  13347. // - DockBuilderAddNode()
  13348. // - DockBuilderRemoveNode()
  13349. // - DockBuilderRemoveNodeChildNodes()
  13350. // - DockBuilderRemoveNodeDockedWindows()
  13351. // - DockBuilderSplitNode()
  13352. // - DockBuilderCopyNodeRec()
  13353. // - DockBuilderCopyNode()
  13354. // - DockBuilderCopyWindowSettings()
  13355. // - DockBuilderCopyDockSpace()
  13356. // - DockBuilderFinish()
  13357. //-----------------------------------------------------------------------------
  13358. void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
  13359. {
  13360. // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
  13361. ImGuiID window_id = ImHashStr(window_name);
  13362. if (ImGuiWindow* window = FindWindowByID(window_id))
  13363. {
  13364. // Apply to created window
  13365. SetWindowDock(window, node_id, ImGuiCond_Always);
  13366. window->DockOrder = -1;
  13367. }
  13368. else
  13369. {
  13370. // Apply to settings
  13371. ImGuiWindowSettings* settings = FindWindowSettings(window_id);
  13372. if (settings == NULL)
  13373. settings = CreateNewWindowSettings(window_name);
  13374. settings->DockId = node_id;
  13375. settings->DockOrder = -1;
  13376. }
  13377. }
  13378. ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
  13379. {
  13380. ImGuiContext* ctx = GImGui;
  13381. return DockContextFindNodeByID(ctx, node_id);
  13382. }
  13383. void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
  13384. {
  13385. ImGuiContext* ctx = GImGui;
  13386. ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
  13387. if (node == NULL)
  13388. return;
  13389. node->Pos = pos;
  13390. node->AuthorityForPos = ImGuiDataAuthority_DockNode;
  13391. }
  13392. void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
  13393. {
  13394. ImGuiContext* ctx = GImGui;
  13395. ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
  13396. if (node == NULL)
  13397. return;
  13398. IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
  13399. node->Size = node->SizeRef = size;
  13400. node->AuthorityForSize = ImGuiDataAuthority_DockNode;
  13401. }
  13402. // Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
  13403. // - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
  13404. // - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
  13405. // - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
  13406. // For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
  13407. // - Use (id == 0) to let the system allocate a node identifier.
  13408. // - Existing node with a same id will be removed.
  13409. ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
  13410. {
  13411. ImGuiContext* ctx = GImGui;
  13412. ImGuiDockNode* node = NULL;
  13413. if (id != 0)
  13414. DockBuilderRemoveNode(id);
  13415. if (flags & ImGuiDockNodeFlags_DockSpace)
  13416. {
  13417. DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
  13418. node = DockContextFindNodeByID(ctx, id);
  13419. }
  13420. else
  13421. {
  13422. node = DockContextAddNode(ctx, id);
  13423. node->LocalFlags = flags;
  13424. }
  13425. node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
  13426. return node->ID;
  13427. }
  13428. void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
  13429. {
  13430. ImGuiContext* ctx = GImGui;
  13431. ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
  13432. if (node == NULL)
  13433. return;
  13434. DockBuilderRemoveNodeDockedWindows(node_id, true);
  13435. DockBuilderRemoveNodeChildNodes(node_id);
  13436. if (node->IsCentralNode() && node->ParentNode)
  13437. node->ParentNode->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  13438. DockContextRemoveNode(ctx, node, true);
  13439. }
  13440. // root_id = 0 to remove all, root_id != 0 to remove child of given node.
  13441. void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
  13442. {
  13443. ImGuiContext* ctx = GImGui;
  13444. ImGuiDockContext* dc = &ctx->DockContext;
  13445. ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
  13446. if (root_id && root_node == NULL)
  13447. return;
  13448. bool has_central_node = false;
  13449. ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
  13450. ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
  13451. // Process active windows
  13452. ImVector<ImGuiDockNode*> nodes_to_remove;
  13453. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  13454. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  13455. {
  13456. bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
  13457. if (want_removal)
  13458. {
  13459. if (node->IsCentralNode())
  13460. has_central_node = true;
  13461. if (root_id != 0)
  13462. DockContextQueueNotifyRemovedNode(ctx, node);
  13463. if (root_node)
  13464. {
  13465. DockNodeMoveWindows(root_node, node);
  13466. DockSettingsRenameNodeReferences(node->ID, root_node->ID);
  13467. }
  13468. nodes_to_remove.push_back(node);
  13469. }
  13470. }
  13471. // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
  13472. // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
  13473. if (root_node)
  13474. {
  13475. root_node->AuthorityForPos = backup_root_node_authority_for_pos;
  13476. root_node->AuthorityForSize = backup_root_node_authority_for_size;
  13477. }
  13478. // Apply to settings
  13479. for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
  13480. if (ImGuiID window_settings_dock_id = settings->DockId)
  13481. for (int n = 0; n < nodes_to_remove.Size; n++)
  13482. if (nodes_to_remove[n]->ID == window_settings_dock_id)
  13483. {
  13484. settings->DockId = root_id;
  13485. break;
  13486. }
  13487. // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
  13488. if (nodes_to_remove.Size > 1)
  13489. ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
  13490. for (int n = 0; n < nodes_to_remove.Size; n++)
  13491. DockContextRemoveNode(ctx, nodes_to_remove[n], false);
  13492. if (root_id == 0)
  13493. {
  13494. dc->Nodes.Clear();
  13495. dc->Requests.clear();
  13496. }
  13497. else if (has_central_node)
  13498. {
  13499. root_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  13500. root_node->CentralNode = root_node;
  13501. }
  13502. }
  13503. void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
  13504. {
  13505. // Clear references in settings
  13506. ImGuiContext* ctx = GImGui;
  13507. ImGuiContext& g = *ctx;
  13508. if (clear_settings_refs)
  13509. {
  13510. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  13511. {
  13512. bool want_removal = (root_id == 0) || (settings->DockId == root_id);
  13513. if (!want_removal && settings->DockId != 0)
  13514. if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
  13515. if (DockNodeGetRootNode(node)->ID == root_id)
  13516. want_removal = true;
  13517. if (want_removal)
  13518. settings->DockId = 0;
  13519. }
  13520. }
  13521. // Clear references in windows
  13522. for (int n = 0; n < g.Windows.Size; n++)
  13523. {
  13524. ImGuiWindow* window = g.Windows[n];
  13525. bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
  13526. if (want_removal)
  13527. {
  13528. const ImGuiID backup_dock_id = window->DockId;
  13529. IM_UNUSED(backup_dock_id);
  13530. DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
  13531. if (!clear_settings_refs)
  13532. IM_ASSERT(window->DockId == backup_dock_id);
  13533. }
  13534. }
  13535. }
  13536. // If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
  13537. // Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
  13538. // FIXME-DOCK: We are not exposing nor using split_outer.
  13539. ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
  13540. {
  13541. ImGuiContext* ctx = GImGui;
  13542. IM_ASSERT(split_dir != ImGuiDir_None);
  13543. IMGUI_DEBUG_LOG_DOCKING("DockBuilderSplitNode node 0x%08X, split_dir %d\n", id, split_dir);
  13544. ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
  13545. if (node == NULL)
  13546. {
  13547. IM_ASSERT(node != NULL);
  13548. return 0;
  13549. }
  13550. IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
  13551. ImGuiDockRequest req;
  13552. req.Type = ImGuiDockRequestType_Split;
  13553. req.DockTargetWindow = NULL;
  13554. req.DockTargetNode = node;
  13555. req.DockPayload = NULL;
  13556. req.DockSplitDir = split_dir;
  13557. req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
  13558. req.DockSplitOuter = false;
  13559. DockContextProcessDock(ctx, &req);
  13560. ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
  13561. ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
  13562. if (out_id_at_dir)
  13563. *out_id_at_dir = id_at_dir;
  13564. if (out_id_at_opposite_dir)
  13565. *out_id_at_opposite_dir = id_at_opposite_dir;
  13566. return id_at_dir;
  13567. }
  13568. static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
  13569. {
  13570. ImGuiContext* ctx = GImGui;
  13571. ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx, dst_node_id_if_known);
  13572. dst_node->SharedFlags = src_node->SharedFlags;
  13573. dst_node->LocalFlags = src_node->LocalFlags;
  13574. dst_node->Pos = src_node->Pos;
  13575. dst_node->Size = src_node->Size;
  13576. dst_node->SizeRef = src_node->SizeRef;
  13577. dst_node->SplitAxis = src_node->SplitAxis;
  13578. out_node_remap_pairs->push_back(src_node->ID);
  13579. out_node_remap_pairs->push_back(dst_node->ID);
  13580. for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
  13581. if (src_node->ChildNodes[child_n])
  13582. {
  13583. dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
  13584. dst_node->ChildNodes[child_n]->ParentNode = dst_node;
  13585. }
  13586. IMGUI_DEBUG_LOG_DOCKING("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
  13587. return dst_node;
  13588. }
  13589. void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
  13590. {
  13591. ImGuiContext* ctx = GImGui;
  13592. IM_ASSERT(src_node_id != 0);
  13593. IM_ASSERT(dst_node_id != 0);
  13594. IM_ASSERT(out_node_remap_pairs != NULL);
  13595. ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
  13596. IM_ASSERT(src_node != NULL);
  13597. out_node_remap_pairs->clear();
  13598. DockBuilderRemoveNode(dst_node_id);
  13599. DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
  13600. IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
  13601. }
  13602. void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
  13603. {
  13604. ImGuiWindow* src_window = FindWindowByName(src_name);
  13605. if (src_window == NULL)
  13606. return;
  13607. if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
  13608. {
  13609. dst_window->Pos = src_window->Pos;
  13610. dst_window->Size = src_window->Size;
  13611. dst_window->SizeFull = src_window->SizeFull;
  13612. dst_window->Collapsed = src_window->Collapsed;
  13613. }
  13614. else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name))
  13615. {
  13616. ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
  13617. if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
  13618. {
  13619. dst_settings->ViewportPos = window_pos_2ih;
  13620. dst_settings->ViewportId = src_window->ViewportId;
  13621. dst_settings->Pos = ImVec2ih(0, 0);
  13622. }
  13623. else
  13624. {
  13625. dst_settings->Pos = window_pos_2ih;
  13626. }
  13627. dst_settings->Size = ImVec2ih(src_window->SizeFull);
  13628. dst_settings->Collapsed = src_window->Collapsed;
  13629. }
  13630. }
  13631. // FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
  13632. void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
  13633. {
  13634. IM_ASSERT(src_dockspace_id != 0);
  13635. IM_ASSERT(dst_dockspace_id != 0);
  13636. IM_ASSERT(in_window_remap_pairs != NULL);
  13637. IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
  13638. // Duplicate entire dock
  13639. // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
  13640. // whereas we could attempt to at least keep them together in a new, same floating node.
  13641. ImVector<ImGuiID> node_remap_pairs;
  13642. DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
  13643. // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
  13644. // (The windows associated to src_dockspace_id are staying in place)
  13645. ImVector<ImGuiID> src_windows;
  13646. for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
  13647. {
  13648. const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
  13649. const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
  13650. ImGuiID src_window_id = ImHashStr(src_window_name);
  13651. src_windows.push_back(src_window_id);
  13652. // Search in the remapping tables
  13653. ImGuiID src_dock_id = 0;
  13654. if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
  13655. src_dock_id = src_window->DockId;
  13656. else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id))
  13657. src_dock_id = src_window_settings->DockId;
  13658. ImGuiID dst_dock_id = 0;
  13659. for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
  13660. if (node_remap_pairs[dock_remap_n] == src_dock_id)
  13661. {
  13662. dst_dock_id = node_remap_pairs[dock_remap_n + 1];
  13663. //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
  13664. break;
  13665. }
  13666. if (dst_dock_id != 0)
  13667. {
  13668. // Docked windows gets redocked into the new node hierarchy.
  13669. IMGUI_DEBUG_LOG_DOCKING("Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
  13670. DockBuilderDockWindow(dst_window_name, dst_dock_id);
  13671. }
  13672. else
  13673. {
  13674. // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
  13675. // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
  13676. IMGUI_DEBUG_LOG_DOCKING("Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
  13677. DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
  13678. }
  13679. }
  13680. // Anything else in the source nodes of 'node_remap_pairs' are windows that were docked in src_dockspace_id but are not owned by it (unaffiliated windows, e.g. "ImGui Demo")
  13681. // Find those windows and move to them to the cloned dock node. This may be optional?
  13682. for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
  13683. if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
  13684. {
  13685. ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
  13686. ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
  13687. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  13688. {
  13689. ImGuiWindow* window = node->Windows[window_n];
  13690. if (src_windows.contains(window->ID))
  13691. continue;
  13692. // Docked windows gets redocked into the new node hierarchy.
  13693. IMGUI_DEBUG_LOG_DOCKING("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
  13694. DockBuilderDockWindow(window->Name, dst_dock_id);
  13695. }
  13696. }
  13697. }
  13698. void ImGui::DockBuilderFinish(ImGuiID root_id)
  13699. {
  13700. ImGuiContext* ctx = GImGui;
  13701. //DockContextRebuild(ctx);
  13702. DockContextBuildAddWindowsToNodes(ctx, root_id);
  13703. }
  13704. //-----------------------------------------------------------------------------
  13705. // Docking: Begin/End Support Functions (called from Begin/End)
  13706. //-----------------------------------------------------------------------------
  13707. // - GetWindowAlwaysWantOwnTabBar()
  13708. // - DockContextBindNodeToWindow()
  13709. // - BeginDocked()
  13710. // - BeginDockableDragDropSource()
  13711. // - BeginDockableDragDropTarget()
  13712. //-----------------------------------------------------------------------------
  13713. bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
  13714. {
  13715. ImGuiContext& g = *GImGui;
  13716. if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
  13717. if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
  13718. if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
  13719. return true;
  13720. return false;
  13721. }
  13722. static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
  13723. {
  13724. ImGuiContext& g = *ctx;
  13725. ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
  13726. IM_ASSERT(window->DockNode == NULL);
  13727. // We should not be docking into a split node (SetWindowDock should avoid this)
  13728. if (node && node->IsSplitNode())
  13729. {
  13730. DockContextProcessUndockWindow(ctx, window);
  13731. return NULL;
  13732. }
  13733. // Create node
  13734. if (node == NULL)
  13735. {
  13736. node = DockContextAddNode(ctx, window->DockId);
  13737. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
  13738. node->LastFrameAlive = g.FrameCount;
  13739. }
  13740. // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
  13741. // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
  13742. // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
  13743. // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
  13744. if (!node->IsVisible)
  13745. {
  13746. ImGuiDockNode* ancestor_node = node;
  13747. while (!ancestor_node->IsVisible)
  13748. {
  13749. ancestor_node->IsVisible = true;
  13750. ancestor_node->MarkedForPosSizeWrite = true;
  13751. if (ancestor_node->ParentNode)
  13752. ancestor_node = ancestor_node->ParentNode;
  13753. }
  13754. IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
  13755. DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, true);
  13756. }
  13757. // Add window to node
  13758. DockNodeAddWindow(node, window, true);
  13759. IM_ASSERT(node == window->DockNode);
  13760. return node;
  13761. }
  13762. void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
  13763. {
  13764. ImGuiContext* ctx = GImGui;
  13765. ImGuiContext& g = *ctx;
  13766. const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
  13767. if (auto_dock_node)
  13768. {
  13769. if (window->DockId == 0)
  13770. {
  13771. IM_ASSERT(window->DockNode == NULL);
  13772. window->DockId = DockContextGenNodeID(ctx);
  13773. }
  13774. }
  13775. else
  13776. {
  13777. // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
  13778. bool want_undock = false;
  13779. want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
  13780. want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
  13781. if (want_undock)
  13782. {
  13783. DockContextProcessUndockWindow(ctx, window);
  13784. return;
  13785. }
  13786. }
  13787. // Bind to our dock node
  13788. ImGuiDockNode* node = window->DockNode;
  13789. if (node != NULL)
  13790. IM_ASSERT(window->DockId == node->ID);
  13791. if (window->DockId != 0 && node == NULL)
  13792. {
  13793. node = DockContextBindNodeToWindow(ctx, window);
  13794. if (node == NULL)
  13795. return;
  13796. }
  13797. #if 0
  13798. // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
  13799. if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
  13800. {
  13801. DockContextProcessUndockWindow(ctx, window);
  13802. return;
  13803. }
  13804. #endif
  13805. // Undock if our dockspace node disappeared
  13806. // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
  13807. if (node->LastFrameAlive < g.FrameCount)
  13808. {
  13809. // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
  13810. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  13811. if (root_node->LastFrameAlive < g.FrameCount)
  13812. {
  13813. DockContextProcessUndockWindow(ctx, window);
  13814. }
  13815. else
  13816. {
  13817. window->DockIsActive = true;
  13818. window->DockTabIsVisible = false;
  13819. }
  13820. return;
  13821. }
  13822. // Store style overrides
  13823. for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
  13824. window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
  13825. // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
  13826. // and never create neither a host window neither a tab bar.
  13827. // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
  13828. if (node->HostWindow == NULL)
  13829. {
  13830. window->DockIsActive = (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing);
  13831. window->DockTabIsVisible = false;
  13832. if (node->Windows.Size > 1)
  13833. DockNodeHideWindowDuringHostWindowCreation(window);
  13834. return;
  13835. }
  13836. // We can have zero-sized nodes (e.g. children of a small-size dockspace)
  13837. IM_ASSERT(node->HostWindow);
  13838. IM_ASSERT(node->IsLeafNode());
  13839. IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
  13840. node->State = ImGuiDockNodeState_HostWindowVisible;
  13841. // Undock if we are submitted earlier than the host window
  13842. if (window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
  13843. {
  13844. DockContextProcessUndockWindow(ctx, window);
  13845. return;
  13846. }
  13847. // Position/Size window
  13848. SetNextWindowPos(node->Pos);
  13849. SetNextWindowSize(node->Size);
  13850. g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
  13851. window->DockIsActive = true;
  13852. window->DockTabIsVisible = false;
  13853. if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
  13854. return;
  13855. // When the window is selected we mark it as visible.
  13856. if (node->VisibleWindow == window)
  13857. window->DockTabIsVisible = true;
  13858. // Update window flag
  13859. IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
  13860. window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
  13861. if (node->IsHiddenTabBar() || node->IsNoTabBar())
  13862. window->Flags |= ImGuiWindowFlags_NoTitleBar;
  13863. else
  13864. window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
  13865. // Save new dock order only if the window has been visible once already
  13866. // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
  13867. if (node->TabBar && window->WasActive)
  13868. window->DockOrder = (short)DockNodeGetTabOrder(window);
  13869. if ((node->WantCloseAll || node->WantCloseTabId == window->ID) && p_open != NULL)
  13870. *p_open = false;
  13871. // Update ChildId to allow returning from Child to Parent with Escape
  13872. ImGuiWindow* parent_window = window->DockNode->HostWindow;
  13873. window->ChildId = parent_window->GetID(window->Name);
  13874. }
  13875. void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
  13876. {
  13877. ImGuiContext& g = *GImGui;
  13878. IM_ASSERT(g.ActiveId == window->MoveId);
  13879. IM_ASSERT(g.MovingWindow == window);
  13880. window->DC.LastItemId = window->MoveId;
  13881. window = window->RootWindowDockTree;
  13882. IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
  13883. bool is_drag_docking = ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
  13884. if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
  13885. {
  13886. SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
  13887. EndDragDropSource();
  13888. // Store style overrides
  13889. for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
  13890. window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
  13891. }
  13892. }
  13893. void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
  13894. {
  13895. ImGuiContext* ctx = GImGui;
  13896. ImGuiContext& g = *ctx;
  13897. //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
  13898. IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
  13899. if (!g.DragDropActive)
  13900. return;
  13901. //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  13902. if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
  13903. return;
  13904. // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
  13905. // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
  13906. const ImGuiPayload* payload = &g.DragDropPayload;
  13907. if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
  13908. {
  13909. EndDragDropTarget();
  13910. return;
  13911. }
  13912. ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
  13913. if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
  13914. {
  13915. // Select target node
  13916. // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
  13917. bool dock_into_floating_window = false;
  13918. ImGuiDockNode* node = NULL;
  13919. if (window->DockNodeAsHost)
  13920. {
  13921. // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
  13922. node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
  13923. // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
  13924. // In this case we need to fallback into any leaf mode, possibly the central node.
  13925. // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
  13926. if (node && node->IsDockSpace() && node->IsRootNode())
  13927. node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
  13928. }
  13929. else
  13930. {
  13931. if (window->DockNode)
  13932. node = window->DockNode;
  13933. else
  13934. dock_into_floating_window = true; // Dock into a regular window
  13935. }
  13936. const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
  13937. const bool is_explicit_target = IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
  13938. // Preview docking request and find out split direction/ratio
  13939. //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
  13940. const bool do_preview = payload->IsPreview() || payload->IsDelivery();
  13941. if (do_preview && (node != NULL || dock_into_floating_window))
  13942. {
  13943. ImGuiDockPreviewData split_inner;
  13944. ImGuiDockPreviewData split_outer;
  13945. ImGuiDockPreviewData* split_data = &split_inner;
  13946. if (node && (node->ParentNode || node->IsCentralNode()))
  13947. if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
  13948. {
  13949. DockNodePreviewDockSetup(window, root_node, payload_window, &split_outer, is_explicit_target, true);
  13950. if (split_outer.IsSplitDirExplicit)
  13951. split_data = &split_outer;
  13952. }
  13953. DockNodePreviewDockSetup(window, node, payload_window, &split_inner, is_explicit_target, false);
  13954. if (split_data == &split_outer)
  13955. split_inner.IsDropAllowed = false;
  13956. // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
  13957. DockNodePreviewDockRender(window, node, payload_window, &split_inner);
  13958. DockNodePreviewDockRender(window, node, payload_window, &split_outer);
  13959. // Queue docking request
  13960. if (split_data->IsDropAllowed && payload->IsDelivery())
  13961. DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
  13962. }
  13963. }
  13964. EndDragDropTarget();
  13965. }
  13966. //-----------------------------------------------------------------------------
  13967. // Docking: Settings
  13968. //-----------------------------------------------------------------------------
  13969. // - DockSettingsRenameNodeReferences()
  13970. // - DockSettingsRemoveNodeReferences()
  13971. // - DockSettingsFindNodeSettings()
  13972. // - DockSettingsHandler_ApplyAll()
  13973. // - DockSettingsHandler_ReadOpen()
  13974. // - DockSettingsHandler_ReadLine()
  13975. // - DockSettingsHandler_DockNodeToSettings()
  13976. // - DockSettingsHandler_WriteAll()
  13977. //-----------------------------------------------------------------------------
  13978. static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
  13979. {
  13980. ImGuiContext& g = *GImGui;
  13981. IMGUI_DEBUG_LOG_DOCKING("DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
  13982. for (int window_n = 0; window_n < g.Windows.Size; window_n++)
  13983. {
  13984. ImGuiWindow* window = g.Windows[window_n];
  13985. if (window->DockId == old_node_id && window->DockNode == NULL)
  13986. window->DockId = new_node_id;
  13987. }
  13988. //// FIXME-OPT: We could remove this loop by storing the index in the map
  13989. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  13990. if (settings->DockId == old_node_id)
  13991. settings->DockId = new_node_id;
  13992. }
  13993. // Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
  13994. static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
  13995. {
  13996. ImGuiContext& g = *GImGui;
  13997. int found = 0;
  13998. //// FIXME-OPT: We could remove this loop by storing the index in the map
  13999. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  14000. for (int node_n = 0; node_n < node_ids_count; node_n++)
  14001. if (settings->DockId == node_ids[node_n])
  14002. {
  14003. settings->DockId = 0;
  14004. settings->DockOrder = -1;
  14005. if (++found < node_ids_count)
  14006. break;
  14007. return;
  14008. }
  14009. }
  14010. static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
  14011. {
  14012. // FIXME-OPT
  14013. ImGuiDockContext* dc = &ctx->DockContext;
  14014. for (int n = 0; n < dc->NodesSettings.Size; n++)
  14015. if (dc->NodesSettings[n].ID == id)
  14016. return &dc->NodesSettings[n];
  14017. return NULL;
  14018. }
  14019. // Clear settings data
  14020. static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  14021. {
  14022. ImGuiDockContext* dc = &ctx->DockContext;
  14023. dc->NodesSettings.clear();
  14024. DockContextClearNodes(ctx, 0, true);
  14025. }
  14026. // Recreate nodes based on settings data
  14027. static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  14028. {
  14029. // Prune settings at boot time only
  14030. ImGuiDockContext* dc = &ctx->DockContext;
  14031. if (ctx->Windows.Size == 0)
  14032. DockContextPruneUnusedSettingsNodes(ctx);
  14033. DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
  14034. DockContextBuildAddWindowsToNodes(ctx, 0);
  14035. }
  14036. static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  14037. {
  14038. if (strcmp(name, "Data") != 0)
  14039. return NULL;
  14040. return (void*)1;
  14041. }
  14042. static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
  14043. {
  14044. char c = 0;
  14045. int x = 0, y = 0;
  14046. int r = 0;
  14047. // Parsing, e.g.
  14048. // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
  14049. // " DockNode ID=0x00000002 Parent=0x00000001 "
  14050. // Important: this code expect currently fields in a fixed order.
  14051. ImGuiDockNodeSettings node;
  14052. line = ImStrSkipBlank(line);
  14053. if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); }
  14054. else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
  14055. else return;
  14056. if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
  14057. if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; }
  14058. if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
  14059. if (node.ParentNodeId == 0)
  14060. {
  14061. if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
  14062. if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
  14063. }
  14064. else
  14065. {
  14066. if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
  14067. }
  14068. if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
  14069. if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
  14070. if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
  14071. if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
  14072. if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
  14073. if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
  14074. if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
  14075. if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
  14076. if (node.ParentNodeId != 0)
  14077. if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
  14078. node.Depth = parent_settings->Depth + 1;
  14079. ctx->DockContext.NodesSettings.push_back(node);
  14080. }
  14081. static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
  14082. {
  14083. ImGuiDockNodeSettings node_settings;
  14084. IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
  14085. node_settings.ID = node->ID;
  14086. node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
  14087. node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
  14088. node_settings.SelectedTabId = node->SelectedTabId;
  14089. node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
  14090. node_settings.Depth = (char)depth;
  14091. node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
  14092. node_settings.Pos = ImVec2ih(node->Pos);
  14093. node_settings.Size = ImVec2ih(node->Size);
  14094. node_settings.SizeRef = ImVec2ih(node->SizeRef);
  14095. dc->NodesSettings.push_back(node_settings);
  14096. if (node->ChildNodes[0])
  14097. DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
  14098. if (node->ChildNodes[1])
  14099. DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
  14100. }
  14101. static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  14102. {
  14103. ImGuiContext& g = *ctx;
  14104. ImGuiDockContext* dc = &ctx->DockContext;
  14105. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  14106. return;
  14107. // Gather settings data
  14108. // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
  14109. dc->NodesSettings.resize(0);
  14110. dc->NodesSettings.reserve(dc->Nodes.Data.Size);
  14111. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  14112. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  14113. if (node->IsRootNode())
  14114. DockSettingsHandler_DockNodeToSettings(dc, node, 0);
  14115. int max_depth = 0;
  14116. for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
  14117. max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
  14118. // Write to text buffer
  14119. buf->appendf("[%s][Data]\n", handler->TypeName);
  14120. for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
  14121. {
  14122. const int line_start_pos = buf->size(); (void)line_start_pos;
  14123. const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
  14124. buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file
  14125. buf->appendf(" ID=0x%08X", node_settings->ID);
  14126. if (node_settings->ParentNodeId)
  14127. {
  14128. buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
  14129. }
  14130. else
  14131. {
  14132. if (node_settings->ParentWindowId)
  14133. buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
  14134. buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
  14135. }
  14136. if (node_settings->SplitAxis != ImGuiAxis_None)
  14137. buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
  14138. if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
  14139. buf->appendf(" NoResize=1");
  14140. if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
  14141. buf->appendf(" CentralNode=1");
  14142. if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
  14143. buf->appendf(" NoTabBar=1");
  14144. if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
  14145. buf->appendf(" HiddenTabBar=1");
  14146. if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
  14147. buf->appendf(" NoWindowMenuButton=1");
  14148. if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
  14149. buf->appendf(" NoCloseButton=1");
  14150. if (node_settings->SelectedTabId)
  14151. buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
  14152. #if IMGUI_DEBUG_INI_SETTINGS
  14153. // [DEBUG] Include comments in the .ini file to ease debugging
  14154. if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
  14155. {
  14156. buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything
  14157. if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
  14158. buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
  14159. // Iterate settings so we can give info about windows that didn't exist during the session.
  14160. int contains_window = 0;
  14161. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  14162. if (settings->DockId == node_settings->ID)
  14163. {
  14164. if (contains_window++ == 0)
  14165. buf->appendf(" ; contains ");
  14166. buf->appendf("'%s' ", settings->GetName());
  14167. }
  14168. }
  14169. #endif
  14170. buf->appendf("\n");
  14171. }
  14172. buf->appendf("\n");
  14173. }
  14174. //-----------------------------------------------------------------------------
  14175. // [SECTION] PLATFORM DEPENDENT HELPERS
  14176. //-----------------------------------------------------------------------------
  14177. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
  14178. #ifdef _MSC_VER
  14179. #pragma comment(lib, "user32")
  14180. #pragma comment(lib, "kernel32")
  14181. #endif
  14182. // Win32 clipboard implementation
  14183. // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
  14184. static const char* GetClipboardTextFn_DefaultImpl(void*)
  14185. {
  14186. ImGuiContext& g = *GImGui;
  14187. g.ClipboardHandlerData.clear();
  14188. if (!::OpenClipboard(NULL))
  14189. return NULL;
  14190. HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
  14191. if (wbuf_handle == NULL)
  14192. {
  14193. ::CloseClipboard();
  14194. return NULL;
  14195. }
  14196. if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
  14197. {
  14198. int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
  14199. g.ClipboardHandlerData.resize(buf_len);
  14200. ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
  14201. }
  14202. ::GlobalUnlock(wbuf_handle);
  14203. ::CloseClipboard();
  14204. return g.ClipboardHandlerData.Data;
  14205. }
  14206. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  14207. {
  14208. if (!::OpenClipboard(NULL))
  14209. return;
  14210. const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
  14211. HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
  14212. if (wbuf_handle == NULL)
  14213. {
  14214. ::CloseClipboard();
  14215. return;
  14216. }
  14217. WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
  14218. ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
  14219. ::GlobalUnlock(wbuf_handle);
  14220. ::EmptyClipboard();
  14221. if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
  14222. ::GlobalFree(wbuf_handle);
  14223. ::CloseClipboard();
  14224. }
  14225. #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
  14226. #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
  14227. static PasteboardRef main_clipboard = 0;
  14228. // OSX clipboard implementation
  14229. // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
  14230. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  14231. {
  14232. if (!main_clipboard)
  14233. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  14234. PasteboardClear(main_clipboard);
  14235. CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
  14236. if (cf_data)
  14237. {
  14238. PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
  14239. CFRelease(cf_data);
  14240. }
  14241. }
  14242. static const char* GetClipboardTextFn_DefaultImpl(void*)
  14243. {
  14244. if (!main_clipboard)
  14245. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  14246. PasteboardSynchronize(main_clipboard);
  14247. ItemCount item_count = 0;
  14248. PasteboardGetItemCount(main_clipboard, &item_count);
  14249. for (ItemCount i = 0; i < item_count; i++)
  14250. {
  14251. PasteboardItemID item_id = 0;
  14252. PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
  14253. CFArrayRef flavor_type_array = 0;
  14254. PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
  14255. for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
  14256. {
  14257. CFDataRef cf_data;
  14258. if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
  14259. {
  14260. ImGuiContext& g = *GImGui;
  14261. g.ClipboardHandlerData.clear();
  14262. int length = (int)CFDataGetLength(cf_data);
  14263. g.ClipboardHandlerData.resize(length + 1);
  14264. CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
  14265. g.ClipboardHandlerData[length] = 0;
  14266. CFRelease(cf_data);
  14267. return g.ClipboardHandlerData.Data;
  14268. }
  14269. }
  14270. }
  14271. return NULL;
  14272. }
  14273. #else
  14274. // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
  14275. static const char* GetClipboardTextFn_DefaultImpl(void*)
  14276. {
  14277. ImGuiContext& g = *GImGui;
  14278. return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
  14279. }
  14280. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  14281. {
  14282. ImGuiContext& g = *GImGui;
  14283. g.ClipboardHandlerData.clear();
  14284. const char* text_end = text + strlen(text);
  14285. g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
  14286. memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
  14287. g.ClipboardHandlerData[(int)(text_end - text)] = 0;
  14288. }
  14289. #endif
  14290. //-----------------------------------------------------------------------------
  14291. // [SECTION] METRICS/DEBUGGER WINDOW
  14292. //-----------------------------------------------------------------------------
  14293. // - RenderViewportThumbnail() [Internal]
  14294. // - RenderViewportsThumbnails() [Internal]
  14295. // - MetricsHelpMarker() [Internal]
  14296. // - ShowMetricsWindow()
  14297. // - DebugNodeColumns() [Internal]
  14298. // - DebugNodeDockNode() [Internal]
  14299. // - DebugNodeDrawList() [Internal]
  14300. // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
  14301. // - DebugNodeStorage() [Internal]
  14302. // - DebugNodeTabBar() [Internal]
  14303. // - DebugNodeViewport() [Internal]
  14304. // - DebugNodeWindow() [Internal]
  14305. // - DebugNodeWindowSettings() [Internal]
  14306. // - DebugNodeWindowsList() [Internal]
  14307. //-----------------------------------------------------------------------------
  14308. #ifndef IMGUI_DISABLE_METRICS_WINDOW
  14309. void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
  14310. {
  14311. ImGuiContext& g = *GImGui;
  14312. ImGuiWindow* window = g.CurrentWindow;
  14313. ImVec2 scale = bb.GetSize() / viewport->Size;
  14314. ImVec2 off = bb.Min - viewport->Pos * scale;
  14315. float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
  14316. window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
  14317. for (int i = 0; i != g.Windows.Size; i++)
  14318. {
  14319. ImGuiWindow* thumb_window = g.Windows[i];
  14320. if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
  14321. continue;
  14322. if (thumb_window->Viewport != viewport)
  14323. continue;
  14324. ImRect thumb_r = thumb_window->Rect();
  14325. ImRect title_r = thumb_window->TitleBarRect();
  14326. thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale));
  14327. 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
  14328. thumb_r.ClipWithFull(bb);
  14329. title_r.ClipWithFull(bb);
  14330. const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
  14331. window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
  14332. window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
  14333. window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
  14334. window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
  14335. }
  14336. draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
  14337. }
  14338. static void RenderViewportsThumbnails()
  14339. {
  14340. ImGuiContext& g = *GImGui;
  14341. ImGuiWindow* window = g.CurrentWindow;
  14342. // 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.
  14343. float SCALE = 1.0f / 8.0f;
  14344. ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  14345. for (int n = 0; n < g.Viewports.Size; n++)
  14346. bb_full.Add(g.Viewports[n]->GetMainRect());
  14347. ImVec2 p = window->DC.CursorPos;
  14348. ImVec2 off = p - bb_full.Min * SCALE;
  14349. for (int n = 0; n < g.Viewports.Size; n++)
  14350. {
  14351. ImGuiViewportP* viewport = g.Viewports[n];
  14352. ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
  14353. ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
  14354. }
  14355. ImGui::Dummy(bb_full.GetSize() * SCALE);
  14356. }
  14357. static int IMGUI_CDECL ViewportComparerByFrontMostStampCount(const void* lhs, const void* rhs)
  14358. {
  14359. const ImGuiViewportP* a = *(const ImGuiViewportP* const *)lhs;
  14360. const ImGuiViewportP* b = *(const ImGuiViewportP* const *)rhs;
  14361. return b->LastFrontMostStampCount - a->LastFrontMostStampCount;
  14362. }
  14363. // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
  14364. static void MetricsHelpMarker(const char* desc)
  14365. {
  14366. ImGui::TextDisabled("(?)");
  14367. if (ImGui::IsItemHovered())
  14368. {
  14369. ImGui::BeginTooltip();
  14370. ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
  14371. ImGui::TextUnformatted(desc);
  14372. ImGui::PopTextWrapPos();
  14373. ImGui::EndTooltip();
  14374. }
  14375. }
  14376. void ImGui::ShowMetricsWindow(bool* p_open)
  14377. {
  14378. if (!Begin("Dear ImGui Metrics/Debugger", p_open))
  14379. {
  14380. End();
  14381. return;
  14382. }
  14383. ImGuiContext& g = *GImGui;
  14384. ImGuiIO& io = g.IO;
  14385. ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
  14386. // Basic info
  14387. Text("Dear ImGui %s", GetVersion());
  14388. Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  14389. Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
  14390. Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
  14391. Text("%d active allocations", io.MetricsActiveAllocations);
  14392. //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
  14393. Separator();
  14394. // Debugging enums
  14395. enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
  14396. const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
  14397. 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
  14398. const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
  14399. if (cfg->ShowWindowsRectsType < 0)
  14400. cfg->ShowWindowsRectsType = WRT_WorkRect;
  14401. if (cfg->ShowTablesRectsType < 0)
  14402. cfg->ShowTablesRectsType = TRT_WorkRect;
  14403. struct Funcs
  14404. {
  14405. static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
  14406. {
  14407. if (rect_type == TRT_OuterRect) { return table->OuterRect; }
  14408. else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
  14409. else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
  14410. else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
  14411. else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
  14412. else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
  14413. else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); }
  14414. 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); }
  14415. else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
  14416. else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate
  14417. else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
  14418. else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
  14419. else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
  14420. IM_ASSERT(0);
  14421. return ImRect();
  14422. }
  14423. static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
  14424. {
  14425. if (rect_type == WRT_OuterRect) { return window->Rect(); }
  14426. else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
  14427. else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
  14428. else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
  14429. else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
  14430. else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
  14431. else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
  14432. else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
  14433. IM_ASSERT(0);
  14434. return ImRect();
  14435. }
  14436. };
  14437. // Tools
  14438. if (TreeNode("Tools"))
  14439. {
  14440. // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
  14441. if (Button("Item Picker.."))
  14442. DebugStartItemPicker();
  14443. SameLine();
  14444. 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.");
  14445. Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
  14446. Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
  14447. SameLine();
  14448. SetNextItemWidth(GetFontSize() * 12);
  14449. cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
  14450. if (cfg->ShowWindowsRects && g.NavWindow != NULL)
  14451. {
  14452. BulletText("'%s':", g.NavWindow->Name);
  14453. Indent();
  14454. for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
  14455. {
  14456. ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
  14457. 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]);
  14458. }
  14459. Unindent();
  14460. }
  14461. Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
  14462. Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
  14463. Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
  14464. SameLine();
  14465. SetNextItemWidth(GetFontSize() * 12);
  14466. cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
  14467. if (cfg->ShowTablesRects && g.NavWindow != NULL)
  14468. {
  14469. for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
  14470. {
  14471. ImGuiTable* table = g.Tables.GetByIndex(table_n);
  14472. if (table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
  14473. continue;
  14474. BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
  14475. if (IsItemHovered())
  14476. 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);
  14477. Indent();
  14478. char buf[128];
  14479. for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
  14480. {
  14481. if (rect_n >= TRT_ColumnsRect)
  14482. {
  14483. if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
  14484. continue;
  14485. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  14486. {
  14487. ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
  14488. 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]);
  14489. Selectable(buf);
  14490. if (IsItemHovered())
  14491. GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
  14492. }
  14493. }
  14494. else
  14495. {
  14496. ImRect r = Funcs::GetTableRect(table, rect_n, -1);
  14497. 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]);
  14498. Selectable(buf);
  14499. if (IsItemHovered())
  14500. GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
  14501. }
  14502. }
  14503. Unindent();
  14504. }
  14505. }
  14506. TreePop();
  14507. }
  14508. // Windows
  14509. DebugNodeWindowsList(&g.Windows, "Windows");
  14510. //DebugNodeWindowsList(&g.WindowsFocusOrder, "WindowsFocusOrder");
  14511. // DrawLists
  14512. int drawlist_count = 0;
  14513. for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
  14514. drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
  14515. if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
  14516. {
  14517. for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
  14518. {
  14519. ImGuiViewportP* viewport = g.Viewports[viewport_i];
  14520. bool viewport_has_drawlist = false;
  14521. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  14522. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  14523. {
  14524. if (!viewport_has_drawlist)
  14525. Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
  14526. viewport_has_drawlist = true;
  14527. DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  14528. }
  14529. }
  14530. TreePop();
  14531. }
  14532. // Viewports
  14533. if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
  14534. {
  14535. Indent(GetTreeNodeToLabelSpacing());
  14536. RenderViewportsThumbnails();
  14537. Unindent(GetTreeNodeToLabelSpacing());
  14538. bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
  14539. SameLine();
  14540. MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
  14541. if (open)
  14542. {
  14543. for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
  14544. {
  14545. const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
  14546. BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
  14547. i, mon.DpiScale * 100.0f,
  14548. mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
  14549. mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
  14550. }
  14551. TreePop();
  14552. }
  14553. if (TreeNode("Inferred order (front-to-back)"))
  14554. {
  14555. static ImVector<ImGuiViewportP*> viewports;
  14556. viewports.resize(g.Viewports.Size);
  14557. memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
  14558. if (viewports.Size > 1)
  14559. ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByFrontMostStampCount);
  14560. for (int i = 0; i < viewports.Size; i++)
  14561. BulletText("Viewport #%d, ID: 0x%08X, FrontMostStampCount = %08d, Window: \"%s\"", viewports[i]->Idx, viewports[i]->ID, viewports[i]->LastFrontMostStampCount, viewports[i]->Window ? viewports[i]->Window->Name : "N/A");
  14562. TreePop();
  14563. }
  14564. for (int i = 0; i < g.Viewports.Size; i++)
  14565. DebugNodeViewport(g.Viewports[i]);
  14566. TreePop();
  14567. }
  14568. // Details for Popups
  14569. if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
  14570. {
  14571. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  14572. {
  14573. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  14574. BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
  14575. }
  14576. TreePop();
  14577. }
  14578. // Details for TabBars
  14579. if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
  14580. {
  14581. for (int n = 0; n < g.TabBars.GetSize(); n++)
  14582. {
  14583. ImGuiTabBar* tab_bar = g.TabBars.GetByIndex(n);
  14584. PushID(tab_bar);
  14585. DebugNodeTabBar(tab_bar, "TabBar");
  14586. PopID();
  14587. }
  14588. TreePop();
  14589. }
  14590. // Details for Tables
  14591. #ifdef IMGUI_HAS_TABLE
  14592. if (TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
  14593. {
  14594. for (int n = 0; n < g.Tables.GetSize(); n++)
  14595. DebugNodeTable(g.Tables.GetByIndex(n));
  14596. TreePop();
  14597. }
  14598. #endif // #ifdef IMGUI_HAS_TABLE
  14599. // Details for Docking
  14600. #ifdef IMGUI_HAS_DOCK
  14601. if (TreeNode("Docking"))
  14602. {
  14603. static bool root_nodes_only = true;
  14604. ImGuiDockContext* dc = &g.DockContext;
  14605. Checkbox("List root nodes", &root_nodes_only);
  14606. Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
  14607. if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
  14608. SameLine();
  14609. if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
  14610. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  14611. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  14612. if (!root_nodes_only || node->IsRootNode())
  14613. DebugNodeDockNode(node, "Node");
  14614. TreePop();
  14615. }
  14616. #endif // #ifdef IMGUI_HAS_DOCK
  14617. // Settings
  14618. if (TreeNode("Settings"))
  14619. {
  14620. if (SmallButton("Clear"))
  14621. ClearIniSettings();
  14622. SameLine();
  14623. if (SmallButton("Save to memory"))
  14624. SaveIniSettingsToMemory();
  14625. SameLine();
  14626. if (SmallButton("Save to disk"))
  14627. SaveIniSettingsToDisk(g.IO.IniFilename);
  14628. SameLine();
  14629. if (g.IO.IniFilename)
  14630. Text("\"%s\"", g.IO.IniFilename);
  14631. else
  14632. TextUnformatted("<NULL>");
  14633. Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
  14634. if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
  14635. {
  14636. for (int n = 0; n < g.SettingsHandlers.Size; n++)
  14637. BulletText("%s", g.SettingsHandlers[n].TypeName);
  14638. TreePop();
  14639. }
  14640. if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
  14641. {
  14642. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  14643. DebugNodeWindowSettings(settings);
  14644. TreePop();
  14645. }
  14646. #ifdef IMGUI_HAS_TABLE
  14647. if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
  14648. {
  14649. for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
  14650. DebugNodeTableSettings(settings);
  14651. TreePop();
  14652. }
  14653. #endif // #ifdef IMGUI_HAS_TABLE
  14654. #ifdef IMGUI_HAS_DOCK
  14655. if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
  14656. {
  14657. ImGuiDockContext* dc = &g.DockContext;
  14658. Text("In SettingsWindows:");
  14659. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  14660. if (settings->DockId != 0)
  14661. BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
  14662. Text("In SettingsNodes:");
  14663. for (int n = 0; n < dc->NodesSettings.Size; n++)
  14664. {
  14665. ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
  14666. const char* selected_tab_name = NULL;
  14667. if (settings->SelectedTabId)
  14668. {
  14669. if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
  14670. selected_tab_name = window->Name;
  14671. else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabId))
  14672. selected_tab_name = window_settings->GetName();
  14673. }
  14674. BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
  14675. }
  14676. TreePop();
  14677. }
  14678. #endif // #ifdef IMGUI_HAS_DOCK
  14679. if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
  14680. {
  14681. InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
  14682. TreePop();
  14683. }
  14684. TreePop();
  14685. }
  14686. // Misc Details
  14687. if (TreeNode("Internal state"))
  14688. {
  14689. const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
  14690. Text("WINDOWING");
  14691. Indent();
  14692. Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  14693. Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
  14694. Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
  14695. Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0);
  14696. Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
  14697. Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
  14698. Unindent();
  14699. Text("ITEMS");
  14700. Indent();
  14701. Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
  14702. Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  14703. Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
  14704. Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
  14705. Unindent();
  14706. Text("NAV,FOCUS");
  14707. Indent();
  14708. Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  14709. Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
  14710. Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
  14711. Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
  14712. Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
  14713. Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
  14714. Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
  14715. Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
  14716. Unindent();
  14717. TreePop();
  14718. }
  14719. // Overlay: Display windows Rectangles and Begin Order
  14720. if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
  14721. {
  14722. for (int n = 0; n < g.Windows.Size; n++)
  14723. {
  14724. ImGuiWindow* window = g.Windows[n];
  14725. if (!window->WasActive)
  14726. continue;
  14727. ImDrawList* draw_list = GetForegroundDrawList(window);
  14728. if (cfg->ShowWindowsRects)
  14729. {
  14730. ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
  14731. draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
  14732. }
  14733. if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
  14734. {
  14735. char buf[32];
  14736. ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
  14737. float font_size = GetFontSize();
  14738. draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
  14739. draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
  14740. }
  14741. }
  14742. }
  14743. #ifdef IMGUI_HAS_TABLE
  14744. // Overlay: Display Tables Rectangles
  14745. if (cfg->ShowTablesRects)
  14746. {
  14747. for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
  14748. {
  14749. ImGuiTable* table = g.Tables.GetByIndex(table_n);
  14750. if (table->LastFrameActive < g.FrameCount - 1)
  14751. continue;
  14752. ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
  14753. if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
  14754. {
  14755. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  14756. {
  14757. ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
  14758. ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
  14759. float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
  14760. draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
  14761. }
  14762. }
  14763. else
  14764. {
  14765. ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
  14766. draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
  14767. }
  14768. }
  14769. }
  14770. #endif // #ifdef IMGUI_HAS_TABLE
  14771. #ifdef IMGUI_HAS_DOCK
  14772. // Overlay: Display Docking info
  14773. if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.HoveredDockNode)
  14774. {
  14775. char buf[64] = "";
  14776. char* p = buf;
  14777. ImGuiDockNode* node = g.HoveredDockNode;
  14778. ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
  14779. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
  14780. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
  14781. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
  14782. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
  14783. int depth = DockNodeGetDepth(node);
  14784. overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
  14785. ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
  14786. overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
  14787. overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
  14788. }
  14789. #endif // #ifdef IMGUI_HAS_DOCK
  14790. End();
  14791. }
  14792. // [DEBUG] Display contents of Columns
  14793. void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
  14794. {
  14795. if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
  14796. return;
  14797. BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
  14798. for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
  14799. BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
  14800. TreePop();
  14801. }
  14802. // [DEBUG] Display contents of ImDockNode
  14803. void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
  14804. {
  14805. ImGuiContext& g = *GImGui;
  14806. const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
  14807. const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted
  14808. if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  14809. bool open;
  14810. if (node->Windows.Size > 0)
  14811. open = TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
  14812. else
  14813. open = TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
  14814. if (!is_alive) { PopStyleColor(); }
  14815. if (is_active && IsItemHovered())
  14816. if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
  14817. GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
  14818. if (open)
  14819. {
  14820. IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
  14821. IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
  14822. BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
  14823. node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
  14824. DebugNodeWindow(node->HostWindow, "HostWindow");
  14825. DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
  14826. BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
  14827. BulletText("Misc:%s%s%s%s%s",
  14828. node->IsDockSpace() ? " IsDockSpace" : "",
  14829. node->IsCentralNode() ? " IsCentralNode" : "",
  14830. is_alive ? " IsAlive" : "", is_active ? " IsActive" : "",
  14831. node->WantLockSizeOnce ? " WantLockSizeOnce" : "");
  14832. if (TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags))
  14833. {
  14834. CheckboxFlags("LocalFlags: NoDocking", &node->LocalFlags, ImGuiDockNodeFlags_NoDocking);
  14835. CheckboxFlags("LocalFlags: NoSplit", &node->LocalFlags, ImGuiDockNodeFlags_NoSplit);
  14836. CheckboxFlags("LocalFlags: NoResize", &node->LocalFlags, ImGuiDockNodeFlags_NoResize);
  14837. CheckboxFlags("LocalFlags: NoResizeX", &node->LocalFlags, ImGuiDockNodeFlags_NoResizeX);
  14838. CheckboxFlags("LocalFlags: NoResizeY", &node->LocalFlags, ImGuiDockNodeFlags_NoResizeY);
  14839. CheckboxFlags("LocalFlags: NoTabBar", &node->LocalFlags, ImGuiDockNodeFlags_NoTabBar);
  14840. CheckboxFlags("LocalFlags: HiddenTabBar", &node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar);
  14841. CheckboxFlags("LocalFlags: NoWindowMenuButton", &node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton);
  14842. CheckboxFlags("LocalFlags: NoCloseButton", &node->LocalFlags, ImGuiDockNodeFlags_NoCloseButton);
  14843. TreePop();
  14844. }
  14845. if (node->ParentNode)
  14846. DebugNodeDockNode(node->ParentNode, "ParentNode");
  14847. if (node->ChildNodes[0])
  14848. DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
  14849. if (node->ChildNodes[1])
  14850. DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
  14851. if (node->TabBar)
  14852. DebugNodeTabBar(node->TabBar, "TabBar");
  14853. TreePop();
  14854. }
  14855. }
  14856. // [DEBUG] Display contents of ImDrawList
  14857. // Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
  14858. void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
  14859. {
  14860. ImGuiContext& g = *GImGui;
  14861. ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
  14862. int cmd_count = draw_list->CmdBuffer.Size;
  14863. if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
  14864. cmd_count--;
  14865. 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);
  14866. if (draw_list == GetWindowDrawList())
  14867. {
  14868. SameLine();
  14869. 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)
  14870. if (node_open)
  14871. TreePop();
  14872. return;
  14873. }
  14874. ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
  14875. if (window && fg_draw_list && IsItemHovered())
  14876. fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  14877. if (!node_open)
  14878. return;
  14879. if (window && !window->WasActive)
  14880. TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
  14881. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
  14882. {
  14883. if (pcmd->UserCallback)
  14884. {
  14885. BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  14886. continue;
  14887. }
  14888. char buf[300];
  14889. ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
  14890. pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
  14891. pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  14892. bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
  14893. if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
  14894. DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
  14895. if (!pcmd_node_open)
  14896. continue;
  14897. // Calculate approximate coverage area (touched pixel count)
  14898. // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
  14899. const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  14900. const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
  14901. float total_area = 0.0f;
  14902. for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
  14903. {
  14904. ImVec2 triangle[3];
  14905. for (int n = 0; n < 3; n++, idx_n++)
  14906. triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
  14907. total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
  14908. }
  14909. // Display vertex information summary. Hover to get all triangles drawn in wire-frame
  14910. ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
  14911. Selectable(buf);
  14912. if (IsItemHovered() && fg_draw_list)
  14913. DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
  14914. // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
  14915. ImGuiListClipper clipper;
  14916. clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  14917. while (clipper.Step())
  14918. for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
  14919. {
  14920. char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
  14921. ImVec2 triangle[3];
  14922. for (int n = 0; n < 3; n++, idx_i++)
  14923. {
  14924. const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
  14925. triangle[n] = v.pos;
  14926. buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
  14927. (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  14928. }
  14929. Selectable(buf, false);
  14930. if (fg_draw_list && IsItemHovered())
  14931. {
  14932. ImDrawListFlags backup_flags = fg_draw_list->Flags;
  14933. fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  14934. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
  14935. fg_draw_list->Flags = backup_flags;
  14936. }
  14937. }
  14938. TreePop();
  14939. }
  14940. TreePop();
  14941. }
  14942. // [DEBUG] Display mesh/aabb of a ImDrawCmd
  14943. void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
  14944. {
  14945. IM_ASSERT(show_mesh || show_aabb);
  14946. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  14947. ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
  14948. // Draw wire-frame version of all triangles
  14949. ImRect clip_rect = draw_cmd->ClipRect;
  14950. ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  14951. ImDrawListFlags backup_flags = out_draw_list->Flags;
  14952. out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  14953. for (unsigned int idx_n = draw_cmd->IdxOffset; idx_n < draw_cmd->IdxOffset + draw_cmd->ElemCount; )
  14954. {
  14955. ImVec2 triangle[3];
  14956. for (int n = 0; n < 3; n++, idx_n++)
  14957. vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
  14958. if (show_mesh)
  14959. out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
  14960. }
  14961. // Draw bounding boxes
  14962. if (show_aabb)
  14963. {
  14964. 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
  14965. out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
  14966. }
  14967. out_draw_list->Flags = backup_flags;
  14968. }
  14969. // [DEBUG] Display contents of ImGuiStorage
  14970. void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
  14971. {
  14972. if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
  14973. return;
  14974. for (int n = 0; n < storage->Data.Size; n++)
  14975. {
  14976. const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
  14977. 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.
  14978. }
  14979. TreePop();
  14980. }
  14981. // [DEBUG] Display contents of ImGuiTabBar
  14982. void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
  14983. {
  14984. // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
  14985. char buf[256];
  14986. char* p = buf;
  14987. const char* buf_end = buf + IM_ARRAYSIZE(buf);
  14988. const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
  14989. p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
  14990. p += ImFormatString(p, buf_end - p, " { ");
  14991. for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
  14992. {
  14993. ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  14994. p += ImFormatString(p, buf_end - p, "%s'%s'",
  14995. tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???");
  14996. }
  14997. p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
  14998. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  14999. bool open = TreeNode(label, "%s", buf);
  15000. if (!is_active) { PopStyleColor(); }
  15001. if (is_active && IsItemHovered())
  15002. {
  15003. ImDrawList* draw_list = GetForegroundDrawList();
  15004. draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
  15005. 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));
  15006. 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));
  15007. }
  15008. if (open)
  15009. {
  15010. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
  15011. {
  15012. const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  15013. PushID(tab);
  15014. if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
  15015. if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
  15016. Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f",
  15017. tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth);
  15018. PopID();
  15019. }
  15020. TreePop();
  15021. }
  15022. }
  15023. void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
  15024. {
  15025. SetNextItemOpen(true, ImGuiCond_Once);
  15026. if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
  15027. {
  15028. ImGuiWindowFlags flags = viewport->Flags;
  15029. BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
  15030. viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
  15031. viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
  15032. viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
  15033. if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
  15034. BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
  15035. //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
  15036. (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
  15037. (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
  15038. (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
  15039. (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
  15040. (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
  15041. (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
  15042. (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
  15043. (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
  15044. (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
  15045. (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
  15046. (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
  15047. (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
  15048. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  15049. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  15050. DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  15051. TreePop();
  15052. }
  15053. }
  15054. void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
  15055. {
  15056. if (window == NULL)
  15057. {
  15058. BulletText("%s: NULL", label);
  15059. return;
  15060. }
  15061. ImGuiContext& g = *GImGui;
  15062. const bool is_active = window->WasActive;
  15063. ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
  15064. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  15065. const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
  15066. if (!is_active) { PopStyleColor(); }
  15067. if (IsItemHovered() && is_active)
  15068. GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  15069. if (!open)
  15070. return;
  15071. if (window->MemoryCompacted)
  15072. TextDisabled("Note: some memory buffers have been compacted/freed.");
  15073. ImGuiWindowFlags flags = window->Flags;
  15074. DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
  15075. 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);
  15076. BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
  15077. (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
  15078. (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
  15079. (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
  15080. BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
  15081. 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" : "");
  15082. BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
  15083. BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
  15084. for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
  15085. {
  15086. ImRect r = window->NavRectRel[layer];
  15087. if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
  15088. {
  15089. BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
  15090. continue;
  15091. }
  15092. 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);
  15093. if (IsItemHovered())
  15094. GetForegroundDrawList(window)->AddRect(r.Min + window->Pos, r.Max + window->Pos, IM_COL32(255, 255, 0, 255));
  15095. }
  15096. BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
  15097. BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
  15098. BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
  15099. BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
  15100. if (window->DockNode || window->DockNodeAsHost)
  15101. DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
  15102. if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
  15103. if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
  15104. if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
  15105. if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
  15106. if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
  15107. {
  15108. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  15109. DebugNodeColumns(&window->ColumnsStorage[n]);
  15110. TreePop();
  15111. }
  15112. DebugNodeStorage(&window->StateStorage, "Storage");
  15113. TreePop();
  15114. }
  15115. void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
  15116. {
  15117. Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
  15118. settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
  15119. }
  15120. void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
  15121. {
  15122. if (!TreeNode(label, "%s (%d)", label, windows->Size))
  15123. return;
  15124. Text("(In front-to-back order:)");
  15125. for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
  15126. {
  15127. PushID((*windows)[i]);
  15128. DebugNodeWindow((*windows)[i], "Window");
  15129. PopID();
  15130. }
  15131. TreePop();
  15132. }
  15133. #else
  15134. void ImGui::ShowMetricsWindow(bool*) {}
  15135. void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
  15136. void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
  15137. void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
  15138. void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
  15139. void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
  15140. void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
  15141. void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
  15142. void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
  15143. void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
  15144. #endif
  15145. //-----------------------------------------------------------------------------
  15146. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  15147. // 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.
  15148. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  15149. #include "imgui_user.inl"
  15150. #endif
  15151. //-----------------------------------------------------------------------------
  15152. #endif // #ifndef IMGUI_DISABLE