imgui.cpp 757 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687
  1. // dear imgui, v1.76 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 for demo code. All applications in examples/ are doing that.
  7. // Resources:
  8. // - FAQ http://dearimgui.org/faq
  9. // - Homepage & latest https://github.com/ocornut/imgui
  10. // - Releases & changelog https://github.com/ocornut/imgui/releases
  11. // - Gallery https://github.com/ocornut/imgui/issues/2847 (please post your screenshots/video there!)
  12. // - Glossary https://github.com/ocornut/imgui/wiki/Glossary
  13. // - Wiki https://github.com/ocornut/imgui/wiki
  14. // - Issues & support https://github.com/ocornut/imgui/issues
  15. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  16. // See LICENSE.txt for copyright and licensing details (standard MIT License).
  17. // This library is free but I need your support to sustain development and maintenance.
  18. // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org".
  19. // Individuals: you can support continued development via donations. See docs/README or web page.
  20. // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
  21. // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
  22. // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
  23. // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
  24. // to a better solution or official support for them.
  25. /*
  26. Index of this file:
  27. DOCUMENTATION
  28. - MISSION STATEMENT
  29. - END-USER GUIDE
  30. - PROGRAMMER GUIDE
  31. - READ FIRST
  32. - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  33. - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  34. - HOW A SIMPLE APPLICATION MAY LOOK LIKE (2 variations)
  35. - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  36. - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  37. - API BREAKING CHANGES (read me when you update!)
  38. - FREQUENTLY ASKED QUESTIONS (FAQ)
  39. - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
  40. CODE
  41. (search for "[SECTION]" in the code to find them)
  42. // [SECTION] FORWARD DECLARATIONS
  43. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  44. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  45. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  46. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  47. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  48. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  49. // [SECTION] MISC HELPERS/UTILITIES (Color functions)
  50. // [SECTION] ImGuiStorage
  51. // [SECTION] ImGuiTextFilter
  52. // [SECTION] ImGuiTextBuffer
  53. // [SECTION] ImGuiListClipper
  54. // [SECTION] STYLING
  55. // [SECTION] RENDER HELPERS
  56. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  57. // [SECTION] ERROR CHECKING
  58. // [SECTION] LAYOUT
  59. // [SECTION] SCROLLING
  60. // [SECTION] TOOLTIPS
  61. // [SECTION] POPUPS
  62. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  63. // [SECTION] DRAG AND DROP
  64. // [SECTION] LOGGING/CAPTURING
  65. // [SECTION] SETTINGS
  66. // [SECTION] VIEWPORTS, PLATFORM WINDOWS
  67. // [SECTION] DOCKING
  68. // [SECTION] PLATFORM DEPENDENT HELPERS
  69. // [SECTION] METRICS/DEBUG WINDOW
  70. */
  71. //-----------------------------------------------------------------------------
  72. // DOCUMENTATION
  73. //-----------------------------------------------------------------------------
  74. /*
  75. MISSION STATEMENT
  76. =================
  77. - Easy to use to create code-driven and data-driven tools.
  78. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
  79. - Easy to hack and improve.
  80. - Minimize screen real-estate usage.
  81. - Minimize setup and maintenance.
  82. - Minimize state storage on user side.
  83. - Portable, minimize dependencies, run on target (consoles, phones, etc.).
  84. - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
  85. opening a tree node for the first time, etc. but a typical frame should not allocate anything).
  86. Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
  87. - Doesn't look fancy, doesn't animate.
  88. - Limited layout features, intricate layouts are typically crafted in code.
  89. END-USER GUIDE
  90. ==============
  91. - Double-click on title bar to collapse window.
  92. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
  93. - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
  94. - Click and drag on any empty space to move window.
  95. - TAB/SHIFT+TAB to cycle through keyboard editable fields.
  96. - CTRL+Click on a slider or drag box to input value as text.
  97. - Use mouse wheel to scroll.
  98. - Text editor:
  99. - Hold SHIFT or use mouse to select text.
  100. - CTRL+Left/Right to word jump.
  101. - CTRL+Shift+Left/Right to select words.
  102. - CTRL+A our Double-Click to select all.
  103. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
  104. - CTRL+Z,CTRL+Y to undo/redo.
  105. - ESCAPE to revert text to its original value.
  106. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  107. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  108. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
  109. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
  110. PROGRAMMER GUIDE
  111. ================
  112. READ FIRST
  113. ----------
  114. - Remember to read the FAQ (https://www.dearimgui.org/faq)
  115. - 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
  116. or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
  117. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
  118. - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
  119. - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
  120. You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
  121. - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
  122. For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
  123. where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
  124. - Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
  125. - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
  126. - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
  127. If you get an assert, read the messages and comments around the assert.
  128. - 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.
  129. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
  130. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
  131. However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
  132. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
  133. HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  134. ----------------------------------------------
  135. - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
  136. - Or maintain your own branch where you have imconfig.h modified.
  137. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  138. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
  139. from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
  140. likely be a comment about it. Please report any issue to the GitHub page!
  141. - Try to keep your copy of dear imgui reasonably up to date.
  142. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  143. ---------------------------------------------------------------
  144. - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
  145. - In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder.
  146. - Add the Dear ImGui source files to your projects or using your preferred build system.
  147. It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL).
  148. - 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.
  149. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
  150. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
  151. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
  152. phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render().
  153. - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
  154. - 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.
  155. HOW A SIMPLE APPLICATION MAY LOOK LIKE
  156. --------------------------------------
  157. EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
  158. // Application init: create a dear imgui context, setup some options, load fonts
  159. ImGui::CreateContext();
  160. ImGuiIO& io = ImGui::GetIO();
  161. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  162. // TODO: Fill optional fields of the io structure later.
  163. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  164. // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
  165. ImGui_ImplWin32_Init(hwnd);
  166. ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
  167. // Application main loop
  168. while (true)
  169. {
  170. // Feed inputs to dear imgui, start new frame
  171. ImGui_ImplDX11_NewFrame();
  172. ImGui_ImplWin32_NewFrame();
  173. ImGui::NewFrame();
  174. // Any application code here
  175. ImGui::Text("Hello, world!");
  176. // Render dear imgui into screen
  177. ImGui::Render();
  178. ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
  179. g_pSwapChain->Present(1, 0);
  180. }
  181. // Shutdown
  182. ImGui_ImplDX11_Shutdown();
  183. ImGui_ImplWin32_Shutdown();
  184. ImGui::DestroyContext();
  185. EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE
  186. // Application init: create a dear imgui context, setup some options, load fonts
  187. ImGui::CreateContext();
  188. ImGuiIO& io = ImGui::GetIO();
  189. // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
  190. // TODO: Fill optional fields of the io structure later.
  191. // TODO: Load TTF/OTF fonts if you don't want to use the default font.
  192. // Build and load the texture atlas into a texture
  193. // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
  194. int width, height;
  195. unsigned char* pixels = NULL;
  196. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  197. // At this point you've got the texture data and you need to upload that your your graphic system:
  198. // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
  199. // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
  200. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
  201. io.Fonts->TexID = (void*)texture;
  202. // Application main loop
  203. while (true)
  204. {
  205. // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
  206. // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
  207. io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
  208. io.DisplaySize.x = 1920.0f; // set the current display width
  209. io.DisplaySize.y = 1280.0f; // set the current display height here
  210. io.MousePos = my_mouse_pos; // set the mouse position
  211. io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
  212. io.MouseDown[1] = my_mouse_buttons[1];
  213. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  214. // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere)
  215. ImGui::NewFrame();
  216. // Most of your application code here
  217. ImGui::Text("Hello, world!");
  218. MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  219. MyGameRender(); // may use any Dear ImGui functions as well!
  220. // Render dear imgui, swap buffers
  221. // (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)
  222. ImGui::EndFrame();
  223. ImGui::Render();
  224. ImDrawData* draw_data = ImGui::GetDrawData();
  225. MyImGuiRenderFunction(draw_data);
  226. SwapBuffers();
  227. }
  228. // Shutdown
  229. ImGui::DestroyContext();
  230. HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
  231. ---------------------------------------------
  232. void void MyImGuiRenderFunction(ImDrawData* draw_data)
  233. {
  234. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  235. // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  236. // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
  237. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  238. for (int n = 0; n < draw_data->CmdListsCount; n++)
  239. {
  240. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  241. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
  242. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
  243. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  244. {
  245. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  246. if (pcmd->UserCallback)
  247. {
  248. pcmd->UserCallback(cmd_list, pcmd);
  249. }
  250. else
  251. {
  252. // The texture for the draw call is specified by pcmd->TextureId.
  253. // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
  254. MyEngineBindTexture((MyTexture*)pcmd->TextureId);
  255. // We are using scissoring to clip some objects. All low-level graphics API should supports it.
  256. // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
  257. // (some elements visible outside their bounds) but you can fix that once everything else works!
  258. // - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
  259. // In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
  260. // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
  261. // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
  262. // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
  263. ImVec2 pos = draw_data->DisplayPos;
  264. 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));
  265. // Render 'pcmd->ElemCount/3' indexed triangles.
  266. // 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.
  267. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
  268. }
  269. idx_buffer += pcmd->ElemCount;
  270. }
  271. }
  272. }
  273. - The examples/ folders contains many actual implementation of the pseudo-codes above.
  274. - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
  275. They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the
  276. rest of your application. In every cases you need to pass on the inputs to Dear ImGui.
  277. - Refer to the FAQ for more information. Amusingly, it is called a FAQ because people frequently run into the same issues!
  278. USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
  279. ------------------------------------------
  280. - The gamepad/keyboard navigation is fairly functional and keeps being improved.
  281. - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
  282. - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
  283. - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
  284. - Keyboard:
  285. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
  286. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
  287. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
  288. will be set. For more advanced uses, you may want to read from:
  289. - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
  290. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
  291. - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
  292. Please reach out if you think the game vs navigation input sharing could be improved.
  293. - Gamepad:
  294. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
  295. - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
  296. Note that io.NavInputs[] is cleared by EndFrame().
  297. - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
  298. 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
  299. - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
  300. 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.).
  301. - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
  302. - 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
  303. to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
  304. - Mouse:
  305. - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
  306. - 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.
  307. - 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.
  308. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
  309. 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.
  310. When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
  311. (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
  312. (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
  313. to set a boolean to ignore your other external mouse positions until the external source is moved again.)
  314. API BREAKING CHANGES
  315. ====================
  316. Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
  317. 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.
  318. When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  319. You can read releases logs https://github.com/ocornut/imgui/releases for more details.
  320. (Docking/Viewport Branch)
  321. - 2019/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
  322. - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
  323. you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
  324. - likewise io.MousePos and GetMousePos() will use OS coordinates.
  325. If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
  326. - 2019/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api.
  327. - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
  328. - 2019/12/17 (1.75) - 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.
  329. - 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.
  330. - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
  331. - ShowTestWindow() -> use ShowDemoWindow()
  332. - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
  333. - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
  334. - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
  335. - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
  336. - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
  337. - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
  338. - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
  339. - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
  340. - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was the vaguely documented and rarely if ever used). Instead we added an explicit PrimUnreserve() API.
  341. - 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).
  342. - 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.
  343. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
  344. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
  345. - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
  346. - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
  347. - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
  348. - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
  349. - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
  350. - ImFont::Glyph -> use ImFontGlyph
  351. - 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.
  352. 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.
  353. 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).
  354. If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
  355. - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
  356. - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
  357. - 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.
  358. - 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
  359. 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.
  360. 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.
  361. Please reach out if you are affected.
  362. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
  363. - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
  364. - 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.
  365. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
  366. - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
  367. - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
  368. - 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 a dummy small value!
  369. - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
  370. - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
  371. - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
  372. - 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.
  373. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
  374. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
  375. - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
  376. - 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.
  377. If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
  378. - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
  379. - 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.
  380. NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
  381. Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
  382. - 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).
  383. - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
  384. - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
  385. - 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.
  386. - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
  387. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
  388. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
  389. - 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.).
  390. old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
  391. when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
  392. in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
  393. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
  394. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
  395. - 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.
  396. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
  397. 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.
  398. 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.
  399. - 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",
  400. consistent with other functions. Kept redirection functions (will obsolete).
  401. - 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.
  402. - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
  403. - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
  404. - 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.
  405. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
  406. - 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.
  407. - 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.
  408. - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
  409. - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
  410. - removed Shutdown() function, as DestroyContext() serve this purpose.
  411. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
  412. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
  413. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
  414. - 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.
  415. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
  416. - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
  417. - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
  418. - 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.
  419. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
  420. - 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
  421. - 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.
  422. - 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.
  423. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
  424. - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
  425. - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
  426. - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
  427. - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
  428. - 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.
  429. - 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.
  430. 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.
  431. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
  432. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
  433. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
  434. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
  435. - 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.
  436. - 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.
  437. - 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.
  438. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
  439. IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
  440. IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
  441. IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
  442. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
  443. - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
  444. - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
  445. - 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).
  446. - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
  447. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
  448. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  449. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  450. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  451. - 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.
  452. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
  453. - 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.
  454. - 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).
  455. - 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).
  456. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  457. - 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.
  458. - 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.
  459. - 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))'
  460. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  461. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  462. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  463. - 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().
  464. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  465. - 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.
  466. - 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.
  467. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  468. 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 tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
  469. 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:
  470. 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); }
  471. 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.
  472. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  473. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  474. - 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).
  475. - 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.
  476. - 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).
  477. - 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)
  478. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  479. - 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.
  480. - 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.
  481. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  482. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  483. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  484. 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.
  485. 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!
  486. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  487. - 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.
  488. - 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
  489. - 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.
  490. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  491. - 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.
  492. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  493. - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
  494. - the signature of the io.RenderDrawListsFn handler has changed!
  495. old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  496. new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  497. parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
  498. ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
  499. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
  500. - 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.
  501. - 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!
  502. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  503. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  504. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  505. - 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.
  506. - 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
  507. - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
  508. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  509. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  510. - 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.
  511. - 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.
  512. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  513. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  514. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  515. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  516. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  517. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  518. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  519. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  520. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  521. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  522. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  523. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  524. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  525. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  526. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  527. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  528. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  529. - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  530. - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
  531. - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->TexId = YourTexIdentifier;
  532. 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.
  533. - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
  534. - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  535. - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  536. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  537. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  538. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  539. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  540. - 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)
  541. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  542. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  543. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  544. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  545. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  546. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  547. FREQUENTLY ASKED QUESTIONS (FAQ)
  548. ================================
  549. Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
  550. Some answers are copied down here to facilitate searching in code.
  551. Q&A: Basics
  552. ===========
  553. Q: Where is the documentation?
  554. A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
  555. - Run the examples/ and explore them.
  556. - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
  557. - The demo covers most features of Dear ImGui, so you can read the code and see its output.
  558. - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
  559. - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
  560. examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
  561. - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
  562. - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
  563. - Your programming IDE is your friend, find the type or function declaration to find comments
  564. associated to it.
  565. Q: What is this library called?
  566. Q: Which version should I get?
  567. >> This library is called "Dear ImGui", please don't call it "ImGui" :)
  568. >> See https://www.dearimgui.org/faq
  569. Q&A: Integration
  570. ================
  571. Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
  572. A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
  573. >> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this.
  574. Q. How can I enable keyboard controls?
  575. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
  576. Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
  577. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  578. >> See https://www.dearimgui.org/faq
  579. Q&A: Usage
  580. ----------
  581. Q: Why are multiple widgets reacting when I interact with a single one?
  582. Q: How can I have multiple widgets with the same label or with an empty label?
  583. A: A primer on labels and the ID Stack...
  584. Dear ImGui internally need to uniquely identify UI elements.
  585. Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
  586. Interactive widgets (such as calls to Button buttons) need a unique ID.
  587. Unique ID are used internally to track active widgets and occasionally associate state to widgets.
  588. Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
  589. - Unique ID are often derived from a string label:
  590. Button("OK"); // Label = "OK", ID = hash of (..., "OK")
  591. Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
  592. - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
  593. two buttons labeled "OK" in different windows or different tree locations is fine.
  594. We used "..." above to signify whatever was already pushed to the ID stack previously:
  595. Begin("MyWindow");
  596. Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
  597. End();
  598. Begin("MyOtherWindow");
  599. Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
  600. End();
  601. - If you have a same ID twice in the same location, you'll have a conflict:
  602. Button("OK");
  603. Button("OK"); // ID collision! Interacting with either button will trigger the first one.
  604. Fear not! this is easy to solve and there are many ways to solve it!
  605. - Solving ID conflict in a simple/local context:
  606. When passing a label you can optionally specify extra ID information within string itself.
  607. Use "##" to pass a complement to the ID that won't be visible to the end-user.
  608. This helps solving the simple collision cases when you know e.g. at compilation time which items
  609. are going to be created:
  610. Begin("MyWindow");
  611. Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
  612. Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
  613. Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
  614. End();
  615. - If you want to completely hide the label, but still need an ID:
  616. Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
  617. - Occasionally/rarely you might want change a label while preserving a constant ID. This allows
  618. you to animate labels. For example you may want to include varying information in a window title bar,
  619. but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
  620. Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
  621. Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
  622. sprintf(buf, "My game (%f FPS)###MyGame", fps);
  623. Begin(buf); // Variable title, ID = hash of "MyGame"
  624. - Solving ID conflict in a more general manner:
  625. Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
  626. within the same window. This is the most convenient way of distinguishing ID when iterating and
  627. creating many UI elements programmatically.
  628. You can push a pointer, a string or an integer value into the ID stack.
  629. Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
  630. At each level of the stack we store the seed used for items at this level of the ID stack.
  631. Begin("Window");
  632. for (int i = 0; i < 100; i++)
  633. {
  634. PushID(i); // Push i to the id tack
  635. Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
  636. PopID();
  637. }
  638. for (int i = 0; i < 100; i++)
  639. {
  640. MyObject* obj = Objects[i];
  641. PushID(obj);
  642. Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
  643. PopID();
  644. }
  645. for (int i = 0; i < 100; i++)
  646. {
  647. MyObject* obj = Objects[i];
  648. PushID(obj->Name);
  649. Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
  650. PopID();
  651. }
  652. End();
  653. - You can stack multiple prefixes into the ID stack:
  654. Button("Click"); // Label = "Click", ID = hash of (..., "Click")
  655. PushID("node");
  656. Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
  657. PushID(my_ptr);
  658. Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
  659. PopID();
  660. PopID();
  661. - Tree nodes implicitly creates a scope for you by calling PushID().
  662. Button("Click"); // Label = "Click", ID = hash of (..., "Click")
  663. if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
  664. {
  665. Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
  666. TreePop();
  667. }
  668. - When working with trees, ID are used to preserve the open/close state of each tree node.
  669. Depending on your use cases you may want to use strings, indices or pointers as ID.
  670. e.g. when following a single pointer that may change over time, using a static string as ID
  671. will preserve your node open/closed state when the targeted object change.
  672. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
  673. node open/closed state differently. See what makes more sense in your situation!
  674. Q: How can I display an image? What is ImTextureID, how does it works?
  675. >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
  676. Q: How can I use my own math types instead of ImVec2/ImVec4?
  677. Q: How can I interact with standard C++ types (such as std::string and std::vector)?
  678. Q: How can I display custom shapes? (using low-level ImDrawList API)
  679. >> See https://www.dearimgui.org/faq
  680. Q&A: Fonts, Text
  681. ================
  682. Q: How can I load a different font than the default?
  683. Q: How can I easily use icons in my application?
  684. Q: How can I load multiple fonts?
  685. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  686. >> See https://www.dearimgui.org/faq and docs/FONTS.txt
  687. Q&A: Concerns
  688. =============
  689. Q: Who uses Dear ImGui?
  690. Q: Can you create elaborate/serious tools with Dear ImGui?
  691. Q: Can you reskin the look of Dear ImGui?
  692. Q: Why using C++ (as opposed to C)?
  693. >> See https://www.dearimgui.org/faq
  694. Q&A: Community
  695. ==============
  696. Q: How can I help?
  697. A: - Businesses: please reach out to "contact AT dearimgui.org" if you work in a place using Dear ImGui!
  698. We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
  699. 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.
  700. - Individuals: you can support continued development via PayPal donations. See README.
  701. - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
  702. and see how you want to help and can help!
  703. - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
  704. You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/2847). Visuals are ideal as they inspire other programmers.
  705. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
  706. - 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).
  707. */
  708. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  709. #define _CRT_SECURE_NO_WARNINGS
  710. #endif
  711. #include "imgui.h"
  712. #ifndef IMGUI_DISABLE
  713. #ifndef IMGUI_DEFINE_MATH_OPERATORS
  714. #define IMGUI_DEFINE_MATH_OPERATORS
  715. #endif
  716. #include "imgui_internal.h"
  717. #include <ctype.h> // toupper
  718. #include <stdio.h> // vsnprintf, sscanf, printf
  719. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  720. #include <stddef.h> // intptr_t
  721. #else
  722. #include <stdint.h> // intptr_t
  723. #endif
  724. // Debug options
  725. #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
  726. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
  727. #define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
  728. // Visual Studio warnings
  729. #ifdef _MSC_VER
  730. #pragma warning (disable: 4127) // condition expression is constant
  731. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  732. #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
  733. #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
  734. #endif
  735. #endif
  736. // Clang/GCC warnings with -Weverything
  737. #if defined(__clang__)
  738. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
  739. #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
  740. #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.
  741. #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.
  742. #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.
  743. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
  744. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
  745. #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.
  746. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
  747. #if __has_warning("-Wzero-as-null-pointer-constant")
  748. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
  749. #endif
  750. #if __has_warning("-Wdouble-promotion")
  751. #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.
  752. #endif
  753. #elif defined(__GNUC__)
  754. // We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
  755. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  756. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  757. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  758. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  759. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  760. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  761. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  762. #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
  763. #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
  764. #endif
  765. // 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.
  766. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
  767. static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
  768. // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
  769. static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
  770. static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
  771. 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 certaint time, unless mouse moved.
  772. // Docking
  773. static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
  774. //-------------------------------------------------------------------------
  775. // [SECTION] FORWARD DECLARATIONS
  776. //-------------------------------------------------------------------------
  777. static void SetCurrentWindow(ImGuiWindow* window);
  778. static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size);
  779. static void FindHoveredWindow();
  780. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
  781. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
  782. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
  783. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
  784. // Settings
  785. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
  786. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
  787. static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
  788. // Platform Dependents default implementation for IO functions
  789. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  790. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  791. namespace ImGui
  792. {
  793. // Navigation
  794. static void NavUpdate();
  795. static void NavUpdateWindowing();
  796. static void NavUpdateWindowingOverlay();
  797. static void NavUpdateMoveResult();
  798. static float NavUpdatePageUpPageDown();
  799. static inline void NavUpdateAnyRequestFlag();
  800. static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand);
  801. static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
  802. static ImVec2 NavCalcPreferredRefPos();
  803. static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
  804. static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
  805. static int FindWindowFocusIndex(ImGuiWindow* window);
  806. // Error Checking
  807. static void ErrorCheckEndFrame();
  808. static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write);
  809. // Misc
  810. static void UpdateSettings();
  811. static void UpdateMouseInputs();
  812. static void UpdateMouseWheel();
  813. static void UpdateTabFocus();
  814. static void UpdateDebugToolItemPicker();
  815. static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
  816. static void RenderWindowOuterBorders(ImGuiWindow* window);
  817. 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);
  818. static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
  819. static void EndFrameDrawDimmedBackgrounds();
  820. // Viewports
  821. 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.
  822. static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
  823. static void UpdateViewportsNewFrame();
  824. static void UpdateViewportsEndFrame();
  825. static void UpdateSelectWindowViewport(ImGuiWindow* window);
  826. static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
  827. static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
  828. static void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* viewport);
  829. static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
  830. static int FindPlatformMonitorForPos(const ImVec2& pos);
  831. static int FindPlatformMonitorForRect(const ImRect& r);
  832. static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
  833. }
  834. //-----------------------------------------------------------------------------
  835. // [SECTION] CONTEXT AND MEMORY ALLOCATORS
  836. //-----------------------------------------------------------------------------
  837. // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
  838. // ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
  839. // 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
  840. // SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
  841. // In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
  842. // 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
  843. // If you want thread-safety to allow N threads to access N different contexts, you can:
  844. // - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
  845. // struct ImGuiContext;
  846. // extern thread_local ImGuiContext* MyImGuiTLS;
  847. // #define GImGui MyImGuiTLS
  848. // And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
  849. // - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  850. // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
  851. #ifndef GImGui
  852. ImGuiContext* GImGui = NULL;
  853. #endif
  854. // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
  855. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
  856. // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
  857. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
  858. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
  859. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
  860. #else
  861. static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
  862. static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
  863. #endif
  864. static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
  865. static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
  866. static void* GImAllocatorUserData = NULL;
  867. //-----------------------------------------------------------------------------
  868. // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
  869. //-----------------------------------------------------------------------------
  870. ImGuiStyle::ImGuiStyle()
  871. {
  872. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  873. WindowPadding = ImVec2(8,8); // Padding within a window
  874. WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
  875. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  876. WindowMinSize = ImVec2(32,32); // Minimum window size
  877. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  878. WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
  879. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  880. ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  881. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
  882. PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  883. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  884. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  885. FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
  886. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  887. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  888. 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!
  889. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  890. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
  891. ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  892. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  893. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  894. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  895. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
  896. TabBorderSize = 0.0f; // Thickness of border around tabs.
  897. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
  898. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  899. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
  900. 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.
  901. 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.
  902. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
  903. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
  904. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
  905. 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.
  906. CircleSegmentMaxError = 1.60f; // 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.
  907. // Default theme
  908. ImGui::StyleColorsDark(this);
  909. }
  910. // 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.
  911. // 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.
  912. void ImGuiStyle::ScaleAllSizes(float scale_factor)
  913. {
  914. WindowPadding = ImFloor(WindowPadding * scale_factor);
  915. WindowRounding = ImFloor(WindowRounding * scale_factor);
  916. WindowMinSize = ImFloor(WindowMinSize * scale_factor);
  917. ChildRounding = ImFloor(ChildRounding * scale_factor);
  918. PopupRounding = ImFloor(PopupRounding * scale_factor);
  919. FramePadding = ImFloor(FramePadding * scale_factor);
  920. FrameRounding = ImFloor(FrameRounding * scale_factor);
  921. ItemSpacing = ImFloor(ItemSpacing * scale_factor);
  922. ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
  923. TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
  924. IndentSpacing = ImFloor(IndentSpacing * scale_factor);
  925. ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
  926. ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
  927. ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
  928. GrabMinSize = ImFloor(GrabMinSize * scale_factor);
  929. GrabRounding = ImFloor(GrabRounding * scale_factor);
  930. TabRounding = ImFloor(TabRounding * scale_factor);
  931. DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
  932. DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
  933. MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
  934. }
  935. ImGuiIO::ImGuiIO()
  936. {
  937. // Most fields are initialized with zero
  938. memset(this, 0, sizeof(*this));
  939. 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.
  940. // Settings
  941. ConfigFlags = ImGuiConfigFlags_None;
  942. BackendFlags = ImGuiBackendFlags_None;
  943. DisplaySize = ImVec2(-1.0f, -1.0f);
  944. DeltaTime = 1.0f/60.0f;
  945. IniSavingRate = 5.0f;
  946. IniFilename = "imgui.ini";
  947. LogFilename = "imgui_log.txt";
  948. MouseDoubleClickTime = 0.30f;
  949. MouseDoubleClickMaxDist = 6.0f;
  950. for (int i = 0; i < ImGuiKey_COUNT; i++)
  951. KeyMap[i] = -1;
  952. KeyRepeatDelay = 0.275f;
  953. KeyRepeatRate = 0.050f;
  954. UserData = NULL;
  955. Fonts = NULL;
  956. FontGlobalScale = 1.0f;
  957. FontDefault = NULL;
  958. FontAllowUserScaling = false;
  959. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  960. // Docking options (when ImGuiConfigFlags_DockingEnable is set)
  961. ConfigDockingNoSplit = false;
  962. ConfigDockingWithShift = false;
  963. ConfigDockingAlwaysTabBar = false;
  964. ConfigDockingTransparentPayload = false;
  965. // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
  966. ConfigViewportsNoAutoMerge = false;
  967. ConfigViewportsNoTaskBarIcon = false;
  968. ConfigViewportsNoDecoration = true;
  969. ConfigViewportsNoDefaultParent = false;
  970. // Miscellaneous options
  971. MouseDrawCursor = false;
  972. #ifdef __APPLE__
  973. ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
  974. #else
  975. ConfigMacOSXBehaviors = false;
  976. #endif
  977. ConfigInputTextCursorBlink = true;
  978. ConfigWindowsResizeFromEdges = true;
  979. ConfigWindowsMoveFromTitleBarOnly = false;
  980. ConfigWindowsMemoryCompactTimer = 60.0f;
  981. // Platform Functions
  982. BackendPlatformName = BackendRendererName = NULL;
  983. BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
  984. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  985. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  986. ClipboardUserData = NULL;
  987. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  988. RenderDrawListsFn = NULL;
  989. #endif
  990. // Input (NB: we already have memset zero the entire structure!)
  991. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  992. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  993. MouseDragThreshold = 6.0f;
  994. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  995. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  996. for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
  997. }
  998. // Pass in translated ASCII characters for text input.
  999. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  1000. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  1001. void ImGuiIO::AddInputCharacter(unsigned int c)
  1002. {
  1003. InputQueueCharacters.push_back(c > 0 && c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
  1004. }
  1005. // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
  1006. // we should save the high surrogate.
  1007. void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
  1008. {
  1009. if ((c & 0xFC00) == 0xD800) // High surrogate, must save
  1010. {
  1011. if (InputQueueSurrogate != 0)
  1012. InputQueueCharacters.push_back(0xFFFD);
  1013. InputQueueSurrogate = c;
  1014. return;
  1015. }
  1016. ImWchar cp = c;
  1017. if (InputQueueSurrogate != 0)
  1018. {
  1019. if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
  1020. InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
  1021. else if (IM_UNICODE_CODEPOINT_MAX == (0xFFFF)) // Codepoint will not fit in ImWchar (extra parenthesis around 0xFFFF somehow fixes -Wunreachable-code with Clang)
  1022. cp = IM_UNICODE_CODEPOINT_INVALID;
  1023. else
  1024. cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
  1025. InputQueueSurrogate = 0;
  1026. }
  1027. InputQueueCharacters.push_back(cp);
  1028. }
  1029. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  1030. {
  1031. while (*utf8_chars != 0)
  1032. {
  1033. unsigned int c = 0;
  1034. utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
  1035. if (c > 0)
  1036. InputQueueCharacters.push_back((ImWchar)c);
  1037. }
  1038. }
  1039. void ImGuiIO::ClearInputCharacters()
  1040. {
  1041. InputQueueCharacters.resize(0);
  1042. }
  1043. //-----------------------------------------------------------------------------
  1044. // [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
  1045. //-----------------------------------------------------------------------------
  1046. ImVec2 ImBezierClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
  1047. {
  1048. IM_ASSERT(num_segments > 0); // Use ImBezierClosestPointCasteljau()
  1049. ImVec2 p_last = p1;
  1050. ImVec2 p_closest;
  1051. float p_closest_dist2 = FLT_MAX;
  1052. float t_step = 1.0f / (float)num_segments;
  1053. for (int i_step = 1; i_step <= num_segments; i_step++)
  1054. {
  1055. ImVec2 p_current = ImBezierCalc(p1, p2, p3, p4, t_step * i_step);
  1056. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1057. float dist2 = ImLengthSqr(p - p_line);
  1058. if (dist2 < p_closest_dist2)
  1059. {
  1060. p_closest = p_line;
  1061. p_closest_dist2 = dist2;
  1062. }
  1063. p_last = p_current;
  1064. }
  1065. return p_closest;
  1066. }
  1067. // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
  1068. static void BezierClosestPointCasteljauStep(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)
  1069. {
  1070. float dx = x4 - x1;
  1071. float dy = y4 - y1;
  1072. float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
  1073. float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
  1074. d2 = (d2 >= 0) ? d2 : -d2;
  1075. d3 = (d3 >= 0) ? d3 : -d3;
  1076. if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy))
  1077. {
  1078. ImVec2 p_current(x4, y4);
  1079. ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
  1080. float dist2 = ImLengthSqr(p - p_line);
  1081. if (dist2 < p_closest_dist2)
  1082. {
  1083. p_closest = p_line;
  1084. p_closest_dist2 = dist2;
  1085. }
  1086. p_last = p_current;
  1087. }
  1088. else if (level < 10)
  1089. {
  1090. float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f;
  1091. float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f;
  1092. float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f;
  1093. float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f;
  1094. float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f;
  1095. float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f;
  1096. BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
  1097. BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
  1098. }
  1099. }
  1100. // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
  1101. // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
  1102. ImVec2 ImBezierClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
  1103. {
  1104. IM_ASSERT(tess_tol > 0.0f);
  1105. ImVec2 p_last = p1;
  1106. ImVec2 p_closest;
  1107. float p_closest_dist2 = FLT_MAX;
  1108. BezierClosestPointCasteljauStep(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);
  1109. return p_closest;
  1110. }
  1111. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  1112. {
  1113. ImVec2 ap = p - a;
  1114. ImVec2 ab_dir = b - a;
  1115. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  1116. if (dot < 0.0f)
  1117. return a;
  1118. float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
  1119. if (dot > ab_len_sqr)
  1120. return b;
  1121. return a + ab_dir * dot / ab_len_sqr;
  1122. }
  1123. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1124. {
  1125. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  1126. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  1127. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  1128. return ((b1 == b2) && (b2 == b3));
  1129. }
  1130. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  1131. {
  1132. ImVec2 v0 = b - a;
  1133. ImVec2 v1 = c - a;
  1134. ImVec2 v2 = p - a;
  1135. const float denom = v0.x * v1.y - v1.x * v0.y;
  1136. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  1137. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  1138. out_u = 1.0f - out_v - out_w;
  1139. }
  1140. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  1141. {
  1142. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  1143. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  1144. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  1145. float dist2_ab = ImLengthSqr(p - proj_ab);
  1146. float dist2_bc = ImLengthSqr(p - proj_bc);
  1147. float dist2_ca = ImLengthSqr(p - proj_ca);
  1148. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  1149. if (m == dist2_ab)
  1150. return proj_ab;
  1151. if (m == dist2_bc)
  1152. return proj_bc;
  1153. return proj_ca;
  1154. }
  1155. //-----------------------------------------------------------------------------
  1156. // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
  1157. //-----------------------------------------------------------------------------
  1158. // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
  1159. int ImStricmp(const char* str1, const char* str2)
  1160. {
  1161. int d;
  1162. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  1163. return d;
  1164. }
  1165. int ImStrnicmp(const char* str1, const char* str2, size_t count)
  1166. {
  1167. int d = 0;
  1168. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  1169. return d;
  1170. }
  1171. void ImStrncpy(char* dst, const char* src, size_t count)
  1172. {
  1173. if (count < 1)
  1174. return;
  1175. if (count > 1)
  1176. strncpy(dst, src, count - 1);
  1177. dst[count - 1] = 0;
  1178. }
  1179. char* ImStrdup(const char* str)
  1180. {
  1181. size_t len = strlen(str);
  1182. void* buf = IM_ALLOC(len + 1);
  1183. return (char*)memcpy(buf, (const void*)str, len + 1);
  1184. }
  1185. char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
  1186. {
  1187. size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
  1188. size_t src_size = strlen(src) + 1;
  1189. if (dst_buf_size < src_size)
  1190. {
  1191. IM_FREE(dst);
  1192. dst = (char*)IM_ALLOC(src_size);
  1193. if (p_dst_size)
  1194. *p_dst_size = src_size;
  1195. }
  1196. return (char*)memcpy(dst, (const void*)src, src_size);
  1197. }
  1198. const char* ImStrchrRange(const char* str, const char* str_end, char c)
  1199. {
  1200. const char* p = (const char*)memchr(str, (int)c, str_end - str);
  1201. return p;
  1202. }
  1203. int ImStrlenW(const ImWchar* str)
  1204. {
  1205. //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
  1206. int n = 0;
  1207. while (*str++) n++;
  1208. return n;
  1209. }
  1210. // Find end-of-line. Return pointer will point to either first \n, either str_end.
  1211. const char* ImStreolRange(const char* str, const char* str_end)
  1212. {
  1213. const char* p = (const char*)memchr(str, '\n', str_end - str);
  1214. return p ? p : str_end;
  1215. }
  1216. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  1217. {
  1218. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  1219. buf_mid_line--;
  1220. return buf_mid_line;
  1221. }
  1222. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  1223. {
  1224. if (!needle_end)
  1225. needle_end = needle + strlen(needle);
  1226. const char un0 = (char)toupper(*needle);
  1227. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  1228. {
  1229. if (toupper(*haystack) == un0)
  1230. {
  1231. const char* b = needle + 1;
  1232. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  1233. if (toupper(*a) != toupper(*b))
  1234. break;
  1235. if (b == needle_end)
  1236. return haystack;
  1237. }
  1238. haystack++;
  1239. }
  1240. return NULL;
  1241. }
  1242. // 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.
  1243. void ImStrTrimBlanks(char* buf)
  1244. {
  1245. char* p = buf;
  1246. while (p[0] == ' ' || p[0] == '\t') // Leading blanks
  1247. p++;
  1248. char* p_start = p;
  1249. while (*p != 0) // Find end of string
  1250. p++;
  1251. while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
  1252. p--;
  1253. if (p_start != buf) // Copy memory if we had leading blanks
  1254. memmove(buf, p_start, p - p_start);
  1255. buf[p - p_start] = 0; // Zero terminate
  1256. }
  1257. const char* ImStrSkipBlank(const char* str)
  1258. {
  1259. while (str[0] == ' ' || str[0] == '\t')
  1260. str++;
  1261. return str;
  1262. }
  1263. // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  1264. // 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.
  1265. // B) When buf==NULL vsnprintf() will return the output size.
  1266. #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1267. // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
  1268. // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1269. // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
  1270. // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
  1271. #ifdef IMGUI_USE_STB_SPRINTF
  1272. #define STB_SPRINTF_IMPLEMENTATION
  1273. #include "stb_sprintf.h"
  1274. #endif
  1275. #if defined(_MSC_VER) && !defined(vsnprintf)
  1276. #define vsnprintf _vsnprintf
  1277. #endif
  1278. int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
  1279. {
  1280. va_list args;
  1281. va_start(args, fmt);
  1282. #ifdef IMGUI_USE_STB_SPRINTF
  1283. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1284. #else
  1285. int w = vsnprintf(buf, buf_size, fmt, args);
  1286. #endif
  1287. va_end(args);
  1288. if (buf == NULL)
  1289. return w;
  1290. if (w == -1 || w >= (int)buf_size)
  1291. w = (int)buf_size - 1;
  1292. buf[w] = 0;
  1293. return w;
  1294. }
  1295. int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
  1296. {
  1297. #ifdef IMGUI_USE_STB_SPRINTF
  1298. int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
  1299. #else
  1300. int w = vsnprintf(buf, buf_size, fmt, args);
  1301. #endif
  1302. if (buf == NULL)
  1303. return w;
  1304. if (w == -1 || w >= (int)buf_size)
  1305. w = (int)buf_size - 1;
  1306. buf[w] = 0;
  1307. return w;
  1308. }
  1309. #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
  1310. // CRC32 needs a 1KB lookup table (not cache friendly)
  1311. // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
  1312. // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
  1313. static const ImU32 GCrc32LookupTable[256] =
  1314. {
  1315. 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
  1316. 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
  1317. 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
  1318. 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
  1319. 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
  1320. 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
  1321. 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
  1322. 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
  1323. 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
  1324. 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
  1325. 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
  1326. 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
  1327. 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
  1328. 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
  1329. 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
  1330. 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
  1331. };
  1332. // Known size hash
  1333. // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
  1334. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1335. ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
  1336. {
  1337. ImU32 crc = ~seed;
  1338. const unsigned char* data = (const unsigned char*)data_p;
  1339. const ImU32* crc32_lut = GCrc32LookupTable;
  1340. while (data_size-- != 0)
  1341. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
  1342. return ~crc;
  1343. }
  1344. // Zero-terminated string hash, with support for ### to reset back to seed value
  1345. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  1346. // Because this syntax is rarely used we are optimizing for the common case.
  1347. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  1348. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
  1349. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  1350. ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
  1351. {
  1352. seed = ~seed;
  1353. ImU32 crc = seed;
  1354. const unsigned char* data = (const unsigned char*)data_p;
  1355. const ImU32* crc32_lut = GCrc32LookupTable;
  1356. if (data_size != 0)
  1357. {
  1358. while (data_size-- != 0)
  1359. {
  1360. unsigned char c = *data++;
  1361. if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
  1362. crc = seed;
  1363. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1364. }
  1365. }
  1366. else
  1367. {
  1368. while (unsigned char c = *data++)
  1369. {
  1370. if (c == '#' && data[0] == '#' && data[1] == '#')
  1371. crc = seed;
  1372. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1373. }
  1374. }
  1375. return ~crc;
  1376. }
  1377. //-----------------------------------------------------------------------------
  1378. // [SECTION] MISC HELPERS/UTILITIES (File functions)
  1379. //-----------------------------------------------------------------------------
  1380. // Default file functions
  1381. #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1382. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
  1383. #ifndef WIN32_LEAN_AND_MEAN
  1384. #define WIN32_LEAN_AND_MEAN
  1385. #endif
  1386. #ifndef __MINGW32__
  1387. #include <Windows.h>
  1388. #else
  1389. #include <windows.h>
  1390. #endif
  1391. #endif
  1392. ImFileHandle ImFileOpen(const char* filename, const char* mode)
  1393. {
  1394. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
  1395. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
  1396. // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
  1397. const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
  1398. const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
  1399. ImVector<ImWchar> buf;
  1400. buf.resize(filename_wsize + mode_wsize);
  1401. ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
  1402. ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
  1403. return _wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
  1404. #else
  1405. return fopen(filename, mode);
  1406. #endif
  1407. }
  1408. // 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.
  1409. bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
  1410. 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; }
  1411. ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
  1412. ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
  1413. #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
  1414. // Helper: Load file content into memory
  1415. // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
  1416. void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
  1417. {
  1418. IM_ASSERT(filename && mode);
  1419. if (out_file_size)
  1420. *out_file_size = 0;
  1421. ImFileHandle f;
  1422. if ((f = ImFileOpen(filename, mode)) == NULL)
  1423. return NULL;
  1424. size_t file_size = (size_t)ImFileGetSize(f);
  1425. if (file_size == (size_t)-1)
  1426. {
  1427. ImFileClose(f);
  1428. return NULL;
  1429. }
  1430. void* file_data = IM_ALLOC(file_size + padding_bytes);
  1431. if (file_data == NULL)
  1432. {
  1433. ImFileClose(f);
  1434. return NULL;
  1435. }
  1436. if (ImFileRead(file_data, 1, file_size, f) != file_size)
  1437. {
  1438. ImFileClose(f);
  1439. IM_FREE(file_data);
  1440. return NULL;
  1441. }
  1442. if (padding_bytes > 0)
  1443. memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
  1444. ImFileClose(f);
  1445. if (out_file_size)
  1446. *out_file_size = file_size;
  1447. return file_data;
  1448. }
  1449. //-----------------------------------------------------------------------------
  1450. // [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
  1451. //-----------------------------------------------------------------------------
  1452. // Convert UTF-8 to 32-bit character, process single character input.
  1453. // Based on stb_from_utf8() from github.com/nothings/stb/
  1454. // We handle UTF-8 decoding error by skipping forward.
  1455. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1456. {
  1457. unsigned int c = (unsigned int)-1;
  1458. const unsigned char* str = (const unsigned char*)in_text;
  1459. if (!(*str & 0x80))
  1460. {
  1461. c = (unsigned int)(*str++);
  1462. *out_char = c;
  1463. return 1;
  1464. }
  1465. if ((*str & 0xe0) == 0xc0)
  1466. {
  1467. *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
  1468. if (in_text_end && in_text_end - (const char*)str < 2) return 1;
  1469. if (*str < 0xc2) return 2;
  1470. c = (unsigned int)((*str++ & 0x1f) << 6);
  1471. if ((*str & 0xc0) != 0x80) return 2;
  1472. c += (*str++ & 0x3f);
  1473. *out_char = c;
  1474. return 2;
  1475. }
  1476. if ((*str & 0xf0) == 0xe0)
  1477. {
  1478. *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
  1479. if (in_text_end && in_text_end - (const char*)str < 3) return 1;
  1480. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
  1481. if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
  1482. c = (unsigned int)((*str++ & 0x0f) << 12);
  1483. if ((*str & 0xc0) != 0x80) return 3;
  1484. c += (unsigned int)((*str++ & 0x3f) << 6);
  1485. if ((*str & 0xc0) != 0x80) return 3;
  1486. c += (*str++ & 0x3f);
  1487. *out_char = c;
  1488. return 3;
  1489. }
  1490. if ((*str & 0xf8) == 0xf0)
  1491. {
  1492. *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string
  1493. if (in_text_end && in_text_end - (const char*)str < 4) return 1;
  1494. if (*str > 0xf4) return 4;
  1495. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
  1496. if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
  1497. c = (unsigned int)((*str++ & 0x07) << 18);
  1498. if ((*str & 0xc0) != 0x80) return 4;
  1499. c += (unsigned int)((*str++ & 0x3f) << 12);
  1500. if ((*str & 0xc0) != 0x80) return 4;
  1501. c += (unsigned int)((*str++ & 0x3f) << 6);
  1502. if ((*str & 0xc0) != 0x80) return 4;
  1503. c += (*str++ & 0x3f);
  1504. // utf-8 encodings of values used in surrogate pairs are invalid
  1505. if ((c & 0xFFFFF800) == 0xD800) return 4;
  1506. // If codepoint does not fit in ImWchar, use replacement character U+FFFD instead
  1507. if (c > IM_UNICODE_CODEPOINT_MAX) c = IM_UNICODE_CODEPOINT_INVALID;
  1508. *out_char = c;
  1509. return 4;
  1510. }
  1511. *out_char = 0;
  1512. return 0;
  1513. }
  1514. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1515. {
  1516. ImWchar* buf_out = buf;
  1517. ImWchar* buf_end = buf + buf_size;
  1518. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1519. {
  1520. unsigned int c;
  1521. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1522. if (c == 0)
  1523. break;
  1524. *buf_out++ = (ImWchar)c;
  1525. }
  1526. *buf_out = 0;
  1527. if (in_text_remaining)
  1528. *in_text_remaining = in_text;
  1529. return (int)(buf_out - buf);
  1530. }
  1531. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1532. {
  1533. int char_count = 0;
  1534. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1535. {
  1536. unsigned int c;
  1537. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1538. if (c == 0)
  1539. break;
  1540. char_count++;
  1541. }
  1542. return char_count;
  1543. }
  1544. // Based on stb_to_utf8() from github.com/nothings/stb/
  1545. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  1546. {
  1547. if (c < 0x80)
  1548. {
  1549. buf[0] = (char)c;
  1550. return 1;
  1551. }
  1552. if (c < 0x800)
  1553. {
  1554. if (buf_size < 2) return 0;
  1555. buf[0] = (char)(0xc0 + (c >> 6));
  1556. buf[1] = (char)(0x80 + (c & 0x3f));
  1557. return 2;
  1558. }
  1559. if (c < 0x10000)
  1560. {
  1561. if (buf_size < 3) return 0;
  1562. buf[0] = (char)(0xe0 + (c >> 12));
  1563. buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
  1564. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1565. return 3;
  1566. }
  1567. if (c <= 0x10FFFF)
  1568. {
  1569. if (buf_size < 4) return 0;
  1570. buf[0] = (char)(0xf0 + (c >> 18));
  1571. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1572. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1573. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1574. return 4;
  1575. }
  1576. // Invalid code point, the max unicode is 0x10FFFF
  1577. return 0;
  1578. }
  1579. // Not optimal but we very rarely use this function.
  1580. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
  1581. {
  1582. unsigned int dummy = 0;
  1583. return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
  1584. }
  1585. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1586. {
  1587. if (c < 0x80) return 1;
  1588. if (c < 0x800) return 2;
  1589. if (c < 0x10000) return 3;
  1590. if (c <= 0x10FFFF) return 4;
  1591. return 3;
  1592. }
  1593. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1594. {
  1595. char* buf_out = buf;
  1596. const char* buf_end = buf + buf_size;
  1597. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1598. {
  1599. unsigned int c = (unsigned int)(*in_text++);
  1600. if (c < 0x80)
  1601. *buf_out++ = (char)c;
  1602. else
  1603. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
  1604. }
  1605. *buf_out = 0;
  1606. return (int)(buf_out - buf);
  1607. }
  1608. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1609. {
  1610. int bytes_count = 0;
  1611. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1612. {
  1613. unsigned int c = (unsigned int)(*in_text++);
  1614. if (c < 0x80)
  1615. bytes_count++;
  1616. else
  1617. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1618. }
  1619. return bytes_count;
  1620. }
  1621. //-----------------------------------------------------------------------------
  1622. // [SECTION] MISC HELPERS/UTILTIES (Color functions)
  1623. // Note: The Convert functions are early design which are not consistent with other API.
  1624. //-----------------------------------------------------------------------------
  1625. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1626. {
  1627. float s = 1.0f/255.0f;
  1628. return ImVec4(
  1629. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1630. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1631. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1632. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1633. }
  1634. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1635. {
  1636. ImU32 out;
  1637. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1638. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1639. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1640. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1641. return out;
  1642. }
  1643. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1644. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1645. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1646. {
  1647. float K = 0.f;
  1648. if (g < b)
  1649. {
  1650. ImSwap(g, b);
  1651. K = -1.f;
  1652. }
  1653. if (r < g)
  1654. {
  1655. ImSwap(r, g);
  1656. K = -2.f / 6.f - K;
  1657. }
  1658. const float chroma = r - (g < b ? g : b);
  1659. out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
  1660. out_s = chroma / (r + 1e-20f);
  1661. out_v = r;
  1662. }
  1663. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1664. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1665. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1666. {
  1667. if (s == 0.0f)
  1668. {
  1669. // gray
  1670. out_r = out_g = out_b = v;
  1671. return;
  1672. }
  1673. h = ImFmod(h, 1.0f) / (60.0f/360.0f);
  1674. int i = (int)h;
  1675. float f = h - (float)i;
  1676. float p = v * (1.0f - s);
  1677. float q = v * (1.0f - s * f);
  1678. float t = v * (1.0f - s * (1.0f - f));
  1679. switch (i)
  1680. {
  1681. case 0: out_r = v; out_g = t; out_b = p; break;
  1682. case 1: out_r = q; out_g = v; out_b = p; break;
  1683. case 2: out_r = p; out_g = v; out_b = t; break;
  1684. case 3: out_r = p; out_g = q; out_b = v; break;
  1685. case 4: out_r = t; out_g = p; out_b = v; break;
  1686. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1687. }
  1688. }
  1689. //-----------------------------------------------------------------------------
  1690. // [SECTION] ImGuiStorage
  1691. // Helper: Key->value storage
  1692. //-----------------------------------------------------------------------------
  1693. // std::lower_bound but without the bullshit
  1694. static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
  1695. {
  1696. ImGuiStorage::ImGuiStoragePair* first = data.Data;
  1697. ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
  1698. size_t count = (size_t)(last - first);
  1699. while (count > 0)
  1700. {
  1701. size_t count2 = count >> 1;
  1702. ImGuiStorage::ImGuiStoragePair* mid = first + count2;
  1703. if (mid->key < key)
  1704. {
  1705. first = ++mid;
  1706. count -= count2 + 1;
  1707. }
  1708. else
  1709. {
  1710. count = count2;
  1711. }
  1712. }
  1713. return first;
  1714. }
  1715. // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
  1716. void ImGuiStorage::BuildSortByKey()
  1717. {
  1718. struct StaticFunc
  1719. {
  1720. static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
  1721. {
  1722. // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
  1723. if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
  1724. if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
  1725. return 0;
  1726. }
  1727. };
  1728. if (Data.Size > 1)
  1729. ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
  1730. }
  1731. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1732. {
  1733. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1734. if (it == Data.end() || it->key != key)
  1735. return default_val;
  1736. return it->val_i;
  1737. }
  1738. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1739. {
  1740. return GetInt(key, default_val ? 1 : 0) != 0;
  1741. }
  1742. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1743. {
  1744. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1745. if (it == Data.end() || it->key != key)
  1746. return default_val;
  1747. return it->val_f;
  1748. }
  1749. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1750. {
  1751. ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
  1752. if (it == Data.end() || it->key != key)
  1753. return NULL;
  1754. return it->val_p;
  1755. }
  1756. // 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.
  1757. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1758. {
  1759. ImGuiStoragePair* it = LowerBound(Data, key);
  1760. if (it == Data.end() || it->key != key)
  1761. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1762. return &it->val_i;
  1763. }
  1764. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1765. {
  1766. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1767. }
  1768. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1769. {
  1770. ImGuiStoragePair* it = LowerBound(Data, key);
  1771. if (it == Data.end() || it->key != key)
  1772. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1773. return &it->val_f;
  1774. }
  1775. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1776. {
  1777. ImGuiStoragePair* it = LowerBound(Data, key);
  1778. if (it == Data.end() || it->key != key)
  1779. it = Data.insert(it, ImGuiStoragePair(key, default_val));
  1780. return &it->val_p;
  1781. }
  1782. // 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)
  1783. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1784. {
  1785. ImGuiStoragePair* it = LowerBound(Data, key);
  1786. if (it == Data.end() || it->key != key)
  1787. {
  1788. Data.insert(it, ImGuiStoragePair(key, val));
  1789. return;
  1790. }
  1791. it->val_i = val;
  1792. }
  1793. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1794. {
  1795. SetInt(key, val ? 1 : 0);
  1796. }
  1797. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1798. {
  1799. ImGuiStoragePair* it = LowerBound(Data, key);
  1800. if (it == Data.end() || it->key != key)
  1801. {
  1802. Data.insert(it, ImGuiStoragePair(key, val));
  1803. return;
  1804. }
  1805. it->val_f = val;
  1806. }
  1807. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1808. {
  1809. ImGuiStoragePair* it = LowerBound(Data, key);
  1810. if (it == Data.end() || it->key != key)
  1811. {
  1812. Data.insert(it, ImGuiStoragePair(key, val));
  1813. return;
  1814. }
  1815. it->val_p = val;
  1816. }
  1817. void ImGuiStorage::SetAllInt(int v)
  1818. {
  1819. for (int i = 0; i < Data.Size; i++)
  1820. Data[i].val_i = v;
  1821. }
  1822. //-----------------------------------------------------------------------------
  1823. // [SECTION] ImGuiTextFilter
  1824. //-----------------------------------------------------------------------------
  1825. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1826. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1827. {
  1828. if (default_filter)
  1829. {
  1830. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1831. Build();
  1832. }
  1833. else
  1834. {
  1835. InputBuf[0] = 0;
  1836. CountGrep = 0;
  1837. }
  1838. }
  1839. bool ImGuiTextFilter::Draw(const char* label, float width)
  1840. {
  1841. if (width != 0.0f)
  1842. ImGui::SetNextItemWidth(width);
  1843. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1844. if (value_changed)
  1845. Build();
  1846. return value_changed;
  1847. }
  1848. void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
  1849. {
  1850. out->resize(0);
  1851. const char* wb = b;
  1852. const char* we = wb;
  1853. while (we < e)
  1854. {
  1855. if (*we == separator)
  1856. {
  1857. out->push_back(ImGuiTextRange(wb, we));
  1858. wb = we + 1;
  1859. }
  1860. we++;
  1861. }
  1862. if (wb != we)
  1863. out->push_back(ImGuiTextRange(wb, we));
  1864. }
  1865. void ImGuiTextFilter::Build()
  1866. {
  1867. Filters.resize(0);
  1868. ImGuiTextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
  1869. input_range.split(',', &Filters);
  1870. CountGrep = 0;
  1871. for (int i = 0; i != Filters.Size; i++)
  1872. {
  1873. ImGuiTextRange& f = Filters[i];
  1874. while (f.b < f.e && ImCharIsBlankA(f.b[0]))
  1875. f.b++;
  1876. while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
  1877. f.e--;
  1878. if (f.empty())
  1879. continue;
  1880. if (Filters[i].b[0] != '-')
  1881. CountGrep += 1;
  1882. }
  1883. }
  1884. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1885. {
  1886. if (Filters.empty())
  1887. return true;
  1888. if (text == NULL)
  1889. text = "";
  1890. for (int i = 0; i != Filters.Size; i++)
  1891. {
  1892. const ImGuiTextRange& f = Filters[i];
  1893. if (f.empty())
  1894. continue;
  1895. if (f.b[0] == '-')
  1896. {
  1897. // Subtract
  1898. if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
  1899. return false;
  1900. }
  1901. else
  1902. {
  1903. // Grep
  1904. if (ImStristr(text, text_end, f.b, f.e) != NULL)
  1905. return true;
  1906. }
  1907. }
  1908. // Implicit * grep
  1909. if (CountGrep == 0)
  1910. return true;
  1911. return false;
  1912. }
  1913. //-----------------------------------------------------------------------------
  1914. // [SECTION] ImGuiTextBuffer
  1915. //-----------------------------------------------------------------------------
  1916. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1917. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1918. #ifndef va_copy
  1919. #if defined(__GNUC__) || defined(__clang__)
  1920. #define va_copy(dest, src) __builtin_va_copy(dest, src)
  1921. #else
  1922. #define va_copy(dest, src) (dest = src)
  1923. #endif
  1924. #endif
  1925. char ImGuiTextBuffer::EmptyString[1] = { 0 };
  1926. void ImGuiTextBuffer::append(const char* str, const char* str_end)
  1927. {
  1928. int len = str_end ? (int)(str_end - str) : (int)strlen(str);
  1929. // Add zero-terminator the first time
  1930. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  1931. const int needed_sz = write_off + len;
  1932. if (write_off + len >= Buf.Capacity)
  1933. {
  1934. int new_capacity = Buf.Capacity * 2;
  1935. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  1936. }
  1937. Buf.resize(needed_sz);
  1938. memcpy(&Buf[write_off - 1], str, (size_t)len);
  1939. Buf[write_off - 1 + len] = 0;
  1940. }
  1941. void ImGuiTextBuffer::appendf(const char* fmt, ...)
  1942. {
  1943. va_list args;
  1944. va_start(args, fmt);
  1945. appendfv(fmt, args);
  1946. va_end(args);
  1947. }
  1948. // Helper: Text buffer for logging/accumulating text
  1949. void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
  1950. {
  1951. va_list args_copy;
  1952. va_copy(args_copy, args);
  1953. int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1954. if (len <= 0)
  1955. {
  1956. va_end(args_copy);
  1957. return;
  1958. }
  1959. // Add zero-terminator the first time
  1960. const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
  1961. const int needed_sz = write_off + len;
  1962. if (write_off + len >= Buf.Capacity)
  1963. {
  1964. int new_capacity = Buf.Capacity * 2;
  1965. Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
  1966. }
  1967. Buf.resize(needed_sz);
  1968. ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
  1969. va_end(args_copy);
  1970. }
  1971. //-----------------------------------------------------------------------------
  1972. // [SECTION] ImGuiListClipper
  1973. // This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
  1974. // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
  1975. //-----------------------------------------------------------------------------
  1976. // Helper to calculate coarse clipping of large list of evenly sized items.
  1977. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
  1978. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  1979. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  1980. {
  1981. ImGuiContext& g = *GImGui;
  1982. ImGuiWindow* window = g.CurrentWindow;
  1983. if (g.LogEnabled)
  1984. {
  1985. // If logging is active, do not perform any clipping
  1986. *out_items_display_start = 0;
  1987. *out_items_display_end = items_count;
  1988. return;
  1989. }
  1990. if (window->SkipItems)
  1991. {
  1992. *out_items_display_start = *out_items_display_end = 0;
  1993. return;
  1994. }
  1995. // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
  1996. ImRect unclipped_rect = window->ClipRect;
  1997. if (g.NavMoveRequest)
  1998. unclipped_rect.Add(g.NavScoringRectScreen);
  1999. const ImVec2 pos = window->DC.CursorPos;
  2000. int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
  2001. int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
  2002. // When performing a navigation request, ensure we have one item extra in the direction we are moving to
  2003. if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
  2004. start--;
  2005. if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
  2006. end++;
  2007. start = ImClamp(start, 0, items_count);
  2008. end = ImClamp(end + 1, start, items_count);
  2009. *out_items_display_start = start;
  2010. *out_items_display_end = end;
  2011. }
  2012. static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
  2013. {
  2014. // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
  2015. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
  2016. // The clipper should probably have a 4th step to display the last item in a regular manner.
  2017. ImGuiContext& g = *GImGui;
  2018. ImGuiWindow* window = g.CurrentWindow;
  2019. window->DC.CursorPos.y = pos_y;
  2020. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
  2021. 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.
  2022. 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.
  2023. if (ImGuiColumns* columns = window->DC.CurrentColumns)
  2024. columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  2025. }
  2026. // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
  2027. // Use case B: Begin() called from constructor with items_height>0
  2028. // 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.
  2029. void ImGuiListClipper::Begin(int count, float items_height)
  2030. {
  2031. ImGuiContext& g = *GImGui;
  2032. ImGuiWindow* window = g.CurrentWindow;
  2033. StartPosY = window->DC.CursorPos.y;
  2034. ItemsHeight = items_height;
  2035. ItemsCount = count;
  2036. StepNo = 0;
  2037. DisplayEnd = DisplayStart = -1;
  2038. if (ItemsHeight > 0.0f)
  2039. {
  2040. ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
  2041. if (DisplayStart > 0)
  2042. SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
  2043. StepNo = 2;
  2044. }
  2045. }
  2046. void ImGuiListClipper::End()
  2047. {
  2048. if (ItemsCount < 0)
  2049. return;
  2050. // 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.
  2051. if (ItemsCount < INT_MAX)
  2052. SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
  2053. ItemsCount = -1;
  2054. StepNo = 3;
  2055. }
  2056. bool ImGuiListClipper::Step()
  2057. {
  2058. ImGuiContext& g = *GImGui;
  2059. ImGuiWindow* window = g.CurrentWindow;
  2060. if (ItemsCount == 0 || window->SkipItems)
  2061. {
  2062. ItemsCount = -1;
  2063. return false;
  2064. }
  2065. if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
  2066. {
  2067. DisplayStart = 0;
  2068. DisplayEnd = 1;
  2069. StartPosY = window->DC.CursorPos.y;
  2070. StepNo = 1;
  2071. return true;
  2072. }
  2073. if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
  2074. {
  2075. if (ItemsCount == 1) { ItemsCount = -1; return false; }
  2076. float items_height = window->DC.CursorPos.y - StartPosY;
  2077. IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
  2078. Begin(ItemsCount - 1, items_height);
  2079. DisplayStart++;
  2080. DisplayEnd++;
  2081. StepNo = 3;
  2082. return true;
  2083. }
  2084. if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
  2085. {
  2086. IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
  2087. StepNo = 3;
  2088. return true;
  2089. }
  2090. if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
  2091. End();
  2092. return false;
  2093. }
  2094. //-----------------------------------------------------------------------------
  2095. // [SECTION] STYLING
  2096. //-----------------------------------------------------------------------------
  2097. ImGuiStyle& ImGui::GetStyle()
  2098. {
  2099. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  2100. return GImGui->Style;
  2101. }
  2102. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  2103. {
  2104. ImGuiStyle& style = GImGui->Style;
  2105. ImVec4 c = style.Colors[idx];
  2106. c.w *= style.Alpha * alpha_mul;
  2107. return ColorConvertFloat4ToU32(c);
  2108. }
  2109. ImU32 ImGui::GetColorU32(const ImVec4& col)
  2110. {
  2111. ImGuiStyle& style = GImGui->Style;
  2112. ImVec4 c = col;
  2113. c.w *= style.Alpha;
  2114. return ColorConvertFloat4ToU32(c);
  2115. }
  2116. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  2117. {
  2118. ImGuiStyle& style = GImGui->Style;
  2119. return style.Colors[idx];
  2120. }
  2121. ImU32 ImGui::GetColorU32(ImU32 col)
  2122. {
  2123. ImGuiStyle& style = GImGui->Style;
  2124. if (style.Alpha >= 1.0f)
  2125. return col;
  2126. ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  2127. a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  2128. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  2129. }
  2130. // 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
  2131. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  2132. {
  2133. ImGuiContext& g = *GImGui;
  2134. ImGuiColorMod backup;
  2135. backup.Col = idx;
  2136. backup.BackupValue = g.Style.Colors[idx];
  2137. g.ColorModifiers.push_back(backup);
  2138. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  2139. }
  2140. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  2141. {
  2142. ImGuiContext& g = *GImGui;
  2143. ImGuiColorMod backup;
  2144. backup.Col = idx;
  2145. backup.BackupValue = g.Style.Colors[idx];
  2146. g.ColorModifiers.push_back(backup);
  2147. g.Style.Colors[idx] = col;
  2148. }
  2149. void ImGui::PopStyleColor(int count)
  2150. {
  2151. ImGuiContext& g = *GImGui;
  2152. while (count > 0)
  2153. {
  2154. ImGuiColorMod& backup = g.ColorModifiers.back();
  2155. g.Style.Colors[backup.Col] = backup.BackupValue;
  2156. g.ColorModifiers.pop_back();
  2157. count--;
  2158. }
  2159. }
  2160. struct ImGuiStyleVarInfo
  2161. {
  2162. ImGuiDataType Type;
  2163. ImU32 Count;
  2164. ImU32 Offset;
  2165. void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  2166. };
  2167. static const ImGuiStyleVarInfo GStyleVarInfo[] =
  2168. {
  2169. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  2170. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  2171. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  2172. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
  2173. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  2174. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
  2175. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
  2176. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
  2177. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
  2178. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
  2179. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  2180. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  2181. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
  2182. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  2183. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  2184. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  2185. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
  2186. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
  2187. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  2188. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
  2189. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
  2190. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  2191. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
  2192. };
  2193. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  2194. {
  2195. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
  2196. IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
  2197. return &GStyleVarInfo[idx];
  2198. }
  2199. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  2200. {
  2201. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2202. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
  2203. {
  2204. ImGuiContext& g = *GImGui;
  2205. float* pvar = (float*)var_info->GetVarPtr(&g.Style);
  2206. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  2207. *pvar = val;
  2208. return;
  2209. }
  2210. IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
  2211. }
  2212. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  2213. {
  2214. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  2215. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
  2216. {
  2217. ImGuiContext& g = *GImGui;
  2218. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
  2219. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  2220. *pvar = val;
  2221. return;
  2222. }
  2223. IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
  2224. }
  2225. void ImGui::PopStyleVar(int count)
  2226. {
  2227. ImGuiContext& g = *GImGui;
  2228. while (count > 0)
  2229. {
  2230. // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
  2231. ImGuiStyleMod& backup = g.StyleModifiers.back();
  2232. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  2233. void* data = info->GetVarPtr(&g.Style);
  2234. if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
  2235. else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
  2236. g.StyleModifiers.pop_back();
  2237. count--;
  2238. }
  2239. }
  2240. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  2241. {
  2242. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  2243. switch (idx)
  2244. {
  2245. case ImGuiCol_Text: return "Text";
  2246. case ImGuiCol_TextDisabled: return "TextDisabled";
  2247. case ImGuiCol_WindowBg: return "WindowBg";
  2248. case ImGuiCol_ChildBg: return "ChildBg";
  2249. case ImGuiCol_PopupBg: return "PopupBg";
  2250. case ImGuiCol_Border: return "Border";
  2251. case ImGuiCol_BorderShadow: return "BorderShadow";
  2252. case ImGuiCol_FrameBg: return "FrameBg";
  2253. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  2254. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  2255. case ImGuiCol_TitleBg: return "TitleBg";
  2256. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  2257. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  2258. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  2259. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  2260. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  2261. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  2262. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  2263. case ImGuiCol_CheckMark: return "CheckMark";
  2264. case ImGuiCol_SliderGrab: return "SliderGrab";
  2265. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  2266. case ImGuiCol_Button: return "Button";
  2267. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  2268. case ImGuiCol_ButtonActive: return "ButtonActive";
  2269. case ImGuiCol_Header: return "Header";
  2270. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  2271. case ImGuiCol_HeaderActive: return "HeaderActive";
  2272. case ImGuiCol_Separator: return "Separator";
  2273. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  2274. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  2275. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  2276. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  2277. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  2278. case ImGuiCol_Tab: return "Tab";
  2279. case ImGuiCol_TabHovered: return "TabHovered";
  2280. case ImGuiCol_TabActive: return "TabActive";
  2281. case ImGuiCol_TabUnfocused: return "TabUnfocused";
  2282. case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
  2283. case ImGuiCol_DockingPreview: return "DockingPreview";
  2284. case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
  2285. case ImGuiCol_PlotLines: return "PlotLines";
  2286. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  2287. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  2288. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  2289. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  2290. case ImGuiCol_DragDropTarget: return "DragDropTarget";
  2291. case ImGuiCol_NavHighlight: return "NavHighlight";
  2292. case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
  2293. case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
  2294. case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
  2295. }
  2296. IM_ASSERT(0);
  2297. return "Unknown";
  2298. }
  2299. //-----------------------------------------------------------------------------
  2300. // [SECTION] RENDER HELPERS
  2301. // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
  2302. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
  2303. //-----------------------------------------------------------------------------
  2304. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  2305. {
  2306. const char* text_display_end = text;
  2307. if (!text_end)
  2308. text_end = (const char*)-1;
  2309. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2310. text_display_end++;
  2311. return text_display_end;
  2312. }
  2313. // Internal ImGui functions to render text
  2314. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  2315. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  2316. {
  2317. ImGuiContext& g = *GImGui;
  2318. ImGuiWindow* window = g.CurrentWindow;
  2319. // Hide anything after a '##' string
  2320. const char* text_display_end;
  2321. if (hide_text_after_hash)
  2322. {
  2323. text_display_end = FindRenderedTextEnd(text, text_end);
  2324. }
  2325. else
  2326. {
  2327. if (!text_end)
  2328. text_end = text + strlen(text); // FIXME-OPT
  2329. text_display_end = text_end;
  2330. }
  2331. if (text != text_display_end)
  2332. {
  2333. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  2334. if (g.LogEnabled)
  2335. LogRenderedText(&pos, text, text_display_end);
  2336. }
  2337. }
  2338. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  2339. {
  2340. ImGuiContext& g = *GImGui;
  2341. ImGuiWindow* window = g.CurrentWindow;
  2342. if (!text_end)
  2343. text_end = text + strlen(text); // FIXME-OPT
  2344. if (text != text_end)
  2345. {
  2346. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  2347. if (g.LogEnabled)
  2348. LogRenderedText(&pos, text, text_end);
  2349. }
  2350. }
  2351. // Default clip_rect uses (pos_min,pos_max)
  2352. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  2353. 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)
  2354. {
  2355. // Perform CPU side clipping for single clipped element to avoid using scissor state
  2356. ImVec2 pos = pos_min;
  2357. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  2358. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  2359. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  2360. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  2361. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  2362. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  2363. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  2364. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  2365. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  2366. // Render
  2367. if (need_clipping)
  2368. {
  2369. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  2370. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  2371. }
  2372. else
  2373. {
  2374. draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2375. }
  2376. }
  2377. 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)
  2378. {
  2379. // Hide anything after a '##' string
  2380. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  2381. const int text_len = (int)(text_display_end - text);
  2382. if (text_len == 0)
  2383. return;
  2384. ImGuiContext& g = *GImGui;
  2385. ImGuiWindow* window = g.CurrentWindow;
  2386. RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
  2387. if (g.LogEnabled)
  2388. LogRenderedText(&pos_min, text, text_display_end);
  2389. }
  2390. // Another overly complex function until we reorganize everything into a nice all-in-one helper.
  2391. // 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.
  2392. // 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.
  2393. 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)
  2394. {
  2395. ImGuiContext& g = *GImGui;
  2396. if (text_end_full == NULL)
  2397. text_end_full = FindRenderedTextEnd(text);
  2398. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
  2399. //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));
  2400. //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));
  2401. //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
  2402. // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
  2403. if (text_size.x > pos_max.x - pos_min.x)
  2404. {
  2405. // Hello wo...
  2406. // | | |
  2407. // min max ellipsis_max
  2408. // <-> this is generally some padding value
  2409. const ImFont* font = draw_list->_Data->Font;
  2410. const float font_size = draw_list->_Data->FontSize;
  2411. const char* text_end_ellipsis = NULL;
  2412. ImWchar ellipsis_char = font->EllipsisChar;
  2413. int ellipsis_char_count = 1;
  2414. if (ellipsis_char == (ImWchar)-1)
  2415. {
  2416. ellipsis_char = (ImWchar)'.';
  2417. ellipsis_char_count = 3;
  2418. }
  2419. const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
  2420. float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
  2421. float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
  2422. if (ellipsis_char_count > 1)
  2423. {
  2424. // Full ellipsis size without free spacing after it.
  2425. const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
  2426. ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
  2427. ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
  2428. }
  2429. // We can now claim the space between pos_max.x and ellipsis_max.x
  2430. const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
  2431. float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
  2432. if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
  2433. {
  2434. // Always display at least 1 character if there's no room for character + ellipsis
  2435. text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
  2436. text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
  2437. }
  2438. while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
  2439. {
  2440. // 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)
  2441. text_end_ellipsis--;
  2442. 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
  2443. }
  2444. // Render text, render ellipsis
  2445. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
  2446. float ellipsis_x = pos_min.x + text_size_clipped_x;
  2447. if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
  2448. for (int i = 0; i < ellipsis_char_count; i++)
  2449. {
  2450. font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
  2451. ellipsis_x += ellipsis_glyph_width;
  2452. }
  2453. }
  2454. else
  2455. {
  2456. RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
  2457. }
  2458. if (g.LogEnabled)
  2459. LogRenderedText(&pos_min, text, text_end_full);
  2460. }
  2461. // Render a rectangle shaped with optional rounding and borders
  2462. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2463. {
  2464. ImGuiContext& g = *GImGui;
  2465. ImGuiWindow* window = g.CurrentWindow;
  2466. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2467. const float border_size = g.Style.FrameBorderSize;
  2468. if (border && border_size > 0.0f)
  2469. {
  2470. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  2471. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  2472. }
  2473. }
  2474. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  2475. {
  2476. ImGuiContext& g = *GImGui;
  2477. ImGuiWindow* window = g.CurrentWindow;
  2478. const float border_size = g.Style.FrameBorderSize;
  2479. if (border_size > 0.0f)
  2480. {
  2481. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  2482. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  2483. }
  2484. }
  2485. // Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
  2486. void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)
  2487. {
  2488. const float h = draw_list->_Data->FontSize * 1.00f;
  2489. float r = h * 0.40f * scale;
  2490. ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);
  2491. ImVec2 a, b, c;
  2492. switch (dir)
  2493. {
  2494. case ImGuiDir_Up:
  2495. case ImGuiDir_Down:
  2496. if (dir == ImGuiDir_Up) r = -r;
  2497. a = ImVec2(+0.000f,+0.750f) * r;
  2498. b = ImVec2(-0.866f,-0.750f) * r;
  2499. c = ImVec2(+0.866f,-0.750f) * r;
  2500. break;
  2501. case ImGuiDir_Left:
  2502. case ImGuiDir_Right:
  2503. if (dir == ImGuiDir_Left) r = -r;
  2504. a = ImVec2(+0.750f,+0.000f) * r;
  2505. b = ImVec2(-0.750f,+0.866f) * r;
  2506. c = ImVec2(-0.750f,-0.866f) * r;
  2507. break;
  2508. case ImGuiDir_None:
  2509. case ImGuiDir_COUNT:
  2510. IM_ASSERT(0);
  2511. break;
  2512. }
  2513. draw_list->AddTriangleFilled(center + a, center + b, center + c, col);
  2514. }
  2515. void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
  2516. {
  2517. draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
  2518. }
  2519. void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
  2520. {
  2521. ImGuiContext& g = *GImGui;
  2522. ImGuiWindow* window = g.CurrentWindow;
  2523. float thickness = ImMax(sz / 5.0f, 1.0f);
  2524. sz -= thickness*0.5f;
  2525. pos += ImVec2(thickness*0.25f, thickness*0.25f);
  2526. float third = sz / 3.0f;
  2527. float bx = pos.x + third;
  2528. float by = pos.y + sz - third*0.5f;
  2529. window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
  2530. window->DrawList->PathLineTo(ImVec2(bx, by));
  2531. window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
  2532. window->DrawList->PathStroke(col, false, thickness);
  2533. }
  2534. void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
  2535. {
  2536. ImGuiContext& g = *GImGui;
  2537. if (id != g.NavId)
  2538. return;
  2539. if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
  2540. return;
  2541. ImGuiWindow* window = g.CurrentWindow;
  2542. if (window->DC.NavHideHighlightOneFrame)
  2543. return;
  2544. float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
  2545. ImRect display_rect = bb;
  2546. display_rect.ClipWith(window->ClipRect);
  2547. if (flags & ImGuiNavHighlightFlags_TypeDefault)
  2548. {
  2549. const float THICKNESS = 2.0f;
  2550. const float DISTANCE = 3.0f + THICKNESS * 0.5f;
  2551. display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
  2552. bool fully_visible = window->ClipRect.Contains(display_rect);
  2553. if (!fully_visible)
  2554. window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
  2555. window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
  2556. if (!fully_visible)
  2557. window->DrawList->PopClipRect();
  2558. }
  2559. if (flags & ImGuiNavHighlightFlags_TypeThin)
  2560. {
  2561. window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
  2562. }
  2563. }
  2564. //-----------------------------------------------------------------------------
  2565. // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
  2566. //-----------------------------------------------------------------------------
  2567. // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
  2568. ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
  2569. : DrawListInst(&context->DrawListSharedData)
  2570. {
  2571. Name = ImStrdup(name);
  2572. ID = ImHashStr(name);
  2573. IDStack.push_back(ID);
  2574. Flags = FlagsPreviousFrame = ImGuiWindowFlags_None;
  2575. Viewport = NULL;
  2576. ViewportId = 0;
  2577. ViewportAllowPlatformMonitorExtend = -1;
  2578. ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
  2579. Pos = ImVec2(0.0f, 0.0f);
  2580. Size = SizeFull = ImVec2(0.0f, 0.0f);
  2581. ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f);
  2582. WindowPadding = ImVec2(0.0f, 0.0f);
  2583. WindowRounding = 0.0f;
  2584. WindowBorderSize = 0.0f;
  2585. NameBufLen = (int)strlen(name) + 1;
  2586. MoveId = GetID("#MOVE");
  2587. ChildId = 0;
  2588. Scroll = ImVec2(0.0f, 0.0f);
  2589. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  2590. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  2591. ScrollbarSizes = ImVec2(0.0f, 0.0f);
  2592. ScrollbarX = ScrollbarY = false;
  2593. ViewportOwned = false;
  2594. Active = WasActive = false;
  2595. WriteAccessed = false;
  2596. Collapsed = false;
  2597. WantCollapseToggle = false;
  2598. SkipItems = false;
  2599. Appearing = false;
  2600. Hidden = false;
  2601. IsFallbackWindow = false;
  2602. HasCloseButton = false;
  2603. ResizeBorderHeld = -1;
  2604. BeginCount = 0;
  2605. BeginOrderWithinParent = -1;
  2606. BeginOrderWithinContext = -1;
  2607. PopupId = 0;
  2608. AutoFitFramesX = AutoFitFramesY = -1;
  2609. AutoFitChildAxises = 0x00;
  2610. AutoFitOnlyGrows = false;
  2611. AutoPosLastDirection = ImGuiDir_None;
  2612. HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
  2613. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  2614. SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
  2615. InnerRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f); // Clear so the InnerRect.GetSize() code in Begin() doesn't lead to overflow even if the result isn't used.
  2616. LastFrameActive = -1;
  2617. LastFrameJustFocused = -1;
  2618. LastTimeActive = -1.0f;
  2619. ItemWidthDefault = 0.0f;
  2620. FontWindowScale = FontDpiScale = 1.0f;
  2621. SettingsOffset = -1;
  2622. DrawList = &DrawListInst;
  2623. DrawList->_OwnerName = Name;
  2624. ParentWindow = NULL;
  2625. RootWindow = NULL;
  2626. RootWindowDockStop = NULL;
  2627. RootWindowForTitleBarHighlight = NULL;
  2628. RootWindowForNav = NULL;
  2629. NavLastIds[0] = NavLastIds[1] = 0;
  2630. NavRectRel[0] = NavRectRel[1] = ImRect();
  2631. NavLastChildNavWindow = NULL;
  2632. MemoryCompacted = false;
  2633. MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0;
  2634. DockNode = DockNodeAsHost = NULL;
  2635. DockId = 0;
  2636. DockTabItemStatusFlags = ImGuiItemStatusFlags_None;
  2637. DockOrder = -1;
  2638. DockIsActive = DockTabIsVisible = DockTabWantClose = false;
  2639. }
  2640. ImGuiWindow::~ImGuiWindow()
  2641. {
  2642. IM_ASSERT(DrawList == &DrawListInst);
  2643. IM_DELETE(Name);
  2644. for (int i = 0; i != ColumnsStorage.Size; i++)
  2645. ColumnsStorage[i].~ImGuiColumns();
  2646. }
  2647. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  2648. {
  2649. ImGuiID seed = IDStack.back();
  2650. ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  2651. ImGui::KeepAliveID(id);
  2652. return id;
  2653. }
  2654. ImGuiID ImGuiWindow::GetID(const void* ptr)
  2655. {
  2656. ImGuiID seed = IDStack.back();
  2657. ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
  2658. ImGui::KeepAliveID(id);
  2659. return id;
  2660. }
  2661. ImGuiID ImGuiWindow::GetID(int n)
  2662. {
  2663. ImGuiID seed = IDStack.back();
  2664. ImGuiID id = ImHashData(&n, sizeof(n), seed);
  2665. ImGui::KeepAliveID(id);
  2666. return id;
  2667. }
  2668. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  2669. {
  2670. ImGuiID seed = IDStack.back();
  2671. return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
  2672. }
  2673. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
  2674. {
  2675. ImGuiID seed = IDStack.back();
  2676. return ImHashData(&ptr, sizeof(void*), seed);
  2677. }
  2678. ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
  2679. {
  2680. ImGuiID seed = IDStack.back();
  2681. return ImHashData(&n, sizeof(n), seed);
  2682. }
  2683. // This is only used in rare/specific situations to manufacture an ID out of nowhere.
  2684. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
  2685. {
  2686. ImGuiID seed = IDStack.back();
  2687. 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) };
  2688. ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
  2689. ImGui::KeepAliveID(id);
  2690. return id;
  2691. }
  2692. static void SetCurrentWindow(ImGuiWindow* window)
  2693. {
  2694. ImGuiContext& g = *GImGui;
  2695. g.CurrentWindow = window;
  2696. if (window)
  2697. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  2698. }
  2699. // Free up/compact internal window buffers, we can use this when a window becomes unused.
  2700. // This is currently unused by the library, but you may call this yourself for easy GC.
  2701. // Not freed:
  2702. // - ImGuiWindow, ImGuiWindowSettings, Name
  2703. // - StateStorage, ColumnsStorage (may hold useful data)
  2704. // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
  2705. void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
  2706. {
  2707. window->MemoryCompacted = true;
  2708. window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
  2709. window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
  2710. window->IDStack.clear();
  2711. window->DrawList->ClearFreeMemory();
  2712. window->DC.ChildWindows.clear();
  2713. window->DC.ItemFlagsStack.clear();
  2714. window->DC.ItemWidthStack.clear();
  2715. window->DC.TextWrapPosStack.clear();
  2716. window->DC.GroupStack.clear();
  2717. }
  2718. void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
  2719. {
  2720. // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
  2721. // The other buffers tends to amortize much faster.
  2722. window->MemoryCompacted = false;
  2723. window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
  2724. window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
  2725. window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
  2726. }
  2727. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  2728. {
  2729. ImGuiContext& g = *GImGui;
  2730. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  2731. if (g.ActiveIdIsJustActivated)
  2732. {
  2733. g.ActiveIdTimer = 0.0f;
  2734. g.ActiveIdHasBeenPressedBefore = false;
  2735. g.ActiveIdHasBeenEditedBefore = false;
  2736. if (id != 0)
  2737. {
  2738. g.LastActiveId = id;
  2739. g.LastActiveIdTimer = 0.0f;
  2740. }
  2741. }
  2742. g.ActiveId = id;
  2743. g.ActiveIdAllowOverlap = false;
  2744. g.ActiveIdWindow = window;
  2745. g.ActiveIdHasBeenEditedThisFrame = false;
  2746. if (id)
  2747. {
  2748. g.ActiveIdIsAlive = id;
  2749. g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
  2750. }
  2751. // Clear declaration of inputs claimed by the widget
  2752. // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
  2753. g.ActiveIdUsingNavDirMask = 0x00;
  2754. g.ActiveIdUsingNavInputMask = 0x00;
  2755. g.ActiveIdUsingKeyInputMask = 0x00;
  2756. }
  2757. void ImGui::ClearActiveID()
  2758. {
  2759. SetActiveID(0, NULL);
  2760. }
  2761. void ImGui::SetHoveredID(ImGuiID id)
  2762. {
  2763. ImGuiContext& g = *GImGui;
  2764. g.HoveredId = id;
  2765. g.HoveredIdAllowOverlap = false;
  2766. if (id != 0 && g.HoveredIdPreviousFrame != id)
  2767. g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
  2768. }
  2769. ImGuiID ImGui::GetHoveredID()
  2770. {
  2771. ImGuiContext& g = *GImGui;
  2772. return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
  2773. }
  2774. void ImGui::KeepAliveID(ImGuiID id)
  2775. {
  2776. ImGuiContext& g = *GImGui;
  2777. if (g.ActiveId == id)
  2778. g.ActiveIdIsAlive = id;
  2779. if (g.ActiveIdPreviousFrame == id)
  2780. g.ActiveIdPreviousFrameIsAlive = true;
  2781. }
  2782. void ImGui::MarkItemEdited(ImGuiID id)
  2783. {
  2784. // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
  2785. // 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.
  2786. ImGuiContext& g = *GImGui;
  2787. IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
  2788. IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
  2789. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
  2790. g.ActiveIdHasBeenEditedThisFrame = true;
  2791. g.ActiveIdHasBeenEditedBefore = true;
  2792. g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
  2793. }
  2794. static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
  2795. {
  2796. // An active popup disable hovering on other windows (apart from its own children)
  2797. // FIXME-OPT: This could be cached/stored within the window.
  2798. ImGuiContext& g = *GImGui;
  2799. if (g.NavWindow)
  2800. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
  2801. if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
  2802. {
  2803. // For the purpose of those flags we differentiate "standard popup" from "modal popup"
  2804. // NB: The order of those two tests is important because Modal windows are also Popups.
  2805. if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
  2806. return false;
  2807. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  2808. return false;
  2809. }
  2810. // Filter by viewport
  2811. if (window->Viewport != g.MouseViewport)
  2812. if (g.MovingWindow == NULL || window->RootWindow != g.MovingWindow->RootWindow)
  2813. return false;
  2814. return true;
  2815. }
  2816. // This is roughly matching the behavior of internal-facing ItemHoverable()
  2817. // - 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()
  2818. // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
  2819. bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
  2820. {
  2821. ImGuiContext& g = *GImGui;
  2822. ImGuiWindow* window = g.CurrentWindow;
  2823. if (g.NavDisableMouseHover && !g.NavDisableHighlight)
  2824. return IsItemFocused();
  2825. // Test for bounding box overlap, as updated as ItemAdd()
  2826. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  2827. return false;
  2828. IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
  2829. // Test if we are hovering the right window (our window could be behind another window)
  2830. // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
  2831. // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
  2832. //if (g.HoveredWindow != window)
  2833. // return false;
  2834. if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
  2835. return false;
  2836. // Test if another item is active (e.g. being dragged)
  2837. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  2838. if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
  2839. return false;
  2840. // Test if interactions on this window are blocked by an active popup or modal.
  2841. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
  2842. if (!IsWindowContentHoverable(window, flags))
  2843. return false;
  2844. // Test if the item is disabled
  2845. if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
  2846. return false;
  2847. // Special handling for the dummy item after Begin() which represent the title bar or tab.
  2848. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
  2849. if ((window->DC.LastItemId == window->ID || window->DC.LastItemId == window->MoveId) && window->WriteAccessed)
  2850. return false;
  2851. return true;
  2852. }
  2853. // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
  2854. bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
  2855. {
  2856. ImGuiContext& g = *GImGui;
  2857. if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
  2858. return false;
  2859. ImGuiWindow* window = g.CurrentWindow;
  2860. if (g.HoveredWindow != window)
  2861. return false;
  2862. if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
  2863. return false;
  2864. if (!IsMouseHoveringRect(bb.Min, bb.Max))
  2865. return false;
  2866. if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
  2867. return false;
  2868. if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
  2869. return false;
  2870. SetHoveredID(id);
  2871. // [DEBUG] Item Picker tool!
  2872. // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
  2873. // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
  2874. // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
  2875. // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
  2876. if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
  2877. GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
  2878. if (g.DebugItemPickerBreakId == id)
  2879. IM_DEBUG_BREAK();
  2880. return true;
  2881. }
  2882. bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
  2883. {
  2884. ImGuiContext& g = *GImGui;
  2885. ImGuiWindow* window = g.CurrentWindow;
  2886. if (!bb.Overlaps(window->ClipRect))
  2887. if (id == 0 || id != g.ActiveId)
  2888. if (clip_even_when_logged || !g.LogEnabled)
  2889. return true;
  2890. return false;
  2891. }
  2892. // Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
  2893. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
  2894. {
  2895. ImGuiContext& g = *GImGui;
  2896. // Increment counters
  2897. const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
  2898. window->DC.FocusCounterRegular++;
  2899. if (is_tab_stop)
  2900. window->DC.FocusCounterTabStop++;
  2901. // Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
  2902. // (Note that we can always TAB out of a widget that doesn't allow tabbing in)
  2903. if (g.ActiveId == id && g.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL)
  2904. {
  2905. g.FocusRequestNextWindow = window;
  2906. g.FocusRequestNextCounterTabStop = 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.
  2907. }
  2908. // Handle focus requests
  2909. if (g.FocusRequestCurrWindow == window)
  2910. {
  2911. if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular)
  2912. return true;
  2913. if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop)
  2914. {
  2915. g.NavJustTabbedId = id;
  2916. return true;
  2917. }
  2918. // If another item is about to be focused, we clear our own active id
  2919. if (g.ActiveId == id)
  2920. ClearActiveID();
  2921. }
  2922. return false;
  2923. }
  2924. void ImGui::FocusableItemUnregister(ImGuiWindow* window)
  2925. {
  2926. window->DC.FocusCounterRegular--;
  2927. window->DC.FocusCounterTabStop--;
  2928. }
  2929. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  2930. {
  2931. if (wrap_pos_x < 0.0f)
  2932. return 0.0f;
  2933. ImGuiWindow* window = GImGui->CurrentWindow;
  2934. if (wrap_pos_x == 0.0f)
  2935. wrap_pos_x = window->WorkRect.Max.x;
  2936. else if (wrap_pos_x > 0.0f)
  2937. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  2938. return ImMax(wrap_pos_x - pos.x, 1.0f);
  2939. }
  2940. // IM_ALLOC() == ImGui::MemAlloc()
  2941. void* ImGui::MemAlloc(size_t size)
  2942. {
  2943. if (ImGuiContext* ctx = GImGui)
  2944. ctx->IO.MetricsActiveAllocations++;
  2945. return GImAllocatorAllocFunc(size, GImAllocatorUserData);
  2946. }
  2947. // IM_FREE() == ImGui::MemFree()
  2948. void ImGui::MemFree(void* ptr)
  2949. {
  2950. if (ptr)
  2951. if (ImGuiContext* ctx = GImGui)
  2952. ctx->IO.MetricsActiveAllocations--;
  2953. return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
  2954. }
  2955. const char* ImGui::GetClipboardText()
  2956. {
  2957. ImGuiContext& g = *GImGui;
  2958. return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
  2959. }
  2960. void ImGui::SetClipboardText(const char* text)
  2961. {
  2962. ImGuiContext& g = *GImGui;
  2963. if (g.IO.SetClipboardTextFn)
  2964. g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
  2965. }
  2966. const char* ImGui::GetVersion()
  2967. {
  2968. return IMGUI_VERSION;
  2969. }
  2970. // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
  2971. // 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
  2972. ImGuiContext* ImGui::GetCurrentContext()
  2973. {
  2974. return GImGui;
  2975. }
  2976. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  2977. {
  2978. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  2979. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  2980. #else
  2981. GImGui = ctx;
  2982. #endif
  2983. }
  2984. void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  2985. {
  2986. GImAllocatorAllocFunc = alloc_func;
  2987. GImAllocatorFreeFunc = free_func;
  2988. GImAllocatorUserData = user_data;
  2989. }
  2990. ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
  2991. {
  2992. ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
  2993. if (GImGui == NULL)
  2994. SetCurrentContext(ctx);
  2995. Initialize(ctx);
  2996. return ctx;
  2997. }
  2998. void ImGui::DestroyContext(ImGuiContext* ctx)
  2999. {
  3000. if (ctx == NULL)
  3001. ctx = GImGui;
  3002. Shutdown(ctx);
  3003. if (GImGui == ctx)
  3004. SetCurrentContext(NULL);
  3005. IM_DELETE(ctx);
  3006. }
  3007. ImGuiIO& ImGui::GetIO()
  3008. {
  3009. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  3010. return GImGui->IO;
  3011. }
  3012. ImGuiPlatformIO& ImGui::GetPlatformIO()
  3013. {
  3014. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  3015. return GImGui->PlatformIO;
  3016. }
  3017. // Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
  3018. ImDrawData* ImGui::GetDrawData()
  3019. {
  3020. ImGuiContext& g = *GImGui;
  3021. return g.Viewports[0]->DrawDataP.Valid ? &g.Viewports[0]->DrawDataP : NULL;
  3022. }
  3023. double ImGui::GetTime()
  3024. {
  3025. return GImGui->Time;
  3026. }
  3027. int ImGui::GetFrameCount()
  3028. {
  3029. return GImGui->FrameCount;
  3030. }
  3031. static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
  3032. {
  3033. // Create the draw list on demand, because they are not frequently used for all viewports
  3034. ImGuiContext& g = *GImGui;
  3035. IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
  3036. ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
  3037. if (draw_list == NULL)
  3038. {
  3039. draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
  3040. draw_list->_OwnerName = drawlist_name;
  3041. viewport->DrawLists[drawlist_no] = draw_list;
  3042. }
  3043. // Our ImDrawList system requires that there is always a command
  3044. if (viewport->LastFrameDrawLists[drawlist_no] != g.FrameCount)
  3045. {
  3046. draw_list->Clear();
  3047. draw_list->PushTextureID(g.IO.Fonts->TexID);
  3048. draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
  3049. viewport->LastFrameDrawLists[drawlist_no] = g.FrameCount;
  3050. }
  3051. return draw_list;
  3052. }
  3053. ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
  3054. {
  3055. return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
  3056. }
  3057. ImDrawList* ImGui::GetBackgroundDrawList()
  3058. {
  3059. ImGuiWindow* window = GImGui->CurrentWindow;
  3060. return GetBackgroundDrawList(window->Viewport);
  3061. }
  3062. ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
  3063. {
  3064. return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
  3065. }
  3066. ImDrawList* ImGui::GetForegroundDrawList()
  3067. {
  3068. ImGuiWindow* window = GImGui->CurrentWindow;
  3069. return GetForegroundDrawList(window->Viewport);
  3070. }
  3071. ImDrawListSharedData* ImGui::GetDrawListSharedData()
  3072. {
  3073. return &GImGui->DrawListSharedData;
  3074. }
  3075. void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
  3076. {
  3077. // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
  3078. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
  3079. // This is because we want ActiveId to be set even when the window is not permitted to move.
  3080. ImGuiContext& g = *GImGui;
  3081. FocusWindow(window);
  3082. SetActiveID(window->MoveId, window);
  3083. g.NavDisableHighlight = true;
  3084. g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
  3085. bool can_move_window = true;
  3086. if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
  3087. can_move_window = false;
  3088. if (ImGuiDockNode* node = window->DockNodeAsHost)
  3089. if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
  3090. can_move_window = false;
  3091. if (can_move_window)
  3092. g.MovingWindow = window;
  3093. }
  3094. // We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
  3095. // - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
  3096. // - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
  3097. void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
  3098. {
  3099. ImGuiContext& g = *GImGui;
  3100. bool can_undock_node = false;
  3101. if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
  3102. {
  3103. // Can undock if:
  3104. // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
  3105. // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
  3106. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  3107. if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
  3108. if (undock_floating_node || root_node->IsDockSpace())
  3109. can_undock_node = true;
  3110. }
  3111. const bool clicked = IsMouseClicked(0);
  3112. const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
  3113. if (can_undock_node && dragging)
  3114. {
  3115. DockContextQueueUndockNode(&g, node);
  3116. g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
  3117. }
  3118. else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
  3119. {
  3120. StartMouseMovingWindow(window);
  3121. g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
  3122. }
  3123. }
  3124. // Handle mouse moving window
  3125. // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
  3126. // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
  3127. // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
  3128. // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
  3129. void ImGui::UpdateMouseMovingWindowNewFrame()
  3130. {
  3131. ImGuiContext& g = *GImGui;
  3132. if (g.MovingWindow != NULL)
  3133. {
  3134. // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
  3135. // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
  3136. KeepAliveID(g.ActiveId);
  3137. IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
  3138. ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
  3139. if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
  3140. {
  3141. ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
  3142. if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
  3143. {
  3144. MarkIniSettingsDirty(moving_window);
  3145. SetWindowPos(moving_window, pos, ImGuiCond_Always);
  3146. if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
  3147. moving_window->Viewport->Pos = pos;
  3148. }
  3149. FocusWindow(g.MovingWindow);
  3150. }
  3151. else
  3152. {
  3153. // Try to merge the window back into the main viewport.
  3154. // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
  3155. if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
  3156. UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
  3157. // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
  3158. if (!IsDragDropPayloadBeingAccepted())
  3159. g.MouseViewport = moving_window->Viewport;
  3160. // Clear the NoInput window flag set by the Viewport system
  3161. moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
  3162. ClearActiveID();
  3163. g.MovingWindow = NULL;
  3164. }
  3165. }
  3166. else
  3167. {
  3168. // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
  3169. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
  3170. {
  3171. KeepAliveID(g.ActiveId);
  3172. if (!g.IO.MouseDown[0])
  3173. ClearActiveID();
  3174. }
  3175. }
  3176. }
  3177. // Initiate moving window when clicking on empty space or title bar.
  3178. // Handle left-click and right-click focus.
  3179. void ImGui::UpdateMouseMovingWindowEndFrame()
  3180. {
  3181. ImGuiContext& g = *GImGui;
  3182. if (g.ActiveId != 0 || g.HoveredId != 0)
  3183. return;
  3184. // Unless we just made a window/popup appear
  3185. if (g.NavWindow && g.NavWindow->Appearing)
  3186. return;
  3187. // Click on void to focus window and start moving
  3188. // (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!)
  3189. if (g.IO.MouseClicked[0])
  3190. {
  3191. ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindowDockStop : NULL;
  3192. if (root_window != NULL)
  3193. {
  3194. StartMouseMovingWindow(g.HoveredWindow);
  3195. if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
  3196. if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
  3197. if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
  3198. g.MovingWindow = NULL;
  3199. }
  3200. else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
  3201. {
  3202. // Clicking on void disable focus
  3203. FocusWindow(NULL);
  3204. }
  3205. }
  3206. // With right mouse button we close popups without changing focus based on where the mouse is aimed
  3207. // Instead, focus will be restored to the window under the bottom-most closed popup.
  3208. // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
  3209. if (g.IO.MouseClicked[1])
  3210. {
  3211. // Find the top-most window between HoveredWindow and the top-most Modal Window.
  3212. // This is where we can trim the popup stack.
  3213. ImGuiWindow* modal = GetTopMostPopupModal();
  3214. bool hovered_window_above_modal = false;
  3215. if (modal == NULL)
  3216. hovered_window_above_modal = true;
  3217. for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
  3218. {
  3219. ImGuiWindow* window = g.Windows[i];
  3220. if (window == modal)
  3221. break;
  3222. if (window == g.HoveredWindow)
  3223. hovered_window_above_modal = true;
  3224. }
  3225. ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
  3226. }
  3227. }
  3228. static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
  3229. {
  3230. window->Pos += delta;
  3231. window->ClipRect.Translate(delta);
  3232. window->OuterRectClipped.Translate(delta);
  3233. window->InnerRect.Translate(delta);
  3234. window->DC.CursorPos += delta;
  3235. window->DC.CursorStartPos += delta;
  3236. window->DC.CursorMaxPos += delta;
  3237. window->DC.LastItemRect.Translate(delta);
  3238. window->DC.LastItemDisplayRect.Translate(delta);
  3239. }
  3240. static void ScaleWindow(ImGuiWindow* window, float scale)
  3241. {
  3242. ImVec2 origin = window->Viewport->Pos;
  3243. window->Pos = ImFloor((window->Pos - origin) * scale + origin);
  3244. window->Size = ImFloor(window->Size * scale);
  3245. window->SizeFull = ImFloor(window->SizeFull * scale);
  3246. window->ContentSize = ImFloor(window->ContentSize * scale);
  3247. }
  3248. static bool IsWindowActiveAndVisible(ImGuiWindow* window)
  3249. {
  3250. return (window->Active) && (!window->Hidden);
  3251. }
  3252. static void ImGui::UpdateMouseInputs()
  3253. {
  3254. ImGuiContext& g = *GImGui;
  3255. // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
  3256. if (IsMousePosValid(&g.IO.MousePos))
  3257. g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
  3258. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
  3259. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
  3260. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  3261. else
  3262. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  3263. if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
  3264. g.NavDisableMouseHover = false;
  3265. g.IO.MousePosPrev = g.IO.MousePos;
  3266. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  3267. {
  3268. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  3269. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  3270. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  3271. 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;
  3272. g.IO.MouseDoubleClicked[i] = false;
  3273. if (g.IO.MouseClicked[i])
  3274. {
  3275. if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
  3276. {
  3277. ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  3278. if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  3279. g.IO.MouseDoubleClicked[i] = true;
  3280. g.IO.MouseClickedTime[i] = -DBL_MAX; // so the third click isn't turned into a double-click
  3281. }
  3282. else
  3283. {
  3284. g.IO.MouseClickedTime[i] = g.Time;
  3285. }
  3286. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  3287. g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
  3288. g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
  3289. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  3290. }
  3291. else if (g.IO.MouseDown[i])
  3292. {
  3293. // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
  3294. ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
  3295. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
  3296. 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);
  3297. 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);
  3298. }
  3299. if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
  3300. g.IO.MouseDownWasDoubleClick[i] = false;
  3301. if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
  3302. g.NavDisableMouseHover = false;
  3303. }
  3304. }
  3305. static void StartLockWheelingWindow(ImGuiWindow* window)
  3306. {
  3307. ImGuiContext& g = *GImGui;
  3308. if (g.WheelingWindow == window)
  3309. return;
  3310. g.WheelingWindow = window;
  3311. g.WheelingWindowRefMousePos = g.IO.MousePos;
  3312. g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
  3313. }
  3314. void ImGui::UpdateMouseWheel()
  3315. {
  3316. ImGuiContext& g = *GImGui;
  3317. // Reset the locked window if we move the mouse or after the timer elapses
  3318. if (g.WheelingWindow != NULL)
  3319. {
  3320. g.WheelingWindowTimer -= g.IO.DeltaTime;
  3321. if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
  3322. g.WheelingWindowTimer = 0.0f;
  3323. if (g.WheelingWindowTimer <= 0.0f)
  3324. {
  3325. g.WheelingWindow = NULL;
  3326. g.WheelingWindowTimer = 0.0f;
  3327. }
  3328. }
  3329. if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
  3330. return;
  3331. ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
  3332. if (!window || window->Collapsed)
  3333. return;
  3334. // Zoom / Scale window
  3335. // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
  3336. if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  3337. {
  3338. StartLockWheelingWindow(window);
  3339. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  3340. const float scale = new_font_scale / window->FontWindowScale;
  3341. window->FontWindowScale = new_font_scale;
  3342. if (!(window->Flags & ImGuiWindowFlags_ChildWindow))
  3343. {
  3344. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  3345. SetWindowPos(window, window->Pos + offset, 0);
  3346. window->Size = ImFloor(window->Size * scale);
  3347. window->SizeFull = ImFloor(window->SizeFull * scale);
  3348. }
  3349. return;
  3350. }
  3351. // Mouse wheel scrolling
  3352. // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
  3353. // Vertical Mouse Wheel scrolling
  3354. const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
  3355. if (wheel_y != 0.0f && !g.IO.KeyCtrl)
  3356. {
  3357. StartLockWheelingWindow(window);
  3358. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3359. window = window->ParentWindow;
  3360. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3361. {
  3362. float max_step = window->InnerRect.GetHeight() * 0.67f;
  3363. float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
  3364. SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
  3365. }
  3366. }
  3367. // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
  3368. const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
  3369. if (wheel_x != 0.0f && !g.IO.KeyCtrl)
  3370. {
  3371. StartLockWheelingWindow(window);
  3372. while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
  3373. window = window->ParentWindow;
  3374. if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
  3375. {
  3376. float max_step = window->InnerRect.GetWidth() * 0.67f;
  3377. float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
  3378. SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
  3379. }
  3380. }
  3381. }
  3382. void ImGui::UpdateTabFocus()
  3383. {
  3384. ImGuiContext& g = *GImGui;
  3385. // Pressing TAB activate widget focus
  3386. g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
  3387. if (g.ActiveId == 0 && g.FocusTabPressed)
  3388. {
  3389. // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
  3390. // manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
  3391. g.FocusRequestNextWindow = g.NavWindow;
  3392. g.FocusRequestNextCounterRegular = INT_MAX;
  3393. if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
  3394. g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
  3395. else
  3396. g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
  3397. }
  3398. // Turn queued focus request into current one
  3399. g.FocusRequestCurrWindow = NULL;
  3400. g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX;
  3401. if (g.FocusRequestNextWindow != NULL)
  3402. {
  3403. ImGuiWindow* window = g.FocusRequestNextWindow;
  3404. g.FocusRequestCurrWindow = window;
  3405. if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
  3406. g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
  3407. if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
  3408. g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
  3409. g.FocusRequestNextWindow = NULL;
  3410. g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = INT_MAX;
  3411. }
  3412. g.NavIdTabCounter = INT_MAX;
  3413. }
  3414. // 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)
  3415. void ImGui::UpdateHoveredWindowAndCaptureFlags()
  3416. {
  3417. ImGuiContext& g = *GImGui;
  3418. // Find the window hovered by mouse:
  3419. // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
  3420. // - 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.
  3421. // - 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.
  3422. FindHoveredWindow();
  3423. IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
  3424. // Modal windows prevents cursor from hovering behind them.
  3425. ImGuiWindow* modal_window = GetTopMostPopupModal();
  3426. if (modal_window)
  3427. if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
  3428. g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3429. // Disabled mouse?
  3430. if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
  3431. g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3432. // 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.
  3433. int mouse_earliest_button_down = -1;
  3434. bool mouse_any_down = false;
  3435. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  3436. {
  3437. if (g.IO.MouseClicked[i])
  3438. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
  3439. mouse_any_down |= g.IO.MouseDown[i];
  3440. if (g.IO.MouseDown[i])
  3441. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
  3442. mouse_earliest_button_down = i;
  3443. }
  3444. const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
  3445. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  3446. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
  3447. const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
  3448. if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
  3449. g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3450. // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
  3451. if (g.WantCaptureMouseNextFrame != -1)
  3452. g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
  3453. else
  3454. g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
  3455. // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
  3456. if (g.WantCaptureKeyboardNextFrame != -1)
  3457. g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
  3458. else
  3459. g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
  3460. if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
  3461. g.IO.WantCaptureKeyboard = true;
  3462. // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
  3463. g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
  3464. }
  3465. static void NewFrameSanityChecks()
  3466. {
  3467. ImGuiContext& g = *GImGui;
  3468. // Check user data
  3469. // (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)
  3470. IM_ASSERT(g.Initialized);
  3471. IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
  3472. IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
  3473. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
  3474. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  3475. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  3476. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
  3477. IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!");
  3478. IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
  3479. IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
  3480. IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
  3481. for (int n = 0; n < ImGuiKey_COUNT; n++)
  3482. 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)");
  3483. // Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP)
  3484. if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
  3485. IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
  3486. // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
  3487. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
  3488. g.IO.ConfigWindowsResizeFromEdges = false;
  3489. // 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.
  3490. if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
  3491. IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
  3492. if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
  3493. IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
  3494. // Perform simple checks: multi-viewport and platform windows support
  3495. if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  3496. {
  3497. if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
  3498. {
  3499. IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call PlatformWindowsUpdate() in main loop after EndFrame()? Check examples/ applications for reference.");
  3500. IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
  3501. IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
  3502. IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
  3503. IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
  3504. IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
  3505. IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
  3506. IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
  3507. IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
  3508. if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  3509. IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
  3510. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  3511. IM_ASSERT(g.IO.RenderDrawListsFn == NULL); // Call ImGui::Render() then pass ImGui::GetDrawData() yourself to your render function!
  3512. #endif
  3513. }
  3514. else
  3515. {
  3516. // Disable feature, our back-ends do not support it
  3517. g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
  3518. }
  3519. // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
  3520. for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
  3521. {
  3522. ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
  3523. IM_UNUSED(mon);
  3524. IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor bounds not setup properly.");
  3525. IM_ASSERT(mon.WorkSize.x > 0.0f && mon.WorkSize.y > 0.0f && "Monitor bounds not setup properly. If you don't have work area information, just copy Min/Max into them.");
  3526. IM_ASSERT(mon.DpiScale != 0.0f);
  3527. }
  3528. }
  3529. }
  3530. void ImGui::NewFrame()
  3531. {
  3532. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
  3533. ImGuiContext& g = *GImGui;
  3534. #ifdef IMGUI_ENABLE_TEST_ENGINE
  3535. ImGuiTestEngineHook_PreNewFrame(&g);
  3536. #endif
  3537. // Check and assert for various common IO and Configuration mistakes
  3538. g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
  3539. NewFrameSanityChecks();
  3540. g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
  3541. // Load settings on first frame, save settings when modified (after a delay)
  3542. UpdateSettings();
  3543. g.Time += g.IO.DeltaTime;
  3544. g.WithinFrameScope = true;
  3545. g.FrameCount += 1;
  3546. g.TooltipOverrideCount = 0;
  3547. g.WindowsActiveCount = 0;
  3548. g.MenusIdSubmittedThisFrame.resize(0);
  3549. // Calculate frame-rate for the user, as a purely luxurious feature
  3550. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  3551. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  3552. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  3553. g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
  3554. UpdateViewportsNewFrame();
  3555. // Setup current font and draw list shared data
  3556. // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
  3557. g.IO.Fonts->Locked = true;
  3558. SetCurrentFont(GetDefaultFont());
  3559. IM_ASSERT(g.Font->IsLoaded());
  3560. ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  3561. for (int n = 0; n < g.Viewports.Size; n++)
  3562. virtual_space.Add(g.Viewports[n]->GetMainRect());
  3563. g.DrawListSharedData.ClipRectFullscreen = ImVec4(virtual_space.Min.x, virtual_space.Min.y, virtual_space.Max.x, virtual_space.Max.y);
  3564. g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
  3565. g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError);
  3566. g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
  3567. if (g.Style.AntiAliasedLines)
  3568. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
  3569. if (g.Style.AntiAliasedFill)
  3570. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
  3571. if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
  3572. g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
  3573. // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
  3574. for (int n = 0; n < g.Viewports.Size; n++)
  3575. {
  3576. ImGuiViewportP* viewport = g.Viewports[n];
  3577. viewport->DrawData = NULL;
  3578. viewport->DrawDataP.Clear();
  3579. }
  3580. // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
  3581. if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
  3582. KeepAliveID(g.DragDropPayload.SourceId);
  3583. // Update HoveredId data
  3584. if (!g.HoveredIdPreviousFrame)
  3585. g.HoveredIdTimer = 0.0f;
  3586. if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
  3587. g.HoveredIdNotActiveTimer = 0.0f;
  3588. if (g.HoveredId)
  3589. g.HoveredIdTimer += g.IO.DeltaTime;
  3590. if (g.HoveredId && g.ActiveId != g.HoveredId)
  3591. g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
  3592. g.HoveredIdPreviousFrame = g.HoveredId;
  3593. g.HoveredId = 0;
  3594. g.HoveredIdAllowOverlap = false;
  3595. // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
  3596. if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  3597. ClearActiveID();
  3598. if (g.ActiveId)
  3599. g.ActiveIdTimer += g.IO.DeltaTime;
  3600. g.LastActiveIdTimer += g.IO.DeltaTime;
  3601. g.ActiveIdPreviousFrame = g.ActiveId;
  3602. g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
  3603. g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
  3604. g.ActiveIdIsAlive = 0;
  3605. g.ActiveIdHasBeenEditedThisFrame = false;
  3606. g.ActiveIdPreviousFrameIsAlive = false;
  3607. g.ActiveIdIsJustActivated = false;
  3608. if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
  3609. g.TempInputId = 0;
  3610. if (g.ActiveId == 0)
  3611. {
  3612. g.ActiveIdUsingNavDirMask = 0x00;
  3613. g.ActiveIdUsingNavInputMask = 0x00;
  3614. g.ActiveIdUsingKeyInputMask = 0x00;
  3615. }
  3616. // Drag and drop
  3617. g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
  3618. g.DragDropAcceptIdCurr = 0;
  3619. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  3620. g.DragDropWithinSourceOrTarget = false;
  3621. // Update keyboard input state
  3622. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  3623. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  3624. 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;
  3625. // Update gamepad/keyboard directional navigation
  3626. NavUpdate();
  3627. // Update mouse input state
  3628. UpdateMouseInputs();
  3629. // Undocking
  3630. // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
  3631. DockContextUpdateUndocking(&g);
  3632. // Find hovered window
  3633. // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
  3634. UpdateHoveredWindowAndCaptureFlags();
  3635. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
  3636. UpdateMouseMovingWindowNewFrame();
  3637. // Background darkening/whitening
  3638. if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
  3639. g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  3640. else
  3641. g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
  3642. g.MouseCursor = ImGuiMouseCursor_Arrow;
  3643. g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
  3644. g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  3645. g.PlatformImePosViewport = NULL;
  3646. // Mouse wheel scrolling, scale
  3647. UpdateMouseWheel();
  3648. // Update legacy TAB focus
  3649. UpdateTabFocus();
  3650. // Mark all windows as not visible and compact unused memory.
  3651. IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
  3652. const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX;
  3653. for (int i = 0; i != g.Windows.Size; i++)
  3654. {
  3655. ImGuiWindow* window = g.Windows[i];
  3656. window->WasActive = window->Active;
  3657. window->BeginCount = 0;
  3658. window->Active = false;
  3659. window->WriteAccessed = false;
  3660. // Garbage collect transient buffers of recently unused windows
  3661. if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
  3662. GcCompactTransientWindowBuffers(window);
  3663. }
  3664. // Closing the focused window restore focus to the first active root window in descending z-order
  3665. if (g.NavWindow && !g.NavWindow->WasActive)
  3666. FocusTopMostWindowUnderOne(NULL, NULL);
  3667. // No window should be open at the beginning of the frame.
  3668. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  3669. g.CurrentWindowStack.resize(0);
  3670. g.BeginPopupStack.resize(0);
  3671. ClosePopupsOverWindow(g.NavWindow, false);
  3672. // Docking
  3673. DockContextUpdateDocking(&g);
  3674. // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
  3675. UpdateDebugToolItemPicker();
  3676. // Create implicit/fallback window - which we will only render it if the user has added something to it.
  3677. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
  3678. // This fallback is particularly important as it avoid ImGui:: calls from crashing.
  3679. g.WithinFrameScopeWithImplicitWindow = true;
  3680. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
  3681. Begin("Debug##Default");
  3682. IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
  3683. #ifdef IMGUI_ENABLE_TEST_ENGINE
  3684. ImGuiTestEngineHook_PostNewFrame(&g);
  3685. #endif
  3686. }
  3687. // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
  3688. void ImGui::UpdateDebugToolItemPicker()
  3689. {
  3690. ImGuiContext& g = *GImGui;
  3691. g.DebugItemPickerBreakId = 0;
  3692. if (g.DebugItemPickerActive)
  3693. {
  3694. const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
  3695. ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
  3696. if (ImGui::IsKeyPressedMap(ImGuiKey_Escape))
  3697. g.DebugItemPickerActive = false;
  3698. if (ImGui::IsMouseClicked(0) && hovered_id)
  3699. {
  3700. g.DebugItemPickerBreakId = hovered_id;
  3701. g.DebugItemPickerActive = false;
  3702. }
  3703. ImGui::SetNextWindowBgAlpha(0.60f);
  3704. ImGui::BeginTooltip();
  3705. ImGui::Text("HoveredId: 0x%08X", hovered_id);
  3706. ImGui::Text("Press ESC to abort picking.");
  3707. ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
  3708. ImGui::EndTooltip();
  3709. }
  3710. }
  3711. void ImGui::Initialize(ImGuiContext* context)
  3712. {
  3713. ImGuiContext& g = *context;
  3714. IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
  3715. // Add .ini handle for ImGuiWindow type
  3716. {
  3717. ImGuiSettingsHandler ini_handler;
  3718. ini_handler.TypeName = "Window";
  3719. ini_handler.TypeHash = ImHashStr("Window");
  3720. ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
  3721. ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
  3722. ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
  3723. g.SettingsHandlers.push_back(ini_handler);
  3724. }
  3725. #ifdef IMGUI_HAS_TABLE
  3726. // Add .ini handle for ImGuiTable type
  3727. {
  3728. ImGuiSettingsHandler ini_handler;
  3729. ini_handler.TypeName = "Table";
  3730. ini_handler.TypeHash = ImHashStr("Table");
  3731. ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
  3732. ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
  3733. ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
  3734. g.SettingsHandlers.push_back(ini_handler);
  3735. }
  3736. #endif // #ifdef IMGUI_HAS_TABLE
  3737. #ifdef IMGUI_HAS_DOCK
  3738. // Create default viewport
  3739. ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
  3740. viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
  3741. viewport->Idx = 0;
  3742. viewport->PlatformWindowCreated = true;
  3743. g.Viewports.push_back(viewport);
  3744. g.PlatformIO.MainViewport = g.Viewports[0]; // Make it accessible in public-facing GetPlatformIO() immediately (before the first call to EndFrame)
  3745. g.PlatformIO.Viewports.push_back(g.Viewports[0]);
  3746. // Extensions
  3747. IM_ASSERT(g.DockContext == NULL);
  3748. DockContextInitialize(&g);
  3749. #endif // #ifdef IMGUI_HAS_DOCK
  3750. g.Initialized = true;
  3751. }
  3752. // This function is merely here to free heap allocations.
  3753. void ImGui::Shutdown(ImGuiContext* context)
  3754. {
  3755. // 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)
  3756. ImGuiContext& g = *context;
  3757. if (g.IO.Fonts && g.FontAtlasOwnedByContext)
  3758. {
  3759. g.IO.Fonts->Locked = false;
  3760. IM_DELETE(g.IO.Fonts);
  3761. }
  3762. g.IO.Fonts = NULL;
  3763. // Cleanup of other data are conditional on actually having initialized Dear ImGui.
  3764. if (!g.Initialized)
  3765. return;
  3766. // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
  3767. if (g.SettingsLoaded && g.IO.IniFilename != NULL)
  3768. {
  3769. ImGuiContext* backup_context = GImGui;
  3770. SetCurrentContext(context);
  3771. SaveIniSettingsToDisk(g.IO.IniFilename);
  3772. SetCurrentContext(backup_context);
  3773. }
  3774. // Destroy platform windows
  3775. ImGuiContext* backup_context = ImGui::GetCurrentContext();
  3776. SetCurrentContext(context);
  3777. PlatformWindowsDestroy();
  3778. SetCurrentContext(backup_context);
  3779. // Shutdown extensions
  3780. IM_ASSERT(g.DockContext != NULL);
  3781. DockContextShutdown(&g);
  3782. // Clear everything else
  3783. for (int i = 0; i < g.Windows.Size; i++)
  3784. IM_DELETE(g.Windows[i]);
  3785. g.Windows.clear();
  3786. g.WindowsFocusOrder.clear();
  3787. g.WindowsTempSortBuffer.clear();
  3788. g.CurrentWindow = NULL;
  3789. g.CurrentWindowStack.clear();
  3790. g.WindowsById.Clear();
  3791. g.NavWindow = NULL;
  3792. g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
  3793. g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
  3794. g.MovingWindow = NULL;
  3795. g.ColorModifiers.clear();
  3796. g.StyleModifiers.clear();
  3797. g.FontStack.clear();
  3798. g.OpenPopupStack.clear();
  3799. g.BeginPopupStack.clear();
  3800. g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
  3801. for (int i = 0; i < g.Viewports.Size; i++)
  3802. IM_DELETE(g.Viewports[i]);
  3803. g.Viewports.clear();
  3804. g.TabBars.Clear();
  3805. g.CurrentTabBarStack.clear();
  3806. g.ShrinkWidthBuffer.clear();
  3807. g.PrivateClipboard.clear();
  3808. g.MenusIdSubmittedThisFrame.clear();
  3809. g.InputTextState.ClearFreeMemory();
  3810. g.SettingsWindows.clear();
  3811. g.SettingsHandlers.clear();
  3812. if (g.LogFile)
  3813. {
  3814. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  3815. if (g.LogFile != stdout)
  3816. #endif
  3817. ImFileClose(g.LogFile);
  3818. g.LogFile = NULL;
  3819. }
  3820. g.LogBuffer.clear();
  3821. g.Initialized = false;
  3822. }
  3823. // FIXME: Add a more explicit sort order in the window structure.
  3824. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
  3825. {
  3826. const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
  3827. const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
  3828. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  3829. return d;
  3830. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  3831. return d;
  3832. return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
  3833. }
  3834. static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
  3835. {
  3836. out_sorted_windows->push_back(window);
  3837. if (window->Active)
  3838. {
  3839. int count = window->DC.ChildWindows.Size;
  3840. if (count > 1)
  3841. ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  3842. for (int i = 0; i < count; i++)
  3843. {
  3844. ImGuiWindow* child = window->DC.ChildWindows[i];
  3845. if (child->Active)
  3846. AddWindowToSortBuffer(out_sorted_windows, child);
  3847. }
  3848. }
  3849. }
  3850. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
  3851. {
  3852. if (draw_list->CmdBuffer.empty())
  3853. return;
  3854. // Remove trailing command if unused
  3855. ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
  3856. if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
  3857. {
  3858. draw_list->CmdBuffer.pop_back();
  3859. if (draw_list->CmdBuffer.empty())
  3860. return;
  3861. }
  3862. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
  3863. // May trigger for you if you are using PrimXXX functions incorrectly.
  3864. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  3865. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  3866. if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
  3867. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  3868. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
  3869. // If this assert triggers because you are drawing lots of stuff manually:
  3870. // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
  3871. // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents.
  3872. // - If you want large meshes with more than 64K vertices, you can either:
  3873. // (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
  3874. // Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't.
  3875. // 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.
  3876. // (B) Or handle 32-bit indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
  3877. // Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time:
  3878. // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
  3879. // Your own engine or render API may use different parameters or function calls to specify index sizes.
  3880. // 2 and 4 bytes indices are generally supported by most graphics API.
  3881. // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
  3882. // the 64K limit to split your draw commands in multiple draw lists.
  3883. if (sizeof(ImDrawIdx) == 2)
  3884. IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
  3885. out_list->push_back(draw_list);
  3886. }
  3887. static void AddWindowToDrawData(ImGuiWindow* window, int layer)
  3888. {
  3889. ImGuiContext& g = *GImGui;
  3890. g.IO.MetricsRenderWindows++;
  3891. AddDrawListToDrawData(&window->Viewport->DrawDataBuilder.Layers[layer], window->DrawList);
  3892. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  3893. {
  3894. ImGuiWindow* child = window->DC.ChildWindows[i];
  3895. if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
  3896. AddWindowToDrawData(child, layer);
  3897. }
  3898. }
  3899. // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
  3900. static void AddRootWindowToDrawData(ImGuiWindow* window)
  3901. {
  3902. int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
  3903. AddWindowToDrawData(window, layer);
  3904. }
  3905. void ImDrawDataBuilder::FlattenIntoSingleLayer()
  3906. {
  3907. int n = Layers[0].Size;
  3908. int size = n;
  3909. for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
  3910. size += Layers[i].Size;
  3911. Layers[0].resize(size);
  3912. for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
  3913. {
  3914. ImVector<ImDrawList*>& layer = Layers[layer_n];
  3915. if (layer.empty())
  3916. continue;
  3917. memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  3918. n += layer.Size;
  3919. layer.resize(0);
  3920. }
  3921. }
  3922. static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
  3923. {
  3924. ImDrawData* draw_data = &viewport->DrawDataP;
  3925. viewport->DrawData = draw_data; // Make publicly accessible
  3926. draw_data->Valid = true;
  3927. draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
  3928. draw_data->CmdListsCount = draw_lists->Size;
  3929. draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
  3930. draw_data->DisplayPos = viewport->Pos;
  3931. draw_data->DisplaySize = viewport->Size;
  3932. draw_data->FramebufferScale = ImGui::GetIO().DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
  3933. draw_data->OwnerViewport = viewport;
  3934. for (int n = 0; n < draw_lists->Size; n++)
  3935. {
  3936. draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
  3937. draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
  3938. }
  3939. }
  3940. // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
  3941. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  3942. {
  3943. ImGuiWindow* window = GetCurrentWindow();
  3944. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  3945. window->ClipRect = window->DrawList->_ClipRectStack.back();
  3946. }
  3947. void ImGui::PopClipRect()
  3948. {
  3949. ImGuiWindow* window = GetCurrentWindow();
  3950. window->DrawList->PopClipRect();
  3951. window->ClipRect = window->DrawList->_ClipRectStack.back();
  3952. }
  3953. static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
  3954. {
  3955. for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
  3956. if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
  3957. return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
  3958. return window;
  3959. }
  3960. static void ImGui::EndFrameDrawDimmedBackgrounds()
  3961. {
  3962. ImGuiContext& g = *GImGui;
  3963. // Draw modal whitening background on _other_ viewports than the one the modal is one
  3964. ImGuiWindow* modal_window = GetTopMostPopupModal();
  3965. const bool dim_bg_for_modal = (modal_window != NULL);
  3966. const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL);
  3967. if (dim_bg_for_modal || dim_bg_for_window_list)
  3968. for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
  3969. {
  3970. ImGuiViewportP* viewport = g.Viewports[viewport_n];
  3971. if (modal_window && viewport == modal_window->Viewport)
  3972. continue;
  3973. if (g.NavWindowingList && viewport == g.NavWindowingList->Viewport)
  3974. continue;
  3975. if (g.NavWindowingTargetAnim && viewport == g.NavWindowingTargetAnim->Viewport)
  3976. continue;
  3977. ImDrawList* draw_list = GetForegroundDrawList(viewport);
  3978. const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
  3979. draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
  3980. }
  3981. // Draw modal whitening background between CTRL-TAB list
  3982. if (dim_bg_for_window_list)
  3983. {
  3984. // Choose a draw list that will be front-most across all our children
  3985. ImGuiWindow* window = g.NavWindowingTargetAnim;
  3986. ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindow)->DrawList;
  3987. draw_list->PushClipRectFullScreen();
  3988. // Docking: draw modal whitening background on other nodes of a same dock tree
  3989. if (window->RootWindowDockStop->DockIsActive)
  3990. if (window->RootWindow != window->RootWindowDockStop)
  3991. RenderRectFilledWithHole(draw_list, window->RootWindow->Rect(), window->RootWindowDockStop->Rect(), GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio), g.Style.WindowRounding);
  3992. // Draw navigation selection/windowing rectangle border
  3993. float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
  3994. ImRect bb = window->Rect();
  3995. bb.Expand(g.FontSize);
  3996. if (bb.Contains(window->Viewport->GetMainRect())) // If a window fits the entire viewport, adjust its highlight inward
  3997. {
  3998. bb.Expand(-g.FontSize - 1.0f);
  3999. rounding = window->WindowRounding;
  4000. }
  4001. draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
  4002. draw_list->PopClipRect();
  4003. }
  4004. }
  4005. // 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.
  4006. void ImGui::EndFrame()
  4007. {
  4008. ImGuiContext& g = *GImGui;
  4009. IM_ASSERT(g.Initialized);
  4010. if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
  4011. return;
  4012. IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
  4013. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  4014. if (g.PlatformIO.Platform_SetImeInputPos && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImePos - g.PlatformImeLastPos) > 0.0001f))
  4015. if (g.PlatformImePosViewport && g.PlatformImePosViewport->PlatformWindowCreated)
  4016. {
  4017. g.PlatformIO.Platform_SetImeInputPos(g.PlatformImePosViewport, g.PlatformImePos);
  4018. g.PlatformImeLastPos = g.PlatformImePos;
  4019. g.PlatformImePosViewport = NULL;
  4020. }
  4021. ErrorCheckEndFrame();
  4022. // Hide implicit/fallback "Debug" window if it hasn't been used
  4023. g.WithinFrameScopeWithImplicitWindow = false;
  4024. if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
  4025. g.CurrentWindow->Active = false;
  4026. End();
  4027. // Draw modal whitening background on _other_ viewports than the one the modal is one
  4028. EndFrameDrawDimmedBackgrounds();
  4029. // Show CTRL+TAB list window
  4030. if (g.NavWindowingTarget != NULL)
  4031. NavUpdateWindowingOverlay();
  4032. SetCurrentViewport(NULL, NULL);
  4033. // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
  4034. if (g.DragDropActive)
  4035. {
  4036. bool is_delivered = g.DragDropPayload.Delivery;
  4037. bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
  4038. if (is_delivered || is_elapsed)
  4039. ClearDragDrop();
  4040. }
  4041. // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
  4042. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
  4043. {
  4044. g.DragDropWithinSourceOrTarget = true;
  4045. SetTooltip("...");
  4046. g.DragDropWithinSourceOrTarget = false;
  4047. }
  4048. // End frame
  4049. g.WithinFrameScope = false;
  4050. g.FrameCountEnded = g.FrameCount;
  4051. // Initiate moving window + handle left-click and right-click focus
  4052. UpdateMouseMovingWindowEndFrame();
  4053. // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
  4054. UpdateViewportsEndFrame();
  4055. // Sort the window list so that all child windows are after their parent
  4056. // We cannot do that on FocusWindow() because childs may not exist yet
  4057. g.WindowsTempSortBuffer.resize(0);
  4058. g.WindowsTempSortBuffer.reserve(g.Windows.Size);
  4059. for (int i = 0; i != g.Windows.Size; i++)
  4060. {
  4061. ImGuiWindow* window = g.Windows[i];
  4062. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  4063. continue;
  4064. AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
  4065. }
  4066. // 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.
  4067. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
  4068. g.Windows.swap(g.WindowsTempSortBuffer);
  4069. g.IO.MetricsActiveWindows = g.WindowsActiveCount;
  4070. // Unlock font atlas
  4071. g.IO.Fonts->Locked = false;
  4072. // Clear Input data for next frame
  4073. g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
  4074. g.IO.InputQueueCharacters.resize(0);
  4075. memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
  4076. }
  4077. void ImGui::Render()
  4078. {
  4079. ImGuiContext& g = *GImGui;
  4080. IM_ASSERT(g.Initialized);
  4081. if (g.FrameCountEnded != g.FrameCount)
  4082. EndFrame();
  4083. g.FrameCountRendered = g.FrameCount;
  4084. g.IO.MetricsRenderWindows = 0;
  4085. // Add background ImDrawList (for each active viewport)
  4086. for (int n = 0; n != g.Viewports.Size; n++)
  4087. {
  4088. ImGuiViewportP* viewport = g.Viewports[n];
  4089. viewport->DrawDataBuilder.Clear();
  4090. if (viewport->DrawLists[0] != NULL)
  4091. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
  4092. }
  4093. // Add ImDrawList to render
  4094. ImGuiWindow* windows_to_render_top_most[2];
  4095. windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
  4096. windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingList : NULL);
  4097. for (int n = 0; n != g.Windows.Size; n++)
  4098. {
  4099. ImGuiWindow* window = g.Windows[n];
  4100. if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
  4101. AddRootWindowToDrawData(window);
  4102. }
  4103. for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
  4104. if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
  4105. AddRootWindowToDrawData(windows_to_render_top_most[n]);
  4106. ImVec2 mouse_cursor_offset, mouse_cursor_size, mouse_cursor_uv[4];
  4107. if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
  4108. g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &mouse_cursor_offset, &mouse_cursor_size, &mouse_cursor_uv[0], &mouse_cursor_uv[2]);
  4109. // Setup ImDrawData structures for end-user
  4110. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
  4111. for (int n = 0; n < g.Viewports.Size; n++)
  4112. {
  4113. ImGuiViewportP* viewport = g.Viewports[n];
  4114. viewport->DrawDataBuilder.FlattenIntoSingleLayer();
  4115. // Draw software mouse cursor if requested by io.MouseDrawCursor flag
  4116. // (note we scale cursor by current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor)
  4117. if (mouse_cursor_size.x > 0.0f && mouse_cursor_size.y > 0.0f)
  4118. {
  4119. float scale = g.Style.MouseCursorScale * viewport->DpiScale;
  4120. if (viewport->GetMainRect().Overlaps(ImRect(g.IO.MousePos, g.IO.MousePos + ImVec2(mouse_cursor_size.x + 2, mouse_cursor_size.y + 2) * scale)))
  4121. RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, scale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
  4122. }
  4123. // Add foreground ImDrawList (for each active viewport)
  4124. if (viewport->DrawLists[1] != NULL)
  4125. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
  4126. SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
  4127. g.IO.MetricsRenderVertices += viewport->DrawData->TotalVtxCount;
  4128. g.IO.MetricsRenderIndices += viewport->DrawData->TotalIdxCount;
  4129. }
  4130. // (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
  4131. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  4132. if (g.Viewports[0]->DrawData->CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
  4133. g.IO.RenderDrawListsFn(g.Viewports[0]->DrawData);
  4134. #endif
  4135. }
  4136. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  4137. // CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
  4138. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  4139. {
  4140. ImGuiContext& g = *GImGui;
  4141. const char* text_display_end;
  4142. if (hide_text_after_double_hash)
  4143. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  4144. else
  4145. text_display_end = text_end;
  4146. ImFont* font = g.Font;
  4147. const float font_size = g.FontSize;
  4148. if (text == text_display_end)
  4149. return ImVec2(0.0f, font_size);
  4150. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  4151. // Round
  4152. text_size.x = IM_FLOOR(text_size.x + 0.95f);
  4153. return text_size;
  4154. }
  4155. // Find window given position, search front-to-back
  4156. // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
  4157. // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
  4158. // called, aka before the next Begin(). Moving window isn't affected.
  4159. static void FindHoveredWindow()
  4160. {
  4161. ImGuiContext& g = *GImGui;
  4162. // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
  4163. ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
  4164. if (g.MovingWindow)
  4165. g.MovingWindow->Viewport = g.MouseViewport;
  4166. ImGuiWindow* hovered_window = NULL;
  4167. ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
  4168. if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
  4169. hovered_window = g.MovingWindow;
  4170. ImVec2 padding_regular = g.Style.TouchExtraPadding;
  4171. ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
  4172. for (int i = g.Windows.Size - 1; i >= 0; i--)
  4173. {
  4174. ImGuiWindow* window = g.Windows[i];
  4175. if (!window->Active || window->Hidden)
  4176. continue;
  4177. if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
  4178. continue;
  4179. IM_ASSERT(window->Viewport);
  4180. if (window->Viewport != g.MouseViewport)
  4181. continue;
  4182. // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
  4183. ImRect bb(window->OuterRectClipped);
  4184. if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
  4185. bb.Expand(padding_regular);
  4186. else
  4187. bb.Expand(padding_for_resize_from_edges);
  4188. if (!bb.Contains(g.IO.MousePos))
  4189. continue;
  4190. if (window->HitTestHoleSize.x != 0)
  4191. {
  4192. // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
  4193. ImRect hole_bb((float)(window->HitTestHoleOffset.x), (float)(window->HitTestHoleOffset.y),
  4194. (float)(window->HitTestHoleOffset.x + window->HitTestHoleSize.x), (float)(window->HitTestHoleOffset.y + window->HitTestHoleSize.y));
  4195. if (hole_bb.Contains(g.IO.MousePos - window->Pos))
  4196. continue;
  4197. }
  4198. if (hovered_window == NULL)
  4199. hovered_window = window;
  4200. if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
  4201. hovered_window_ignoring_moving_window = window;
  4202. if (hovered_window && hovered_window_ignoring_moving_window)
  4203. break;
  4204. }
  4205. g.HoveredWindow = hovered_window;
  4206. g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
  4207. g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
  4208. if (g.MovingWindow)
  4209. g.MovingWindow->Viewport = moving_window_viewport;
  4210. }
  4211. // Test if mouse cursor is hovering given rectangle
  4212. // NB- Rectangle is clipped by our current clip setting
  4213. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  4214. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  4215. {
  4216. ImGuiContext& g = *GImGui;
  4217. // Clip
  4218. ImRect rect_clipped(r_min, r_max);
  4219. if (clip)
  4220. rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
  4221. // Expand for touch input
  4222. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  4223. if (!rect_for_touch.Contains(g.IO.MousePos))
  4224. return false;
  4225. if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
  4226. return false;
  4227. return true;
  4228. }
  4229. int ImGui::GetKeyIndex(ImGuiKey imgui_key)
  4230. {
  4231. IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
  4232. ImGuiContext& g = *GImGui;
  4233. return g.IO.KeyMap[imgui_key];
  4234. }
  4235. // Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
  4236. // Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
  4237. bool ImGui::IsKeyDown(int user_key_index)
  4238. {
  4239. if (user_key_index < 0)
  4240. return false;
  4241. ImGuiContext& g = *GImGui;
  4242. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4243. return g.IO.KeysDown[user_key_index];
  4244. }
  4245. // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
  4246. // t1 = current time (e.g.: g.Time)
  4247. // An event is triggered at:
  4248. // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
  4249. int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
  4250. {
  4251. if (t1 == 0.0f)
  4252. return 1;
  4253. if (t0 >= t1)
  4254. return 0;
  4255. if (repeat_rate <= 0.0f)
  4256. return (t0 < repeat_delay) && (t1 >= repeat_delay);
  4257. const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
  4258. const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
  4259. const int count = count_t1 - count_t0;
  4260. return count;
  4261. }
  4262. int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
  4263. {
  4264. ImGuiContext& g = *GImGui;
  4265. if (key_index < 0)
  4266. return 0;
  4267. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4268. const float t = g.IO.KeysDownDuration[key_index];
  4269. return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
  4270. }
  4271. bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
  4272. {
  4273. ImGuiContext& g = *GImGui;
  4274. if (user_key_index < 0)
  4275. return false;
  4276. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4277. const float t = g.IO.KeysDownDuration[user_key_index];
  4278. if (t == 0.0f)
  4279. return true;
  4280. if (repeat && t > g.IO.KeyRepeatDelay)
  4281. return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  4282. return false;
  4283. }
  4284. bool ImGui::IsKeyReleased(int user_key_index)
  4285. {
  4286. ImGuiContext& g = *GImGui;
  4287. if (user_key_index < 0) return false;
  4288. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4289. return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
  4290. }
  4291. bool ImGui::IsMouseDown(ImGuiMouseButton button)
  4292. {
  4293. ImGuiContext& g = *GImGui;
  4294. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4295. return g.IO.MouseDown[button];
  4296. }
  4297. bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
  4298. {
  4299. ImGuiContext& g = *GImGui;
  4300. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4301. const float t = g.IO.MouseDownDuration[button];
  4302. if (t == 0.0f)
  4303. return true;
  4304. if (repeat && t > g.IO.KeyRepeatDelay)
  4305. {
  4306. // 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.
  4307. int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
  4308. if (amount > 0)
  4309. return true;
  4310. }
  4311. return false;
  4312. }
  4313. bool ImGui::IsMouseReleased(ImGuiMouseButton button)
  4314. {
  4315. ImGuiContext& g = *GImGui;
  4316. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4317. return g.IO.MouseReleased[button];
  4318. }
  4319. bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
  4320. {
  4321. ImGuiContext& g = *GImGui;
  4322. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4323. return g.IO.MouseDoubleClicked[button];
  4324. }
  4325. // [Internal] This doesn't test if the button is pressed
  4326. bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
  4327. {
  4328. ImGuiContext& g = *GImGui;
  4329. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4330. if (lock_threshold < 0.0f)
  4331. lock_threshold = g.IO.MouseDragThreshold;
  4332. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  4333. }
  4334. bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
  4335. {
  4336. ImGuiContext& g = *GImGui;
  4337. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4338. if (!g.IO.MouseDown[button])
  4339. return false;
  4340. return IsMouseDragPastThreshold(button, lock_threshold);
  4341. }
  4342. ImVec2 ImGui::GetMousePos()
  4343. {
  4344. ImGuiContext& g = *GImGui;
  4345. return g.IO.MousePos;
  4346. }
  4347. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  4348. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  4349. {
  4350. ImGuiContext& g = *GImGui;
  4351. if (g.BeginPopupStack.Size > 0)
  4352. return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
  4353. return g.IO.MousePos;
  4354. }
  4355. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
  4356. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  4357. {
  4358. // The assert is only to silence a false-positive in XCode Static Analysis.
  4359. // 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).
  4360. IM_ASSERT(GImGui != NULL);
  4361. const float MOUSE_INVALID = -256000.0f;
  4362. ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
  4363. return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
  4364. }
  4365. bool ImGui::IsAnyMouseDown()
  4366. {
  4367. ImGuiContext& g = *GImGui;
  4368. for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
  4369. if (g.IO.MouseDown[n])
  4370. return true;
  4371. return false;
  4372. }
  4373. // Return the delta from the initial clicking position while the mouse button is clicked or was just released.
  4374. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
  4375. // NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
  4376. ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
  4377. {
  4378. ImGuiContext& g = *GImGui;
  4379. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4380. if (lock_threshold < 0.0f)
  4381. lock_threshold = g.IO.MouseDragThreshold;
  4382. if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
  4383. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  4384. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
  4385. return g.IO.MousePos - g.IO.MouseClickedPos[button];
  4386. return ImVec2(0.0f, 0.0f);
  4387. }
  4388. void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
  4389. {
  4390. ImGuiContext& g = *GImGui;
  4391. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4392. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  4393. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  4394. }
  4395. ImGuiMouseCursor ImGui::GetMouseCursor()
  4396. {
  4397. return GImGui->MouseCursor;
  4398. }
  4399. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  4400. {
  4401. GImGui->MouseCursor = cursor_type;
  4402. }
  4403. void ImGui::CaptureKeyboardFromApp(bool capture)
  4404. {
  4405. GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
  4406. }
  4407. void ImGui::CaptureMouseFromApp(bool capture)
  4408. {
  4409. GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
  4410. }
  4411. bool ImGui::IsItemActive()
  4412. {
  4413. ImGuiContext& g = *GImGui;
  4414. if (g.ActiveId)
  4415. {
  4416. ImGuiWindow* window = g.CurrentWindow;
  4417. return g.ActiveId == window->DC.LastItemId;
  4418. }
  4419. return false;
  4420. }
  4421. bool ImGui::IsItemActivated()
  4422. {
  4423. ImGuiContext& g = *GImGui;
  4424. if (g.ActiveId)
  4425. {
  4426. ImGuiWindow* window = g.CurrentWindow;
  4427. if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
  4428. return true;
  4429. }
  4430. return false;
  4431. }
  4432. bool ImGui::IsItemDeactivated()
  4433. {
  4434. ImGuiContext& g = *GImGui;
  4435. ImGuiWindow* window = g.CurrentWindow;
  4436. if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
  4437. return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
  4438. return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
  4439. }
  4440. bool ImGui::IsItemDeactivatedAfterEdit()
  4441. {
  4442. ImGuiContext& g = *GImGui;
  4443. return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
  4444. }
  4445. bool ImGui::IsItemFocused()
  4446. {
  4447. ImGuiContext& g = *GImGui;
  4448. ImGuiWindow* window = g.CurrentWindow;
  4449. if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
  4450. return false;
  4451. // Special handling for the dummy item after Begin() which represent the title bar or tab.
  4452. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
  4453. if (window->DC.LastItemId == window->ID && window->WriteAccessed)
  4454. return false;
  4455. return true;
  4456. }
  4457. bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
  4458. {
  4459. return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
  4460. }
  4461. bool ImGui::IsItemToggledOpen()
  4462. {
  4463. ImGuiContext& g = *GImGui;
  4464. return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
  4465. }
  4466. bool ImGui::IsItemToggledSelection()
  4467. {
  4468. ImGuiContext& g = *GImGui;
  4469. return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
  4470. }
  4471. bool ImGui::IsAnyItemHovered()
  4472. {
  4473. ImGuiContext& g = *GImGui;
  4474. return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
  4475. }
  4476. bool ImGui::IsAnyItemActive()
  4477. {
  4478. ImGuiContext& g = *GImGui;
  4479. return g.ActiveId != 0;
  4480. }
  4481. bool ImGui::IsAnyItemFocused()
  4482. {
  4483. ImGuiContext& g = *GImGui;
  4484. return g.NavId != 0 && !g.NavDisableHighlight;
  4485. }
  4486. bool ImGui::IsItemVisible()
  4487. {
  4488. ImGuiWindow* window = GetCurrentWindowRead();
  4489. return window->ClipRect.Overlaps(window->DC.LastItemRect);
  4490. }
  4491. bool ImGui::IsItemEdited()
  4492. {
  4493. ImGuiWindow* window = GetCurrentWindowRead();
  4494. return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
  4495. }
  4496. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  4497. void ImGui::SetItemAllowOverlap()
  4498. {
  4499. ImGuiContext& g = *GImGui;
  4500. if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
  4501. g.HoveredIdAllowOverlap = true;
  4502. if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
  4503. g.ActiveIdAllowOverlap = true;
  4504. }
  4505. ImVec2 ImGui::GetItemRectMin()
  4506. {
  4507. ImGuiWindow* window = GetCurrentWindowRead();
  4508. return window->DC.LastItemRect.Min;
  4509. }
  4510. ImVec2 ImGui::GetItemRectMax()
  4511. {
  4512. ImGuiWindow* window = GetCurrentWindowRead();
  4513. return window->DC.LastItemRect.Max;
  4514. }
  4515. ImVec2 ImGui::GetItemRectSize()
  4516. {
  4517. ImGuiWindow* window = GetCurrentWindowRead();
  4518. return window->DC.LastItemRect.GetSize();
  4519. }
  4520. bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
  4521. {
  4522. ImGuiContext& g = *GImGui;
  4523. ImGuiWindow* parent_window = g.CurrentWindow;
  4524. flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_NoDocking;
  4525. flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
  4526. // Size
  4527. const ImVec2 content_avail = GetContentRegionAvail();
  4528. ImVec2 size = ImFloor(size_arg);
  4529. const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
  4530. if (size.x <= 0.0f)
  4531. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  4532. if (size.y <= 0.0f)
  4533. size.y = ImMax(content_avail.y + size.y, 4.0f);
  4534. SetNextWindowSize(size);
  4535. // 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.
  4536. char title[256];
  4537. if (name)
  4538. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
  4539. else
  4540. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
  4541. const float backup_border_size = g.Style.ChildBorderSize;
  4542. if (!border)
  4543. g.Style.ChildBorderSize = 0.0f;
  4544. bool ret = Begin(title, NULL, flags);
  4545. g.Style.ChildBorderSize = backup_border_size;
  4546. ImGuiWindow* child_window = g.CurrentWindow;
  4547. child_window->ChildId = id;
  4548. child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
  4549. // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
  4550. // While this is not really documented/defined, it seems that the expected thing to do.
  4551. if (child_window->BeginCount == 1)
  4552. parent_window->DC.CursorPos = child_window->Pos;
  4553. // Process navigation-in immediately so NavInit can run on first frame
  4554. if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
  4555. {
  4556. FocusWindow(child_window);
  4557. NavInitWindow(child_window, false);
  4558. SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
  4559. g.ActiveIdSource = ImGuiInputSource_Nav;
  4560. }
  4561. return ret;
  4562. }
  4563. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4564. {
  4565. ImGuiWindow* window = GetCurrentWindow();
  4566. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  4567. }
  4568. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4569. {
  4570. IM_ASSERT(id != 0);
  4571. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  4572. }
  4573. void ImGui::EndChild()
  4574. {
  4575. ImGuiContext& g = *GImGui;
  4576. ImGuiWindow* window = g.CurrentWindow;
  4577. IM_ASSERT(g.WithinEndChild == false);
  4578. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
  4579. g.WithinEndChild = true;
  4580. if (window->BeginCount > 1)
  4581. {
  4582. End();
  4583. }
  4584. else
  4585. {
  4586. ImVec2 sz = window->Size;
  4587. if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  4588. sz.x = ImMax(4.0f, sz.x);
  4589. if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
  4590. sz.y = ImMax(4.0f, sz.y);
  4591. End();
  4592. ImGuiWindow* parent_window = g.CurrentWindow;
  4593. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  4594. ItemSize(sz);
  4595. if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
  4596. {
  4597. ItemAdd(bb, window->ChildId);
  4598. RenderNavHighlight(bb, window->ChildId);
  4599. // When browsing a window that has no activable items (scroll only) we keep a highlight on the child
  4600. if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
  4601. RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
  4602. }
  4603. else
  4604. {
  4605. // Not navigable into
  4606. ItemAdd(bb, 0);
  4607. }
  4608. }
  4609. g.WithinEndChild = false;
  4610. }
  4611. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  4612. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  4613. {
  4614. ImGuiContext& g = *GImGui;
  4615. const ImGuiStyle& style = g.Style;
  4616. PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
  4617. PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
  4618. PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
  4619. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  4620. bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  4621. PopStyleVar(3);
  4622. PopStyleColor();
  4623. return ret;
  4624. }
  4625. void ImGui::EndChildFrame()
  4626. {
  4627. EndChild();
  4628. }
  4629. static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
  4630. {
  4631. window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
  4632. window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
  4633. window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
  4634. window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
  4635. }
  4636. ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
  4637. {
  4638. ImGuiContext& g = *GImGui;
  4639. return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
  4640. }
  4641. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  4642. {
  4643. ImGuiID id = ImHashStr(name);
  4644. return FindWindowByID(id);
  4645. }
  4646. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
  4647. {
  4648. ImGuiContext& g = *GImGui;
  4649. //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
  4650. // Create window the first time
  4651. ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
  4652. window->Flags = flags;
  4653. g.WindowsById.SetVoidPtr(window->ID, window);
  4654. // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  4655. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  4656. window->Pos = main_viewport->Pos + ImVec2(60, 60);
  4657. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  4658. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4659. if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
  4660. {
  4661. // Retrieve settings from .ini file
  4662. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  4663. SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
  4664. if (settings->ViewportId)
  4665. {
  4666. window->ViewportId = settings->ViewportId;
  4667. window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
  4668. }
  4669. else
  4670. {
  4671. window->ViewportPos = main_viewport->Pos;
  4672. }
  4673. window->Pos = ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y);
  4674. window->Collapsed = settings->Collapsed;
  4675. if (settings->Size.x > 0 && settings->Size.y > 0)
  4676. size = ImVec2(settings->Size.x, settings->Size.y);
  4677. window->DockId = settings->DockId;
  4678. window->DockOrder = settings->DockOrder;
  4679. }
  4680. window->Size = window->SizeFull = ImFloor(size);
  4681. window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
  4682. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  4683. {
  4684. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  4685. window->AutoFitOnlyGrows = false;
  4686. }
  4687. else
  4688. {
  4689. if (window->Size.x <= 0.0f)
  4690. window->AutoFitFramesX = 2;
  4691. if (window->Size.y <= 0.0f)
  4692. window->AutoFitFramesY = 2;
  4693. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  4694. }
  4695. g.WindowsFocusOrder.push_back(window);
  4696. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  4697. g.Windows.push_front(window); // Quite slow but rare and only once
  4698. else
  4699. g.Windows.push_back(window);
  4700. return window;
  4701. }
  4702. static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
  4703. {
  4704. return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
  4705. }
  4706. static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
  4707. {
  4708. return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
  4709. }
  4710. static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
  4711. {
  4712. ImGuiContext& g = *GImGui;
  4713. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
  4714. {
  4715. // Using -1,-1 on either X/Y axis to preserve the current size.
  4716. ImRect cr = g.NextWindowData.SizeConstraintRect;
  4717. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  4718. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  4719. if (g.NextWindowData.SizeCallback)
  4720. {
  4721. ImGuiSizeCallbackData data;
  4722. data.UserData = g.NextWindowData.SizeCallbackUserData;
  4723. data.Pos = window->Pos;
  4724. data.CurrentSize = window->SizeFull;
  4725. data.DesiredSize = new_size;
  4726. g.NextWindowData.SizeCallback(&data);
  4727. new_size = data.DesiredSize;
  4728. }
  4729. new_size.x = IM_FLOOR(new_size.x);
  4730. new_size.y = IM_FLOOR(new_size.y);
  4731. }
  4732. // Minimum size
  4733. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  4734. {
  4735. ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
  4736. new_size = ImMax(new_size, g.Style.WindowMinSize);
  4737. new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
  4738. }
  4739. return new_size;
  4740. }
  4741. static ImVec2 CalcWindowContentSize(ImGuiWindow* window)
  4742. {
  4743. if (window->Collapsed)
  4744. if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  4745. return window->ContentSize;
  4746. if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
  4747. return window->ContentSize;
  4748. ImVec2 sz;
  4749. sz.x = IM_FLOOR((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
  4750. sz.y = IM_FLOOR((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
  4751. return sz;
  4752. }
  4753. static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
  4754. {
  4755. ImGuiContext& g = *GImGui;
  4756. ImGuiStyle& style = g.Style;
  4757. ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight());
  4758. ImVec2 size_pad = window->WindowPadding * 2.0f;
  4759. ImVec2 size_desired = size_contents + size_pad + size_decorations;
  4760. if (window->Flags & ImGuiWindowFlags_Tooltip)
  4761. {
  4762. // Tooltip always resize
  4763. return size_desired;
  4764. }
  4765. else
  4766. {
  4767. // Maximum window size is determined by the viewport size or monitor size
  4768. const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
  4769. const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
  4770. ImVec2 size_min = style.WindowMinSize;
  4771. 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)
  4772. size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
  4773. // FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows?
  4774. ImVec2 avail_size = window->Viewport->Size;
  4775. if (window->ViewportOwned)
  4776. avail_size = ImVec2(FLT_MAX, FLT_MAX);
  4777. const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
  4778. if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
  4779. avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
  4780. ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - g.Style.DisplaySafeAreaPadding * 2.0f));
  4781. // When the window cannot fit all contents (either because of constraints, either because screen is too small),
  4782. // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
  4783. ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4784. bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
  4785. bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
  4786. if (will_have_scrollbar_x)
  4787. size_auto_fit.y += style.ScrollbarSize;
  4788. if (will_have_scrollbar_y)
  4789. size_auto_fit.x += style.ScrollbarSize;
  4790. return size_auto_fit;
  4791. }
  4792. }
  4793. ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
  4794. {
  4795. ImVec2 size_contents = CalcWindowContentSize(window);
  4796. ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents);
  4797. ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4798. return size_final;
  4799. }
  4800. static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
  4801. {
  4802. if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  4803. return ImGuiCol_PopupBg;
  4804. if (flags & ImGuiWindowFlags_ChildWindow)
  4805. return ImGuiCol_ChildBg;
  4806. return ImGuiCol_WindowBg;
  4807. }
  4808. static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
  4809. {
  4810. ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
  4811. ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
  4812. ImVec2 size_expected = pos_max - pos_min;
  4813. ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
  4814. *out_pos = pos_min;
  4815. if (corner_norm.x == 0.0f)
  4816. out_pos->x -= (size_constrained.x - size_expected.x);
  4817. if (corner_norm.y == 0.0f)
  4818. out_pos->y -= (size_constrained.y - size_expected.y);
  4819. *out_size = size_constrained;
  4820. }
  4821. struct ImGuiResizeGripDef
  4822. {
  4823. ImVec2 CornerPosN;
  4824. ImVec2 InnerDir;
  4825. int AngleMin12, AngleMax12;
  4826. };
  4827. static const ImGuiResizeGripDef resize_grip_def[4] =
  4828. {
  4829. { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower-right
  4830. { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower-left
  4831. { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper-left (Unused)
  4832. { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused)
  4833. };
  4834. static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
  4835. {
  4836. ImRect rect = window->Rect();
  4837. if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
  4838. if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
  4839. if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
  4840. if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
  4841. if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
  4842. IM_ASSERT(0);
  4843. return ImRect();
  4844. }
  4845. // 0..3: corners (Lower-right, Lower-left, Unused, Unused)
  4846. // 4..7: borders (Top, Right, Bottom, Left)
  4847. ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n)
  4848. {
  4849. IM_ASSERT(n >= 0 && n <= 7);
  4850. ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
  4851. id = ImHashStr("#RESIZE", 0, id);
  4852. id = ImHashData(&n, sizeof(int), id);
  4853. return id;
  4854. }
  4855. // Handle resize for: Resize Grips, Borders, Gamepad
  4856. // Return true when using auto-fit (double click on resize grip)
  4857. static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
  4858. {
  4859. ImGuiContext& g = *GImGui;
  4860. ImGuiWindowFlags flags = window->Flags;
  4861. if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  4862. return false;
  4863. if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
  4864. return false;
  4865. bool ret_auto_fit = false;
  4866. const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
  4867. const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  4868. const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
  4869. const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
  4870. ImVec2 pos_target(FLT_MAX, FLT_MAX);
  4871. ImVec2 size_target(FLT_MAX, FLT_MAX);
  4872. // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
  4873. // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
  4874. // This is however not the case with current back-ends under Win32, but a custom borderless window implementation would benefit from it.
  4875. // - 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.
  4876. // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
  4877. const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
  4878. if (clip_with_viewport_rect)
  4879. PushClipRect(window->Viewport->Pos, window->Viewport->Pos + window->Viewport->Size, true); // Won't incur a draw command as we are not drawing here.
  4880. // Resize grips and borders are on layer 1
  4881. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  4882. window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
  4883. // Manual resize grips
  4884. PushID("#RESIZE");
  4885. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  4886. {
  4887. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  4888. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
  4889. // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
  4890. ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
  4891. if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
  4892. if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
  4893. bool hovered, held;
  4894. ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  4895. //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
  4896. if (hovered || held)
  4897. g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  4898. if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
  4899. {
  4900. // Manual auto-fit when double-clicking
  4901. size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
  4902. ret_auto_fit = true;
  4903. ClearActiveID();
  4904. }
  4905. else if (held)
  4906. {
  4907. // Resize from any of the four corners
  4908. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  4909. ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
  4910. CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
  4911. }
  4912. if (resize_grip_n == 0 || held || hovered)
  4913. resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  4914. }
  4915. for (int border_n = 0; border_n < resize_border_count; border_n++)
  4916. {
  4917. bool hovered, held;
  4918. ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
  4919. ButtonBehavior(border_rect, window->GetID(border_n + 4), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
  4920. //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
  4921. if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
  4922. {
  4923. g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
  4924. if (held)
  4925. *border_held = border_n;
  4926. }
  4927. if (held)
  4928. {
  4929. ImVec2 border_target = window->Pos;
  4930. ImVec2 border_posn;
  4931. if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
  4932. if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
  4933. if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
  4934. if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
  4935. CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
  4936. }
  4937. }
  4938. PopID();
  4939. if (clip_with_viewport_rect)
  4940. PopClipRect();
  4941. // Restore nav layer
  4942. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  4943. window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
  4944. // Navigation resize (keyboard/gamepad)
  4945. if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
  4946. {
  4947. ImVec2 nav_resize_delta;
  4948. if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
  4949. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  4950. if (g.NavInputSource == ImGuiInputSource_NavGamepad)
  4951. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
  4952. if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
  4953. {
  4954. const float NAV_RESIZE_SPEED = 600.0f;
  4955. nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
  4956. g.NavWindowingToggleLayer = false;
  4957. g.NavDisableMouseHover = true;
  4958. resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
  4959. // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
  4960. size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
  4961. }
  4962. }
  4963. // Apply back modified position/size to window
  4964. if (size_target.x != FLT_MAX)
  4965. {
  4966. window->SizeFull = size_target;
  4967. MarkIniSettingsDirty(window);
  4968. }
  4969. if (pos_target.x != FLT_MAX)
  4970. {
  4971. window->Pos = ImFloor(pos_target);
  4972. MarkIniSettingsDirty(window);
  4973. }
  4974. window->Size = window->SizeFull;
  4975. return ret_auto_fit;
  4976. }
  4977. static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
  4978. {
  4979. ImGuiContext& g = *GImGui;
  4980. ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
  4981. window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
  4982. }
  4983. static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
  4984. {
  4985. ImGuiContext& g = *GImGui;
  4986. float rounding = window->WindowRounding;
  4987. float border_size = window->WindowBorderSize;
  4988. if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
  4989. window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  4990. int border_held = window->ResizeBorderHeld;
  4991. if (border_held != -1)
  4992. {
  4993. struct ImGuiResizeBorderDef
  4994. {
  4995. ImVec2 InnerDir;
  4996. ImVec2 CornerPosN1, CornerPosN2;
  4997. float OuterAngle;
  4998. };
  4999. static const ImGuiResizeBorderDef resize_border_def[4] =
  5000. {
  5001. { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
  5002. { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
  5003. { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
  5004. { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
  5005. };
  5006. const ImGuiResizeBorderDef& def = resize_border_def[border_held];
  5007. ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
  5008. window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
  5009. window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
  5010. window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
  5011. }
  5012. if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
  5013. {
  5014. float y = window->Pos.y + window->TitleBarHeight() - 1;
  5015. 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);
  5016. }
  5017. }
  5018. // Draw background and borders
  5019. // Draw and handle scrollbars
  5020. 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)
  5021. {
  5022. ImGuiContext& g = *GImGui;
  5023. ImGuiStyle& style = g.Style;
  5024. ImGuiWindowFlags flags = window->Flags;
  5025. // Ensure that ScrollBar doesn't read last frame's SkipItems
  5026. window->SkipItems = false;
  5027. // Draw window + handle manual resize
  5028. // 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.
  5029. const float window_rounding = window->WindowRounding;
  5030. const float window_border_size = window->WindowBorderSize;
  5031. if (window->Collapsed)
  5032. {
  5033. // Title bar only
  5034. float backup_border_size = style.FrameBorderSize;
  5035. g.Style.FrameBorderSize = window->WindowBorderSize;
  5036. ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
  5037. RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
  5038. g.Style.FrameBorderSize = backup_border_size;
  5039. }
  5040. else
  5041. {
  5042. // Window background
  5043. if (!(flags & ImGuiWindowFlags_NoBackground))
  5044. {
  5045. bool is_docking_transparent_payload = false;
  5046. if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
  5047. if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
  5048. is_docking_transparent_payload = true;
  5049. ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
  5050. if (window->ViewportOwned)
  5051. {
  5052. // No alpha
  5053. bg_col = (bg_col | IM_COL32_A_MASK);
  5054. if (is_docking_transparent_payload)
  5055. window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
  5056. }
  5057. else
  5058. {
  5059. // Adjust alpha. For docking
  5060. bool override_alpha = false;
  5061. float alpha = 1.0f;
  5062. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
  5063. {
  5064. alpha = g.NextWindowData.BgAlphaVal;
  5065. override_alpha = true;
  5066. }
  5067. if (is_docking_transparent_payload)
  5068. {
  5069. alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
  5070. override_alpha = true;
  5071. }
  5072. if (override_alpha)
  5073. bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
  5074. }
  5075. window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
  5076. }
  5077. // Title bar
  5078. // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
  5079. // in order for their pos/size to be matching their undocking state.)
  5080. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
  5081. {
  5082. ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  5083. window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
  5084. }
  5085. // Menu bar
  5086. if (flags & ImGuiWindowFlags_MenuBar)
  5087. {
  5088. ImRect menu_bar_rect = window->MenuBarRect();
  5089. 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.
  5090. 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, ImDrawCornerFlags_Top);
  5091. if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
  5092. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  5093. }
  5094. // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
  5095. ImGuiDockNode* node = window->DockNode;
  5096. if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
  5097. {
  5098. float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
  5099. float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
  5100. ImVec2 p = node->Pos;
  5101. ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
  5102. bool hovered, held;
  5103. if (ButtonBehavior(r, window->GetID("#UNHIDE"), &hovered, &held, ImGuiButtonFlags_FlattenChildren))
  5104. node->WantHiddenTabBarToggle = true;
  5105. else if (held && IsMouseDragging(0))
  5106. StartMouseMovingWindowOrNode(window, node, true);
  5107. // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
  5108. ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5109. window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
  5110. }
  5111. // Scrollbars
  5112. if (window->ScrollbarX)
  5113. Scrollbar(ImGuiAxis_X);
  5114. if (window->ScrollbarY)
  5115. Scrollbar(ImGuiAxis_Y);
  5116. // Render resize grips (after their input handling so we don't have a frame of latency)
  5117. if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
  5118. {
  5119. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5120. {
  5121. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  5122. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
  5123. 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)));
  5124. 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)));
  5125. 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);
  5126. window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
  5127. }
  5128. }
  5129. // Borders (for dock node host they will be rendered over after the tab bar)
  5130. if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
  5131. RenderWindowOuterBorders(window);
  5132. }
  5133. }
  5134. // Render title text, collapse button, close button
  5135. // When inside a dock node, this is handled in DockNodeUpdateTabBar() instead.
  5136. void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
  5137. {
  5138. ImGuiContext& g = *GImGui;
  5139. ImGuiStyle& style = g.Style;
  5140. ImGuiWindowFlags flags = window->Flags;
  5141. const bool has_close_button = (p_open != NULL);
  5142. const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
  5143. // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
  5144. const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
  5145. window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
  5146. window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  5147. window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
  5148. // Layout buttons
  5149. // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
  5150. float pad_l = style.FramePadding.x;
  5151. float pad_r = style.FramePadding.x;
  5152. float button_sz = g.FontSize;
  5153. ImVec2 close_button_pos;
  5154. ImVec2 collapse_button_pos;
  5155. if (has_close_button)
  5156. {
  5157. pad_r += button_sz;
  5158. close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5159. }
  5160. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
  5161. {
  5162. pad_r += button_sz;
  5163. collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
  5164. }
  5165. if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
  5166. {
  5167. collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
  5168. pad_l += button_sz;
  5169. }
  5170. // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
  5171. if (has_collapse_button)
  5172. if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
  5173. window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
  5174. // Close button
  5175. if (has_close_button)
  5176. if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
  5177. *p_open = false;
  5178. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5179. window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
  5180. window->DC.ItemFlags = item_flags_backup;
  5181. // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
  5182. // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
  5183. const char* UNSAVED_DOCUMENT_MARKER = "*";
  5184. const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
  5185. const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
  5186. // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
  5187. // while uncentered title text will still reach edges correct.
  5188. if (pad_l > style.FramePadding.x)
  5189. pad_l += g.Style.ItemInnerSpacing.x;
  5190. if (pad_r > style.FramePadding.x)
  5191. pad_r += g.Style.ItemInnerSpacing.x;
  5192. if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
  5193. {
  5194. float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
  5195. float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
  5196. pad_l = ImMax(pad_l, pad_extend * centerness);
  5197. pad_r = ImMax(pad_r, pad_extend * centerness);
  5198. }
  5199. 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);
  5200. ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y);
  5201. //if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
  5202. RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
  5203. if (flags & ImGuiWindowFlags_UnsavedDocument)
  5204. {
  5205. 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);
  5206. ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f));
  5207. RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
  5208. }
  5209. }
  5210. void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
  5211. {
  5212. window->ParentWindow = parent_window;
  5213. window->RootWindow = window->RootWindowDockStop = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
  5214. if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  5215. {
  5216. window->RootWindow = parent_window->RootWindow;
  5217. if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
  5218. window->RootWindowDockStop = parent_window->RootWindowDockStop;
  5219. }
  5220. if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  5221. window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
  5222. while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
  5223. {
  5224. IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
  5225. window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
  5226. }
  5227. }
  5228. // Push a new Dear ImGui window to add widgets to.
  5229. // - 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.
  5230. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  5231. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  5232. // 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.
  5233. // - 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.
  5234. // - 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.
  5235. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  5236. {
  5237. ImGuiContext& g = *GImGui;
  5238. const ImGuiStyle& style = g.Style;
  5239. IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
  5240. IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
  5241. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  5242. // Find or create
  5243. ImGuiWindow* window = FindWindowByName(name);
  5244. const bool window_just_created = (window == NULL);
  5245. if (window_just_created)
  5246. {
  5247. ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
  5248. window = CreateNewWindow(name, size_on_first_use, flags);
  5249. }
  5250. // Automatically disable manual moving/resizing when NoInputs is set
  5251. if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
  5252. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  5253. if (flags & ImGuiWindowFlags_NavFlattened)
  5254. IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
  5255. const int current_frame = g.FrameCount;
  5256. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  5257. window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
  5258. // Update the Appearing flag
  5259. bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  5260. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
  5261. if (flags & ImGuiWindowFlags_Popup)
  5262. {
  5263. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5264. window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
  5265. window_just_activated_by_user |= (window != popup_ref.Window);
  5266. }
  5267. window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
  5268. if (window->Appearing)
  5269. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
  5270. // Update Flags, LastFrameActive, BeginOrderXXX fields
  5271. if (first_begin_of_the_frame)
  5272. {
  5273. window->FlagsPreviousFrame = window->Flags;
  5274. window->Flags = (ImGuiWindowFlags)flags;
  5275. window->LastFrameActive = current_frame;
  5276. window->LastTimeActive = (float)g.Time;
  5277. window->BeginOrderWithinParent = 0;
  5278. window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
  5279. }
  5280. else
  5281. {
  5282. flags = window->Flags;
  5283. }
  5284. // Docking
  5285. // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
  5286. IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
  5287. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
  5288. SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
  5289. if (first_begin_of_the_frame)
  5290. {
  5291. bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
  5292. bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
  5293. if (has_dock_node || new_auto_dock_node)
  5294. {
  5295. BeginDocked(window, p_open);
  5296. flags = window->Flags;
  5297. if (window->DockIsActive)
  5298. IM_ASSERT(window->DockNode != NULL);
  5299. // Docking currently override constraints
  5300. g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint;
  5301. }
  5302. }
  5303. // 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
  5304. ImGuiWindow* parent_window_in_stack = window->DockIsActive ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
  5305. ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
  5306. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  5307. // We allow window memory to be compacted so recreate the base stack when needed.
  5308. if (window->IDStack.Size == 0)
  5309. window->IDStack.push_back(window->ID);
  5310. // Add to stack
  5311. // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
  5312. g.CurrentWindowStack.push_back(window);
  5313. g.CurrentWindow = NULL;
  5314. ErrorCheckBeginEndCompareStacksSize(window, true);
  5315. if (flags & ImGuiWindowFlags_Popup)
  5316. {
  5317. ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
  5318. popup_ref.Window = window;
  5319. g.BeginPopupStack.push_back(popup_ref);
  5320. window->PopupId = popup_ref.PopupId;
  5321. }
  5322. if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
  5323. window->NavLastIds[0] = 0;
  5324. // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
  5325. if (first_begin_of_the_frame)
  5326. UpdateWindowParentAndRootLinks(window, flags, parent_window);
  5327. // Process SetNextWindow***() calls
  5328. bool window_pos_set_by_api = false;
  5329. bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
  5330. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
  5331. {
  5332. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
  5333. if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
  5334. {
  5335. // May be processed on the next frame if this is our first frame and we are measuring size
  5336. // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
  5337. window->SetWindowPosVal = g.NextWindowData.PosVal;
  5338. window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
  5339. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5340. }
  5341. else
  5342. {
  5343. SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
  5344. }
  5345. }
  5346. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
  5347. {
  5348. window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
  5349. window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
  5350. SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
  5351. }
  5352. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
  5353. window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
  5354. else if (first_begin_of_the_frame)
  5355. window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
  5356. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
  5357. window->WindowClass = g.NextWindowData.WindowClass;
  5358. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
  5359. SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
  5360. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
  5361. FocusWindow(window);
  5362. if (window->Appearing)
  5363. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
  5364. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  5365. if (first_begin_of_the_frame)
  5366. {
  5367. // Initialize
  5368. const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
  5369. window->Active = true;
  5370. window->HasCloseButton = (p_open != NULL);
  5371. window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
  5372. window->IDStack.resize(1);
  5373. // Restore buffer capacity when woken from a compacted state, to avoid
  5374. if (window->MemoryCompacted)
  5375. GcAwakeTransientWindowBuffers(window);
  5376. // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
  5377. // 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.
  5378. bool window_title_visible_elsewhere = false;
  5379. if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
  5380. window_title_visible_elsewhere = true;
  5381. else if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
  5382. window_title_visible_elsewhere = true;
  5383. if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
  5384. {
  5385. size_t buf_len = (size_t)window->NameBufLen;
  5386. window->Name = ImStrdupcpy(window->Name, &buf_len, name);
  5387. window->NameBufLen = (int)buf_len;
  5388. }
  5389. // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
  5390. // Update contents size from last frame for auto-fitting (or use explicit size)
  5391. window->ContentSize = CalcWindowContentSize(window);
  5392. if (window->HiddenFramesCanSkipItems > 0)
  5393. window->HiddenFramesCanSkipItems--;
  5394. if (window->HiddenFramesCannotSkipItems > 0)
  5395. window->HiddenFramesCannotSkipItems--;
  5396. // Hide new windows for one frame until they calculate their size
  5397. if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
  5398. window->HiddenFramesCannotSkipItems = 1;
  5399. // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
  5400. // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
  5401. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
  5402. {
  5403. window->HiddenFramesCannotSkipItems = 1;
  5404. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  5405. {
  5406. if (!window_size_x_set_by_api)
  5407. window->Size.x = window->SizeFull.x = 0.f;
  5408. if (!window_size_y_set_by_api)
  5409. window->Size.y = window->SizeFull.y = 0.f;
  5410. window->ContentSize = ImVec2(0.f, 0.f);
  5411. }
  5412. }
  5413. // SELECT VIEWPORT
  5414. // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
  5415. UpdateSelectWindowViewport(window);
  5416. SetCurrentViewport(window, window->Viewport);
  5417. window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
  5418. SetCurrentWindow(window);
  5419. flags = window->Flags;
  5420. // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
  5421. // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
  5422. if (flags & ImGuiWindowFlags_ChildWindow)
  5423. window->WindowBorderSize = style.ChildBorderSize;
  5424. else
  5425. window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
  5426. if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
  5427. window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
  5428. else
  5429. window->WindowPadding = style.WindowPadding;
  5430. // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
  5431. window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
  5432. window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
  5433. // Collapse window by double-clicking on title bar
  5434. // 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
  5435. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
  5436. {
  5437. // 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.
  5438. ImRect title_bar_rect = window->TitleBarRect();
  5439. if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
  5440. window->WantCollapseToggle = true;
  5441. if (window->WantCollapseToggle)
  5442. {
  5443. window->Collapsed = !window->Collapsed;
  5444. MarkIniSettingsDirty(window);
  5445. FocusWindow(window);
  5446. }
  5447. }
  5448. else
  5449. {
  5450. window->Collapsed = false;
  5451. }
  5452. window->WantCollapseToggle = false;
  5453. // SIZE
  5454. // Calculate auto-fit size, handle automatic resize
  5455. const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize);
  5456. bool use_current_size_for_scrollbar_x = window_just_created;
  5457. bool use_current_size_for_scrollbar_y = window_just_created;
  5458. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
  5459. {
  5460. // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
  5461. if (!window_size_x_set_by_api)
  5462. {
  5463. window->SizeFull.x = size_auto_fit.x;
  5464. use_current_size_for_scrollbar_x = true;
  5465. }
  5466. if (!window_size_y_set_by_api)
  5467. {
  5468. window->SizeFull.y = size_auto_fit.y;
  5469. use_current_size_for_scrollbar_y = true;
  5470. }
  5471. }
  5472. else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5473. {
  5474. // Auto-fit may only grow window during the first few frames
  5475. // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  5476. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
  5477. {
  5478. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  5479. use_current_size_for_scrollbar_x = true;
  5480. }
  5481. if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
  5482. {
  5483. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  5484. use_current_size_for_scrollbar_y = true;
  5485. }
  5486. if (!window->Collapsed)
  5487. MarkIniSettingsDirty(window);
  5488. }
  5489. // Apply minimum/maximum window size constraints and final size
  5490. window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
  5491. window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
  5492. // Decoration size
  5493. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  5494. // POSITION
  5495. // Popup latch its initial position, will position itself when it appears next frame
  5496. if (window_just_activated_by_user)
  5497. {
  5498. window->AutoPosLastDirection = ImGuiDir_None;
  5499. if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
  5500. window->Pos = g.BeginPopupStack.back().OpenPopupPos;
  5501. }
  5502. // Position child window
  5503. if (flags & ImGuiWindowFlags_ChildWindow)
  5504. {
  5505. IM_ASSERT(parent_window && parent_window->Active);
  5506. window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
  5507. parent_window->DC.ChildWindows.push_back(window);
  5508. if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
  5509. window->Pos = parent_window->DC.CursorPos;
  5510. }
  5511. const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
  5512. if (window_pos_with_pivot)
  5513. SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
  5514. else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
  5515. window->Pos = FindBestWindowPosForPopup(window);
  5516. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
  5517. window->Pos = FindBestWindowPosForPopup(window);
  5518. else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
  5519. window->Pos = FindBestWindowPosForPopup(window);
  5520. // Late create viewport if we don't fit within our current host viewport.
  5521. if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
  5522. if (!window->Viewport->GetMainRect().Contains(window->Rect()))
  5523. {
  5524. // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
  5525. //ImGuiViewport* old_viewport = window->Viewport;
  5526. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
  5527. // FIXME-DPI
  5528. //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
  5529. SetCurrentViewport(window, window->Viewport);
  5530. window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
  5531. SetCurrentWindow(window);
  5532. }
  5533. bool viewport_rect_changed = false;
  5534. if (window->ViewportOwned)
  5535. {
  5536. // Synchronize window --> viewport in most situations
  5537. // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
  5538. if (window->Viewport->PlatformRequestMove)
  5539. {
  5540. window->Pos = window->Viewport->Pos;
  5541. MarkIniSettingsDirty(window);
  5542. }
  5543. else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
  5544. {
  5545. viewport_rect_changed = true;
  5546. window->Viewport->Pos = window->Pos;
  5547. }
  5548. if (window->Viewport->PlatformRequestResize)
  5549. {
  5550. window->Size = window->SizeFull = window->Viewport->Size;
  5551. MarkIniSettingsDirty(window);
  5552. }
  5553. else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
  5554. {
  5555. viewport_rect_changed = true;
  5556. window->Viewport->Size = window->Size;
  5557. }
  5558. // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
  5559. // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
  5560. if (viewport_rect_changed)
  5561. UpdateViewportPlatformMonitor(window->Viewport);
  5562. // Update common viewport flags
  5563. ImGuiViewportFlags viewport_flags = (window->Viewport->Flags) & ~(ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration);
  5564. const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
  5565. if (flags & ImGuiWindowFlags_Tooltip)
  5566. viewport_flags |= ImGuiViewportFlags_TopMost;
  5567. if (g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window)
  5568. viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
  5569. if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
  5570. viewport_flags |= ImGuiViewportFlags_NoDecoration;
  5571. // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
  5572. // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
  5573. // 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,
  5574. // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
  5575. if (is_short_lived_floating_window && (flags & ImGuiWindowFlags_Modal) == 0)
  5576. viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
  5577. // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
  5578. // We don't default to the main viewport because.
  5579. if (window->WindowClass.ParentViewportId)
  5580. window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
  5581. else if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack)
  5582. window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
  5583. else
  5584. window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
  5585. if (window->WindowClass.ViewportFlagsOverrideSet)
  5586. viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
  5587. if (window->WindowClass.ViewportFlagsOverrideClear)
  5588. viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
  5589. // We also tell the back-end that clearing the platform window won't be necessary, as our window is filling the viewport and we have disabled BgAlpha
  5590. viewport_flags |= ImGuiViewportFlags_NoRendererClear;
  5591. window->Viewport->Flags = viewport_flags;
  5592. }
  5593. // Clamp position/size so window stays visible within its viewport or monitor
  5594. // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
  5595. // FIXME: Similar to code in GetWindowAllowedExtentRect()
  5596. ImRect viewport_rect = window->Viewport->GetMainRect();
  5597. if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  5598. {
  5599. ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  5600. if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
  5601. {
  5602. ClampWindowRect(window, window->Viewport->GetWorkRect(), clamp_padding);
  5603. }
  5604. else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
  5605. {
  5606. if (window->Viewport->PlatformMonitor == -1)
  5607. {
  5608. // Fallback for "lost" window (e.g. a monitor disconnected): we move the window back over the main viewport
  5609. SetWindowPos(window, g.Viewports[0]->Pos + style.DisplayWindowPadding, ImGuiCond_Always);
  5610. }
  5611. else
  5612. {
  5613. ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->Viewport->PlatformMonitor];
  5614. ClampWindowRect(window, ImRect(monitor.WorkPos, monitor.WorkPos + monitor.WorkSize), clamp_padding);
  5615. }
  5616. }
  5617. }
  5618. window->Pos = ImFloor(window->Pos);
  5619. // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
  5620. if (window->ViewportOwned || window->DockIsActive)
  5621. window->WindowRounding = 0.0f;
  5622. else
  5623. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
  5624. // Apply window focus (new and reactivated windows are moved to front)
  5625. bool want_focus = false;
  5626. if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  5627. {
  5628. if (flags & ImGuiWindowFlags_Popup)
  5629. want_focus = true;
  5630. else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
  5631. want_focus = true;
  5632. }
  5633. // Decide if we are going to handle borders and resize grips
  5634. const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
  5635. // Handle manual resize: Resize Grips, Borders, Gamepad
  5636. int border_held = -1;
  5637. ImU32 resize_grip_col[4] = {};
  5638. const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
  5639. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
  5640. if (handle_borders_and_resize_grips && !window->Collapsed)
  5641. if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]))
  5642. use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
  5643. window->ResizeBorderHeld = (signed char)border_held;
  5644. // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
  5645. if (window->ViewportOwned)
  5646. {
  5647. if (!window->Viewport->PlatformRequestMove)
  5648. window->Viewport->Pos = window->Pos;
  5649. if (!window->Viewport->PlatformRequestResize)
  5650. window->Viewport->Size = window->Size;
  5651. viewport_rect = window->Viewport->GetMainRect();
  5652. }
  5653. // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
  5654. window->ViewportPos = window->Viewport->Pos;
  5655. // SCROLLBAR VISIBILITY
  5656. // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
  5657. if (!window->Collapsed)
  5658. {
  5659. // When reading the current size we need to read it after size constraints have been applied.
  5660. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
  5661. ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
  5662. ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
  5663. ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
  5664. float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
  5665. float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
  5666. //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
  5667. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
  5668. 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));
  5669. if (window->ScrollbarX && !window->ScrollbarY)
  5670. window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
  5671. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  5672. }
  5673. // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
  5674. // Update various regions. Variables they depends on should be set above in this function.
  5675. // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
  5676. // Outer rectangle
  5677. // Not affected by window border size. Used by:
  5678. // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
  5679. // - Begin() initial clipping rect for drawing window background and borders.
  5680. // - Begin() clipping whole child
  5681. const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
  5682. const ImRect outer_rect = window->Rect();
  5683. const ImRect title_bar_rect = window->TitleBarRect();
  5684. window->OuterRectClipped = outer_rect;
  5685. if (window->DockIsActive)
  5686. window->OuterRectClipped.Min.y += window->TitleBarHeight();
  5687. window->OuterRectClipped.ClipWith(host_rect);
  5688. // Inner rectangle
  5689. // Not affected by window border size. Used by:
  5690. // - InnerClipRect
  5691. // - ScrollToBringRectIntoView()
  5692. // - NavUpdatePageUpPageDown()
  5693. // - Scrollbar()
  5694. window->InnerRect.Min.x = window->Pos.x;
  5695. window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
  5696. window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
  5697. window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
  5698. // Inner clipping rectangle.
  5699. // Will extend a little bit outside the normal work region.
  5700. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
  5701. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  5702. // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
  5703. // Affected by window/frame border size. Used by:
  5704. // - Begin() initial clip rect
  5705. float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
  5706. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5707. window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
  5708. window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
  5709. window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
  5710. window->InnerClipRect.ClipWithFull(host_rect);
  5711. // Default item width. Make it proportional to window size if window manually resizes
  5712. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  5713. window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
  5714. else
  5715. window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
  5716. // SCROLLING
  5717. // Lock down maximum scrolling
  5718. // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
  5719. // for right/bottom aligned items without creating a scrollbar.
  5720. window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
  5721. window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
  5722. // Apply scrolling
  5723. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
  5724. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  5725. // DRAWING
  5726. // Setup draw list and outer clipping rectangle
  5727. window->DrawList->Clear();
  5728. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  5729. PushClipRect(host_rect.Min, host_rect.Max, false);
  5730. // Draw modal or window list full viewport dimming background (for other viewports we'll render them in EndFrame)
  5731. const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
  5732. const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && ((window == g.NavWindowingTargetAnim->RootWindow) || (g.NavWindowingList && (window == g.NavWindowingList) && g.NavWindowingList->Viewport != g.NavWindowingTargetAnim->Viewport));
  5733. if (dim_bg_for_modal || dim_bg_for_window_list)
  5734. {
  5735. const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
  5736. window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
  5737. }
  5738. // Draw navigation selection/windowing rectangle background
  5739. if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
  5740. {
  5741. ImRect bb = window->Rect();
  5742. bb.Expand(g.FontSize);
  5743. if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
  5744. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
  5745. }
  5746. // Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
  5747. // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
  5748. // We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
  5749. // We also disabled this when we have dimming overlay behind this specific one child.
  5750. // 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.
  5751. const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
  5752. if (is_undocked_or_docked_visible)
  5753. {
  5754. bool render_decorations_in_parent = false;
  5755. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
  5756. if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
  5757. render_decorations_in_parent = true;
  5758. if (render_decorations_in_parent)
  5759. window->DrawList = parent_window->DrawList;
  5760. // Handle title bar, scrollbar, resize grips and resize borders
  5761. const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
  5762. 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)));
  5763. RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
  5764. if (render_decorations_in_parent)
  5765. window->DrawList = &window->DrawListInst;
  5766. }
  5767. // Draw navigation selection/windowing rectangle border
  5768. if (g.NavWindowingTargetAnim == window)
  5769. {
  5770. float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
  5771. ImRect bb = window->Rect();
  5772. bb.Expand(g.FontSize);
  5773. if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
  5774. {
  5775. bb.Expand(-g.FontSize - 1.0f);
  5776. rounding = window->WindowRounding;
  5777. }
  5778. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
  5779. }
  5780. // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
  5781. // Work rectangle.
  5782. // Affected by window padding and border size. Used by:
  5783. // - Columns() for right-most edge
  5784. // - TreeNode(), CollapsingHeader() for right-most edge
  5785. // - BeginTabBar() for right-most edge
  5786. const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
  5787. const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
  5788. 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));
  5789. 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));
  5790. window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
  5791. window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
  5792. window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
  5793. window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
  5794. // [LEGACY] Content Region
  5795. // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
  5796. // Used by:
  5797. // - Mouse wheel scrolling + many other things
  5798. window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
  5799. window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
  5800. 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));
  5801. 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));
  5802. // Setup drawing context
  5803. // (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.)
  5804. window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
  5805. window->DC.GroupOffset.x = 0.0f;
  5806. window->DC.ColumnsOffset.x = 0.0f;
  5807. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
  5808. window->DC.CursorPos = window->DC.CursorStartPos;
  5809. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  5810. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  5811. window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
  5812. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  5813. window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  5814. window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
  5815. window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
  5816. window->DC.NavLayerActiveMaskNext = 0x00;
  5817. window->DC.NavFocusScopeIdCurrent = 0;
  5818. window->DC.NavHideHighlightOneFrame = false;
  5819. window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
  5820. window->DC.MenuBarAppending = false;
  5821. window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
  5822. window->DC.TreeDepth = 0;
  5823. window->DC.TreeJumpToParentOnPopMask = 0x00;
  5824. window->DC.ChildWindows.resize(0);
  5825. window->DC.StateStorage = &window->StateStorage;
  5826. window->DC.CurrentColumns = NULL;
  5827. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  5828. window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
  5829. window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
  5830. window->DC.ItemWidth = window->ItemWidthDefault;
  5831. window->DC.TextWrapPos = -1.0f; // disabled
  5832. window->DC.ItemFlagsStack.resize(0);
  5833. window->DC.ItemWidthStack.resize(0);
  5834. window->DC.TextWrapPosStack.resize(0);
  5835. window->DC.GroupStack.resize(0);
  5836. window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
  5837. if (parent_window)
  5838. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  5839. if (window->AutoFitFramesX > 0)
  5840. window->AutoFitFramesX--;
  5841. if (window->AutoFitFramesY > 0)
  5842. window->AutoFitFramesY--;
  5843. // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  5844. if (want_focus)
  5845. {
  5846. FocusWindow(window);
  5847. NavInitWindow(window, false);
  5848. }
  5849. // Close requested by platform window
  5850. if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
  5851. {
  5852. if (!window->DockIsActive || window->DockTabIsVisible)
  5853. {
  5854. window->Viewport->PlatformRequestClose = false;
  5855. g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
  5856. IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' PlatformRequestClose\n", window->Name);
  5857. *p_open = false;
  5858. }
  5859. }
  5860. // Title bar
  5861. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
  5862. RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
  5863. // Clear hit test shape every frame
  5864. window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
  5865. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  5866. // 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.
  5867. // Maybe we can support CTRL+C on every element?
  5868. /*
  5869. if (g.ActiveId == move_id)
  5870. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  5871. LogToClipboard();
  5872. */
  5873. if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
  5874. {
  5875. // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
  5876. // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
  5877. if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
  5878. if ((window->RootWindow->Flags & ImGuiWindowFlags_NoDocking) == 0)
  5879. BeginDockableDragDropSource(window);
  5880. // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
  5881. if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
  5882. if (g.MovingWindow == NULL || g.MovingWindow->RootWindow != window)
  5883. if ((window == window->RootWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
  5884. BeginDockableDragDropTarget(window);
  5885. }
  5886. // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
  5887. // This is useful to allow creating context menus on title bar only, etc.
  5888. if (window->DockIsActive)
  5889. {
  5890. window->DC.LastItemId = window->ID;
  5891. window->DC.LastItemStatusFlags = window->DockTabItemStatusFlags;
  5892. window->DC.LastItemRect = window->DockTabItemRect;
  5893. }
  5894. else
  5895. {
  5896. window->DC.LastItemId = window->MoveId;
  5897. window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
  5898. window->DC.LastItemRect = title_bar_rect;
  5899. }
  5900. #ifdef IMGUI_ENABLE_TEST_ENGINE
  5901. if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5902. IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
  5903. #endif
  5904. }
  5905. else
  5906. {
  5907. // Append
  5908. SetCurrentViewport(window, window->Viewport);
  5909. SetCurrentWindow(window);
  5910. }
  5911. if (!(flags & ImGuiWindowFlags_DockNodeHost))
  5912. PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
  5913. // 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)
  5914. if (first_begin_of_the_frame)
  5915. window->WriteAccessed = false;
  5916. window->BeginCount++;
  5917. g.NextWindowData.ClearFlags();
  5918. // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
  5919. // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
  5920. // This is analogous to regular windows being hidden from one frame.
  5921. // 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.
  5922. if (window->DockIsActive && !window->DockTabIsVisible)
  5923. {
  5924. if (window->LastFrameJustFocused == g.FrameCount)
  5925. window->HiddenFramesCannotSkipItems = 1;
  5926. else
  5927. window->HiddenFramesCanSkipItems = 1;
  5928. }
  5929. if (flags & ImGuiWindowFlags_ChildWindow)
  5930. {
  5931. // Child window can be out of sight and have "negative" clip windows.
  5932. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
  5933. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
  5934. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  5935. if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
  5936. window->HiddenFramesCanSkipItems = 1;
  5937. // Hide along with parent or if parent is collapsed
  5938. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
  5939. window->HiddenFramesCanSkipItems = 1;
  5940. if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
  5941. window->HiddenFramesCannotSkipItems = 1;
  5942. }
  5943. // 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)
  5944. if (style.Alpha <= 0.0f)
  5945. window->HiddenFramesCanSkipItems = 1;
  5946. // Update the Hidden flag
  5947. window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
  5948. // Update the SkipItems flag, used to early out of all items functions (no layout required)
  5949. bool skip_items = false;
  5950. if (window->Collapsed || !window->Active || window->Hidden)
  5951. if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
  5952. skip_items = true;
  5953. window->SkipItems = skip_items;
  5954. return !skip_items;
  5955. }
  5956. void ImGui::End()
  5957. {
  5958. ImGuiContext& g = *GImGui;
  5959. ImGuiWindow* window = g.CurrentWindow;
  5960. // Error checking: verify that user hasn't called End() too many times!
  5961. if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
  5962. {
  5963. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
  5964. return;
  5965. }
  5966. IM_ASSERT(g.CurrentWindowStack.Size > 0);
  5967. // Error checking: verify that user doesn't directly call End() on a child window.
  5968. if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
  5969. IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
  5970. // Close anything that is open
  5971. if (window->DC.CurrentColumns)
  5972. EndColumns();
  5973. if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle
  5974. PopClipRect();
  5975. // Stop logging
  5976. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  5977. LogFinish();
  5978. // Docking: report contents sizes to parent to allow for auto-resize
  5979. if (window->DockNode && window->DockTabIsVisible)
  5980. if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
  5981. host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
  5982. // Pop from window stack
  5983. g.CurrentWindowStack.pop_back();
  5984. if (window->Flags & ImGuiWindowFlags_Popup)
  5985. g.BeginPopupStack.pop_back();
  5986. ErrorCheckBeginEndCompareStacksSize(window, false);
  5987. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  5988. if (g.CurrentWindow)
  5989. SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
  5990. }
  5991. void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
  5992. {
  5993. ImGuiContext& g = *GImGui;
  5994. if (g.WindowsFocusOrder.back() == window)
  5995. return;
  5996. for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window
  5997. if (g.WindowsFocusOrder[i] == window)
  5998. {
  5999. memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
  6000. g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
  6001. break;
  6002. }
  6003. }
  6004. void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
  6005. {
  6006. ImGuiContext& g = *GImGui;
  6007. ImGuiWindow* current_front_window = g.Windows.back();
  6008. if (current_front_window == window || current_front_window->RootWindow == window)
  6009. return;
  6010. for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
  6011. if (g.Windows[i] == window)
  6012. {
  6013. memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
  6014. g.Windows[g.Windows.Size - 1] = window;
  6015. break;
  6016. }
  6017. }
  6018. void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
  6019. {
  6020. ImGuiContext& g = *GImGui;
  6021. if (g.Windows[0] == window)
  6022. return;
  6023. for (int i = 0; i < g.Windows.Size; i++)
  6024. if (g.Windows[i] == window)
  6025. {
  6026. memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
  6027. g.Windows[0] = window;
  6028. break;
  6029. }
  6030. }
  6031. // Moving window to front of display and set focus (which happens to be back of our sorted list)
  6032. void ImGui::FocusWindow(ImGuiWindow* window)
  6033. {
  6034. ImGuiContext& g = *GImGui;
  6035. if (g.NavWindow != window)
  6036. {
  6037. g.NavWindow = window;
  6038. if (window && g.NavDisableMouseHover)
  6039. g.NavMousePosDirty = true;
  6040. g.NavInitRequest = false;
  6041. g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
  6042. g.NavFocusScopeId = 0;
  6043. g.NavIdIsAlive = false;
  6044. g.NavLayer = ImGuiNavLayer_Main;
  6045. //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
  6046. }
  6047. // Close popups if any
  6048. ClosePopupsOverWindow(window, false);
  6049. // Passing NULL allow to disable keyboard focus
  6050. if (!window)
  6051. return;
  6052. window->LastFrameJustFocused = g.FrameCount;
  6053. // Select in dock node
  6054. if (window->DockNode && window->DockNode->TabBar)
  6055. window->DockNode->TabBar->SelectedTabId = window->DockNode->TabBar->NextSelectedTabId = window->ID;
  6056. // Move the root window to the top of the pile
  6057. IM_ASSERT(window->RootWindow != NULL);
  6058. ImGuiWindow* focus_front_window = window->RootWindowDockStop;
  6059. ImGuiWindow* display_front_window = window->RootWindow;
  6060. // Steal focus on active widgets
  6061. if (focus_front_window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement may be unnecessary? Need further testing before removing it..
  6062. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
  6063. ClearActiveID();
  6064. // Bring to front
  6065. BringWindowToFocusFront(focus_front_window);
  6066. if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
  6067. BringWindowToDisplayFront(display_front_window);
  6068. }
  6069. void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
  6070. {
  6071. ImGuiContext& g = *GImGui;
  6072. int start_idx = g.WindowsFocusOrder.Size - 1;
  6073. if (under_this_window != NULL)
  6074. {
  6075. int under_this_window_idx = FindWindowFocusIndex(under_this_window);
  6076. if (under_this_window_idx != -1)
  6077. start_idx = under_this_window_idx - 1;
  6078. }
  6079. for (int i = start_idx; i >= 0; i--)
  6080. {
  6081. // 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.
  6082. ImGuiWindow* window = g.WindowsFocusOrder[i];
  6083. if (window != ignore_window && window->WasActive && window->RootWindowDockStop == window)
  6084. if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
  6085. {
  6086. // FIXME-DOCK: This is failing (lagging by one frame) for docked windows.
  6087. // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
  6088. // 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)
  6089. // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
  6090. ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
  6091. FocusWindow(focus_window);
  6092. return;
  6093. }
  6094. }
  6095. FocusWindow(NULL);
  6096. }
  6097. void ImGui::SetCurrentFont(ImFont* font)
  6098. {
  6099. ImGuiContext& g = *GImGui;
  6100. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  6101. IM_ASSERT(font->Scale > 0.0f);
  6102. g.Font = font;
  6103. g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
  6104. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  6105. ImFontAtlas* atlas = g.Font->ContainerAtlas;
  6106. g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
  6107. g.DrawListSharedData.Font = g.Font;
  6108. g.DrawListSharedData.FontSize = g.FontSize;
  6109. }
  6110. void ImGui::PushFont(ImFont* font)
  6111. {
  6112. ImGuiContext& g = *GImGui;
  6113. if (!font)
  6114. font = GetDefaultFont();
  6115. SetCurrentFont(font);
  6116. g.FontStack.push_back(font);
  6117. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  6118. }
  6119. void ImGui::PopFont()
  6120. {
  6121. ImGuiContext& g = *GImGui;
  6122. g.CurrentWindow->DrawList->PopTextureID();
  6123. g.FontStack.pop_back();
  6124. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  6125. }
  6126. void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
  6127. {
  6128. ImGuiWindow* window = GetCurrentWindow();
  6129. if (enabled)
  6130. window->DC.ItemFlags |= option;
  6131. else
  6132. window->DC.ItemFlags &= ~option;
  6133. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  6134. }
  6135. void ImGui::PopItemFlag()
  6136. {
  6137. ImGuiWindow* window = GetCurrentWindow();
  6138. window->DC.ItemFlagsStack.pop_back();
  6139. window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
  6140. }
  6141. // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
  6142. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  6143. {
  6144. PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
  6145. }
  6146. void ImGui::PopAllowKeyboardFocus()
  6147. {
  6148. PopItemFlag();
  6149. }
  6150. void ImGui::PushButtonRepeat(bool repeat)
  6151. {
  6152. PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
  6153. }
  6154. void ImGui::PopButtonRepeat()
  6155. {
  6156. PopItemFlag();
  6157. }
  6158. void ImGui::PushTextWrapPos(float wrap_pos_x)
  6159. {
  6160. ImGuiWindow* window = GetCurrentWindow();
  6161. window->DC.TextWrapPos = wrap_pos_x;
  6162. window->DC.TextWrapPosStack.push_back(wrap_pos_x);
  6163. }
  6164. void ImGui::PopTextWrapPos()
  6165. {
  6166. ImGuiWindow* window = GetCurrentWindow();
  6167. window->DC.TextWrapPosStack.pop_back();
  6168. window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
  6169. }
  6170. bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
  6171. {
  6172. if (window->RootWindow == potential_parent)
  6173. return true;
  6174. while (window != NULL)
  6175. {
  6176. if (window == potential_parent)
  6177. return true;
  6178. window = window->ParentWindow;
  6179. }
  6180. return false;
  6181. }
  6182. bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
  6183. {
  6184. IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
  6185. ImGuiContext& g = *GImGui;
  6186. if (flags & ImGuiHoveredFlags_AnyWindow)
  6187. {
  6188. if (g.HoveredWindow == NULL)
  6189. return false;
  6190. }
  6191. else
  6192. {
  6193. switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
  6194. {
  6195. case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
  6196. if (g.HoveredWindow == NULL || g.HoveredWindow->RootWindowDockStop != g.CurrentWindow->RootWindowDockStop)
  6197. return false;
  6198. break;
  6199. case ImGuiHoveredFlags_RootWindow:
  6200. if (g.HoveredWindow != g.CurrentWindow->RootWindowDockStop)
  6201. return false;
  6202. break;
  6203. case ImGuiHoveredFlags_ChildWindows:
  6204. if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
  6205. return false;
  6206. break;
  6207. default:
  6208. if (g.HoveredWindow != g.CurrentWindow)
  6209. return false;
  6210. break;
  6211. }
  6212. }
  6213. if (!IsWindowContentHoverable(g.HoveredWindow, flags))
  6214. return false;
  6215. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  6216. if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
  6217. return false;
  6218. return true;
  6219. }
  6220. bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
  6221. {
  6222. ImGuiContext& g = *GImGui;
  6223. if (flags & ImGuiFocusedFlags_AnyWindow)
  6224. return g.NavWindow != NULL;
  6225. IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
  6226. switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
  6227. {
  6228. case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
  6229. return g.NavWindow && g.NavWindow->RootWindowDockStop == g.CurrentWindow->RootWindowDockStop;
  6230. case ImGuiFocusedFlags_RootWindow:
  6231. return g.NavWindow == g.CurrentWindow->RootWindowDockStop;
  6232. case ImGuiFocusedFlags_ChildWindows:
  6233. return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
  6234. default:
  6235. return g.NavWindow == g.CurrentWindow;
  6236. }
  6237. }
  6238. ImGuiID ImGui::GetWindowDockID()
  6239. {
  6240. ImGuiContext& g = *GImGui;
  6241. return g.CurrentWindow->DockId;
  6242. }
  6243. bool ImGui::IsWindowDocked()
  6244. {
  6245. ImGuiContext& g = *GImGui;
  6246. return g.CurrentWindow->DockIsActive;
  6247. }
  6248. // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
  6249. // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
  6250. // If you want a window to never be focused, you may use the e.g. NoInputs flag.
  6251. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
  6252. {
  6253. return window->Active && window == window->RootWindowDockStop && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
  6254. }
  6255. float ImGui::GetWindowWidth()
  6256. {
  6257. ImGuiWindow* window = GImGui->CurrentWindow;
  6258. return window->Size.x;
  6259. }
  6260. float ImGui::GetWindowHeight()
  6261. {
  6262. ImGuiWindow* window = GImGui->CurrentWindow;
  6263. return window->Size.y;
  6264. }
  6265. ImVec2 ImGui::GetWindowPos()
  6266. {
  6267. ImGuiContext& g = *GImGui;
  6268. ImGuiWindow* window = g.CurrentWindow;
  6269. return window->Pos;
  6270. }
  6271. void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  6272. {
  6273. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6274. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  6275. return;
  6276. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6277. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6278. window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
  6279. // Set
  6280. const ImVec2 old_pos = window->Pos;
  6281. window->Pos = ImFloor(pos);
  6282. ImVec2 offset = window->Pos - old_pos;
  6283. 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
  6284. window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
  6285. window->DC.CursorStartPos += offset;
  6286. }
  6287. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  6288. {
  6289. ImGuiWindow* window = GetCurrentWindowRead();
  6290. SetWindowPos(window, pos, cond);
  6291. }
  6292. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  6293. {
  6294. if (ImGuiWindow* window = FindWindowByName(name))
  6295. SetWindowPos(window, pos, cond);
  6296. }
  6297. ImVec2 ImGui::GetWindowSize()
  6298. {
  6299. ImGuiWindow* window = GetCurrentWindowRead();
  6300. return window->Size;
  6301. }
  6302. void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  6303. {
  6304. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6305. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  6306. return;
  6307. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6308. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6309. // Set
  6310. if (size.x > 0.0f)
  6311. {
  6312. window->AutoFitFramesX = 0;
  6313. window->SizeFull.x = IM_FLOOR(size.x);
  6314. }
  6315. else
  6316. {
  6317. window->AutoFitFramesX = 2;
  6318. window->AutoFitOnlyGrows = false;
  6319. }
  6320. if (size.y > 0.0f)
  6321. {
  6322. window->AutoFitFramesY = 0;
  6323. window->SizeFull.y = IM_FLOOR(size.y);
  6324. }
  6325. else
  6326. {
  6327. window->AutoFitFramesY = 2;
  6328. window->AutoFitOnlyGrows = false;
  6329. }
  6330. }
  6331. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  6332. {
  6333. SetWindowSize(GImGui->CurrentWindow, size, cond);
  6334. }
  6335. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  6336. {
  6337. if (ImGuiWindow* window = FindWindowByName(name))
  6338. SetWindowSize(window, size, cond);
  6339. }
  6340. void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  6341. {
  6342. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6343. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  6344. return;
  6345. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6346. // Set
  6347. window->Collapsed = collapsed;
  6348. }
  6349. static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
  6350. {
  6351. IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
  6352. window->HitTestHoleSize = ImVec2ih(size);
  6353. window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
  6354. }
  6355. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  6356. {
  6357. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  6358. }
  6359. bool ImGui::IsWindowCollapsed()
  6360. {
  6361. ImGuiWindow* window = GetCurrentWindowRead();
  6362. return window->Collapsed;
  6363. }
  6364. bool ImGui::IsWindowAppearing()
  6365. {
  6366. ImGuiWindow* window = GetCurrentWindowRead();
  6367. return window->Appearing;
  6368. }
  6369. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  6370. {
  6371. if (ImGuiWindow* window = FindWindowByName(name))
  6372. SetWindowCollapsed(window, collapsed, cond);
  6373. }
  6374. void ImGui::SetWindowFocus()
  6375. {
  6376. FocusWindow(GImGui->CurrentWindow);
  6377. }
  6378. void ImGui::SetWindowFocus(const char* name)
  6379. {
  6380. if (name)
  6381. {
  6382. if (ImGuiWindow* window = FindWindowByName(name))
  6383. FocusWindow(window);
  6384. }
  6385. else
  6386. {
  6387. FocusWindow(NULL);
  6388. }
  6389. }
  6390. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
  6391. {
  6392. ImGuiContext& g = *GImGui;
  6393. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6394. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
  6395. g.NextWindowData.PosVal = pos;
  6396. g.NextWindowData.PosPivotVal = pivot;
  6397. g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
  6398. g.NextWindowData.PosUndock = true;
  6399. }
  6400. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  6401. {
  6402. ImGuiContext& g = *GImGui;
  6403. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6404. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
  6405. g.NextWindowData.SizeVal = size;
  6406. g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
  6407. }
  6408. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
  6409. {
  6410. ImGuiContext& g = *GImGui;
  6411. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
  6412. g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
  6413. g.NextWindowData.SizeCallback = custom_callback;
  6414. g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
  6415. }
  6416. // Content size = inner scrollable rectangle, padded with WindowPadding.
  6417. // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
  6418. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  6419. {
  6420. ImGuiContext& g = *GImGui;
  6421. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
  6422. g.NextWindowData.ContentSizeVal = size;
  6423. }
  6424. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  6425. {
  6426. ImGuiContext& g = *GImGui;
  6427. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  6428. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
  6429. g.NextWindowData.CollapsedVal = collapsed;
  6430. g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
  6431. }
  6432. void ImGui::SetNextWindowFocus()
  6433. {
  6434. ImGuiContext& g = *GImGui;
  6435. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
  6436. }
  6437. void ImGui::SetNextWindowBgAlpha(float alpha)
  6438. {
  6439. ImGuiContext& g = *GImGui;
  6440. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
  6441. g.NextWindowData.BgAlphaVal = alpha;
  6442. }
  6443. void ImGui::SetNextWindowViewport(ImGuiID id)
  6444. {
  6445. ImGuiContext& g = *GImGui;
  6446. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
  6447. g.NextWindowData.ViewportId = id;
  6448. }
  6449. void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
  6450. {
  6451. ImGuiContext& g = *GImGui;
  6452. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
  6453. g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
  6454. g.NextWindowData.DockId = id;
  6455. }
  6456. void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
  6457. {
  6458. ImGuiContext& g = *GImGui;
  6459. IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
  6460. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
  6461. g.NextWindowData.WindowClass = *window_class;
  6462. }
  6463. ImDrawList* ImGui::GetWindowDrawList()
  6464. {
  6465. ImGuiWindow* window = GetCurrentWindow();
  6466. return window->DrawList;
  6467. }
  6468. float ImGui::GetWindowDpiScale()
  6469. {
  6470. ImGuiContext& g = *GImGui;
  6471. return g.CurrentDpiScale;
  6472. }
  6473. ImGuiViewport* ImGui::GetWindowViewport()
  6474. {
  6475. ImGuiContext& g = *GImGui;
  6476. IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
  6477. return g.CurrentViewport;
  6478. }
  6479. ImFont* ImGui::GetFont()
  6480. {
  6481. return GImGui->Font;
  6482. }
  6483. float ImGui::GetFontSize()
  6484. {
  6485. return GImGui->FontSize;
  6486. }
  6487. ImVec2 ImGui::GetFontTexUvWhitePixel()
  6488. {
  6489. return GImGui->DrawListSharedData.TexUvWhitePixel;
  6490. }
  6491. void ImGui::SetWindowFontScale(float scale)
  6492. {
  6493. ImGuiContext& g = *GImGui;
  6494. ImGuiWindow* window = GetCurrentWindow();
  6495. window->FontWindowScale = scale;
  6496. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  6497. }
  6498. void ImGui::ActivateItem(ImGuiID id)
  6499. {
  6500. ImGuiContext& g = *GImGui;
  6501. g.NavNextActivateId = id;
  6502. }
  6503. void ImGui::PushFocusScope(ImGuiID id)
  6504. {
  6505. ImGuiContext& g = *GImGui;
  6506. ImGuiWindow* window = g.CurrentWindow;
  6507. window->IDStack.push_back(window->DC.NavFocusScopeIdCurrent);
  6508. window->DC.NavFocusScopeIdCurrent = id;
  6509. }
  6510. void ImGui::PopFocusScope()
  6511. {
  6512. ImGuiContext& g = *GImGui;
  6513. ImGuiWindow* window = g.CurrentWindow;
  6514. window->DC.NavFocusScopeIdCurrent = window->IDStack.back();
  6515. window->IDStack.pop_back();
  6516. }
  6517. void ImGui::SetKeyboardFocusHere(int offset)
  6518. {
  6519. IM_ASSERT(offset >= -1); // -1 is allowed but not below
  6520. ImGuiContext& g = *GImGui;
  6521. ImGuiWindow* window = g.CurrentWindow;
  6522. g.FocusRequestNextWindow = window;
  6523. g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
  6524. g.FocusRequestNextCounterTabStop = INT_MAX;
  6525. }
  6526. void ImGui::SetItemDefaultFocus()
  6527. {
  6528. ImGuiContext& g = *GImGui;
  6529. ImGuiWindow* window = g.CurrentWindow;
  6530. if (!window->Appearing)
  6531. return;
  6532. if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
  6533. {
  6534. g.NavInitRequest = false;
  6535. g.NavInitResultId = g.NavWindow->DC.LastItemId;
  6536. g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
  6537. NavUpdateAnyRequestFlag();
  6538. if (!IsItemVisible())
  6539. SetScrollHereY();
  6540. }
  6541. }
  6542. void ImGui::SetStateStorage(ImGuiStorage* tree)
  6543. {
  6544. ImGuiWindow* window = GImGui->CurrentWindow;
  6545. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  6546. }
  6547. ImGuiStorage* ImGui::GetStateStorage()
  6548. {
  6549. ImGuiWindow* window = GImGui->CurrentWindow;
  6550. return window->DC.StateStorage;
  6551. }
  6552. void ImGui::PushID(const char* str_id)
  6553. {
  6554. ImGuiWindow* window = GImGui->CurrentWindow;
  6555. window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
  6556. }
  6557. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  6558. {
  6559. ImGuiWindow* window = GImGui->CurrentWindow;
  6560. window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
  6561. }
  6562. void ImGui::PushID(const void* ptr_id)
  6563. {
  6564. ImGuiWindow* window = GImGui->CurrentWindow;
  6565. window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
  6566. }
  6567. void ImGui::PushID(int int_id)
  6568. {
  6569. ImGuiWindow* window = GImGui->CurrentWindow;
  6570. window->IDStack.push_back(window->GetIDNoKeepAlive(int_id));
  6571. }
  6572. // Push a given id value ignoring the ID stack as a seed.
  6573. void ImGui::PushOverrideID(ImGuiID id)
  6574. {
  6575. ImGuiWindow* window = GImGui->CurrentWindow;
  6576. window->IDStack.push_back(id);
  6577. }
  6578. void ImGui::PopID()
  6579. {
  6580. ImGuiWindow* window = GImGui->CurrentWindow;
  6581. window->IDStack.pop_back();
  6582. }
  6583. ImGuiID ImGui::GetID(const char* str_id)
  6584. {
  6585. ImGuiWindow* window = GImGui->CurrentWindow;
  6586. return window->GetID(str_id);
  6587. }
  6588. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  6589. {
  6590. ImGuiWindow* window = GImGui->CurrentWindow;
  6591. return window->GetID(str_id_begin, str_id_end);
  6592. }
  6593. ImGuiID ImGui::GetID(const void* ptr_id)
  6594. {
  6595. ImGuiWindow* window = GImGui->CurrentWindow;
  6596. return window->GetID(ptr_id);
  6597. }
  6598. bool ImGui::IsRectVisible(const ImVec2& size)
  6599. {
  6600. ImGuiWindow* window = GImGui->CurrentWindow;
  6601. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  6602. }
  6603. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  6604. {
  6605. ImGuiWindow* window = GImGui->CurrentWindow;
  6606. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  6607. }
  6608. //-----------------------------------------------------------------------------
  6609. // [SECTION] ERROR CHECKING
  6610. //-----------------------------------------------------------------------------
  6611. // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
  6612. // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
  6613. // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
  6614. // may see different structures than what imgui.cpp sees, which is problematic.
  6615. // We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
  6616. 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)
  6617. {
  6618. bool error = false;
  6619. if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
  6620. if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
  6621. if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
  6622. if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
  6623. if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
  6624. if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
  6625. if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
  6626. return !error;
  6627. }
  6628. static void ImGui::ErrorCheckEndFrame()
  6629. {
  6630. // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
  6631. // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
  6632. ImGuiContext& g = *GImGui;
  6633. if (g.CurrentWindowStack.Size != 1)
  6634. {
  6635. if (g.CurrentWindowStack.Size > 1)
  6636. {
  6637. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
  6638. while (g.CurrentWindowStack.Size > 1)
  6639. End();
  6640. }
  6641. else
  6642. {
  6643. IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
  6644. }
  6645. }
  6646. }
  6647. // Save and compare stack sizes on Begin()/End() to detect usage errors
  6648. // Begin() calls this with write=true
  6649. // End() calls this with write=false
  6650. static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write)
  6651. {
  6652. ImGuiContext& g = *GImGui;
  6653. short* p = &window->DC.StackSizesBackup[0];
  6654. // Window stacks
  6655. // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
  6656. { int n = window->IDStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "PushID/PopID or TreeNode/TreePop Mismatch!"); p++; } // Too few or too many PopID()/TreePop()
  6657. { int n = window->DC.GroupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup()
  6658. // Global stacks
  6659. // 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.
  6660. { int n = g.BeginPopupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup()
  6661. { int n = g.ColorModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor()
  6662. { int n = g.StyleModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar()
  6663. { int n = g.FontStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont()
  6664. IM_ASSERT(p == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
  6665. }
  6666. //-----------------------------------------------------------------------------
  6667. // [SECTION] LAYOUT
  6668. //-----------------------------------------------------------------------------
  6669. // - ItemSize()
  6670. // - ItemAdd()
  6671. // - SameLine()
  6672. // - GetCursorScreenPos()
  6673. // - SetCursorScreenPos()
  6674. // - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
  6675. // - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
  6676. // - GetCursorStartPos()
  6677. // - Indent()
  6678. // - Unindent()
  6679. // - SetNextItemWidth()
  6680. // - PushItemWidth()
  6681. // - PushMultiItemsWidths()
  6682. // - PopItemWidth()
  6683. // - CalcItemWidth()
  6684. // - CalcItemSize()
  6685. // - GetTextLineHeight()
  6686. // - GetTextLineHeightWithSpacing()
  6687. // - GetFrameHeight()
  6688. // - GetFrameHeightWithSpacing()
  6689. // - GetContentRegionMax()
  6690. // - GetContentRegionMaxAbs() [Internal]
  6691. // - GetContentRegionAvail(),
  6692. // - GetWindowContentRegionMin(), GetWindowContentRegionMax()
  6693. // - GetWindowContentRegionWidth()
  6694. // - BeginGroup()
  6695. // - EndGroup()
  6696. // Also see in imgui_widgets: tab bars, columns.
  6697. //-----------------------------------------------------------------------------
  6698. // Advance cursor given item size for layout.
  6699. void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
  6700. {
  6701. ImGuiContext& g = *GImGui;
  6702. ImGuiWindow* window = g.CurrentWindow;
  6703. if (window->SkipItems)
  6704. return;
  6705. // We increase the height in this function to accommodate for baseline offset.
  6706. // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
  6707. // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
  6708. const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
  6709. const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
  6710. // Always align ourselves on pixel boundaries
  6711. //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]
  6712. window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
  6713. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
  6714. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
  6715. window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
  6716. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  6717. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
  6718. //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
  6719. window->DC.PrevLineSize.y = line_height;
  6720. window->DC.CurrLineSize.y = 0.0f;
  6721. window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
  6722. window->DC.CurrLineTextBaseOffset = 0.0f;
  6723. // Horizontal layout mode
  6724. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  6725. SameLine();
  6726. }
  6727. void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
  6728. {
  6729. ItemSize(bb.GetSize(), text_baseline_y);
  6730. }
  6731. // Declare item bounding box for clipping and interaction.
  6732. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  6733. // declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
  6734. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
  6735. {
  6736. ImGuiContext& g = *GImGui;
  6737. ImGuiWindow* window = g.CurrentWindow;
  6738. if (id != 0)
  6739. {
  6740. // Navigation processing runs prior to clipping early-out
  6741. // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
  6742. // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
  6743. // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
  6744. // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
  6745. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
  6746. // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
  6747. // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
  6748. // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
  6749. window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
  6750. if (g.NavId == id || g.NavAnyRequest)
  6751. if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
  6752. if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
  6753. NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
  6754. // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
  6755. #ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
  6756. if (id == g.DebugItemPickerBreakId)
  6757. {
  6758. IM_DEBUG_BREAK();
  6759. g.DebugItemPickerBreakId = 0;
  6760. }
  6761. #endif
  6762. }
  6763. window->DC.LastItemId = id;
  6764. window->DC.LastItemRect = bb;
  6765. window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
  6766. g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
  6767. #ifdef IMGUI_ENABLE_TEST_ENGINE
  6768. if (id != 0)
  6769. IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
  6770. #endif
  6771. // Clipping test
  6772. const bool is_clipped = IsClippedEx(bb, id, false);
  6773. if (is_clipped)
  6774. return false;
  6775. //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
  6776. // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
  6777. if (IsMouseHoveringRect(bb.Min, bb.Max))
  6778. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
  6779. return true;
  6780. }
  6781. // Gets back to previous line and continue with horizontal layout
  6782. // offset_from_start_x == 0 : follow right after previous item
  6783. // offset_from_start_x != 0 : align to specified x position (relative to window/group left)
  6784. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  6785. // spacing_w >= 0 : enforce spacing amount
  6786. void ImGui::SameLine(float offset_from_start_x, float spacing_w)
  6787. {
  6788. ImGuiWindow* window = GetCurrentWindow();
  6789. if (window->SkipItems)
  6790. return;
  6791. ImGuiContext& g = *GImGui;
  6792. if (offset_from_start_x != 0.0f)
  6793. {
  6794. if (spacing_w < 0.0f) spacing_w = 0.0f;
  6795. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
  6796. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  6797. }
  6798. else
  6799. {
  6800. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  6801. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  6802. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  6803. }
  6804. window->DC.CurrLineSize = window->DC.PrevLineSize;
  6805. window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  6806. }
  6807. ImVec2 ImGui::GetCursorScreenPos()
  6808. {
  6809. ImGuiWindow* window = GetCurrentWindowRead();
  6810. return window->DC.CursorPos;
  6811. }
  6812. void ImGui::SetCursorScreenPos(const ImVec2& pos)
  6813. {
  6814. ImGuiWindow* window = GetCurrentWindow();
  6815. window->DC.CursorPos = pos;
  6816. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  6817. }
  6818. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  6819. // 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'.
  6820. ImVec2 ImGui::GetCursorPos()
  6821. {
  6822. ImGuiWindow* window = GetCurrentWindowRead();
  6823. return window->DC.CursorPos - window->Pos + window->Scroll;
  6824. }
  6825. float ImGui::GetCursorPosX()
  6826. {
  6827. ImGuiWindow* window = GetCurrentWindowRead();
  6828. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  6829. }
  6830. float ImGui::GetCursorPosY()
  6831. {
  6832. ImGuiWindow* window = GetCurrentWindowRead();
  6833. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  6834. }
  6835. void ImGui::SetCursorPos(const ImVec2& local_pos)
  6836. {
  6837. ImGuiWindow* window = GetCurrentWindow();
  6838. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  6839. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  6840. }
  6841. void ImGui::SetCursorPosX(float x)
  6842. {
  6843. ImGuiWindow* window = GetCurrentWindow();
  6844. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  6845. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  6846. }
  6847. void ImGui::SetCursorPosY(float y)
  6848. {
  6849. ImGuiWindow* window = GetCurrentWindow();
  6850. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  6851. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  6852. }
  6853. ImVec2 ImGui::GetCursorStartPos()
  6854. {
  6855. ImGuiWindow* window = GetCurrentWindowRead();
  6856. return window->DC.CursorStartPos - window->Pos;
  6857. }
  6858. void ImGui::Indent(float indent_w)
  6859. {
  6860. ImGuiContext& g = *GImGui;
  6861. ImGuiWindow* window = GetCurrentWindow();
  6862. window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  6863. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  6864. }
  6865. void ImGui::Unindent(float indent_w)
  6866. {
  6867. ImGuiContext& g = *GImGui;
  6868. ImGuiWindow* window = GetCurrentWindow();
  6869. window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  6870. window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
  6871. }
  6872. // Affect large frame+labels widgets only.
  6873. void ImGui::SetNextItemWidth(float item_width)
  6874. {
  6875. ImGuiContext& g = *GImGui;
  6876. g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
  6877. g.NextItemData.Width = item_width;
  6878. }
  6879. void ImGui::PushItemWidth(float item_width)
  6880. {
  6881. ImGuiContext& g = *GImGui;
  6882. ImGuiWindow* window = g.CurrentWindow;
  6883. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  6884. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
  6885. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  6886. }
  6887. void ImGui::PushMultiItemsWidths(int components, float w_full)
  6888. {
  6889. ImGuiContext& g = *GImGui;
  6890. ImGuiWindow* window = g.CurrentWindow;
  6891. const ImGuiStyle& style = g.Style;
  6892. const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  6893. const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  6894. window->DC.ItemWidthStack.push_back(w_item_last);
  6895. for (int i = 0; i < components-1; i++)
  6896. window->DC.ItemWidthStack.push_back(w_item_one);
  6897. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  6898. g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
  6899. }
  6900. void ImGui::PopItemWidth()
  6901. {
  6902. ImGuiWindow* window = GetCurrentWindow();
  6903. window->DC.ItemWidthStack.pop_back();
  6904. window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
  6905. }
  6906. // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
  6907. // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
  6908. float ImGui::CalcItemWidth()
  6909. {
  6910. ImGuiContext& g = *GImGui;
  6911. ImGuiWindow* window = g.CurrentWindow;
  6912. float w;
  6913. if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
  6914. w = g.NextItemData.Width;
  6915. else
  6916. w = window->DC.ItemWidth;
  6917. if (w < 0.0f)
  6918. {
  6919. float region_max_x = GetContentRegionMaxAbs().x;
  6920. w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
  6921. }
  6922. w = IM_FLOOR(w);
  6923. return w;
  6924. }
  6925. // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
  6926. // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
  6927. // Note that only CalcItemWidth() is publicly exposed.
  6928. // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
  6929. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
  6930. {
  6931. ImGuiWindow* window = GImGui->CurrentWindow;
  6932. ImVec2 region_max;
  6933. if (size.x < 0.0f || size.y < 0.0f)
  6934. region_max = GetContentRegionMaxAbs();
  6935. if (size.x == 0.0f)
  6936. size.x = default_w;
  6937. else if (size.x < 0.0f)
  6938. size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
  6939. if (size.y == 0.0f)
  6940. size.y = default_h;
  6941. else if (size.y < 0.0f)
  6942. size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
  6943. return size;
  6944. }
  6945. float ImGui::GetTextLineHeight()
  6946. {
  6947. ImGuiContext& g = *GImGui;
  6948. return g.FontSize;
  6949. }
  6950. float ImGui::GetTextLineHeightWithSpacing()
  6951. {
  6952. ImGuiContext& g = *GImGui;
  6953. return g.FontSize + g.Style.ItemSpacing.y;
  6954. }
  6955. float ImGui::GetFrameHeight()
  6956. {
  6957. ImGuiContext& g = *GImGui;
  6958. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  6959. }
  6960. float ImGui::GetFrameHeightWithSpacing()
  6961. {
  6962. ImGuiContext& g = *GImGui;
  6963. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  6964. }
  6965. // 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!
  6966. // FIXME: This is in window space (not screen space!).
  6967. ImVec2 ImGui::GetContentRegionMax()
  6968. {
  6969. ImGuiContext& g = *GImGui;
  6970. ImGuiWindow* window = g.CurrentWindow;
  6971. ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
  6972. if (window->DC.CurrentColumns)
  6973. mx.x = window->WorkRect.Max.x - window->Pos.x;
  6974. return mx;
  6975. }
  6976. // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
  6977. ImVec2 ImGui::GetContentRegionMaxAbs()
  6978. {
  6979. ImGuiContext& g = *GImGui;
  6980. ImGuiWindow* window = g.CurrentWindow;
  6981. ImVec2 mx = window->ContentRegionRect.Max;
  6982. if (window->DC.CurrentColumns)
  6983. mx.x = window->WorkRect.Max.x;
  6984. return mx;
  6985. }
  6986. ImVec2 ImGui::GetContentRegionAvail()
  6987. {
  6988. ImGuiWindow* window = GImGui->CurrentWindow;
  6989. return GetContentRegionMaxAbs() - window->DC.CursorPos;
  6990. }
  6991. // In window space (not screen space!)
  6992. ImVec2 ImGui::GetWindowContentRegionMin()
  6993. {
  6994. ImGuiWindow* window = GImGui->CurrentWindow;
  6995. return window->ContentRegionRect.Min - window->Pos;
  6996. }
  6997. ImVec2 ImGui::GetWindowContentRegionMax()
  6998. {
  6999. ImGuiWindow* window = GImGui->CurrentWindow;
  7000. return window->ContentRegionRect.Max - window->Pos;
  7001. }
  7002. float ImGui::GetWindowContentRegionWidth()
  7003. {
  7004. ImGuiWindow* window = GImGui->CurrentWindow;
  7005. return window->ContentRegionRect.GetWidth();
  7006. }
  7007. // 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.)
  7008. void ImGui::BeginGroup()
  7009. {
  7010. ImGuiContext& g = *GImGui;
  7011. ImGuiWindow* window = GetCurrentWindow();
  7012. window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
  7013. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  7014. group_data.BackupCursorPos = window->DC.CursorPos;
  7015. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  7016. group_data.BackupIndent = window->DC.Indent;
  7017. group_data.BackupGroupOffset = window->DC.GroupOffset;
  7018. group_data.BackupCurrLineSize = window->DC.CurrLineSize;
  7019. group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
  7020. group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
  7021. group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
  7022. group_data.EmitItem = true;
  7023. window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
  7024. window->DC.Indent = window->DC.GroupOffset;
  7025. window->DC.CursorMaxPos = window->DC.CursorPos;
  7026. window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
  7027. if (g.LogEnabled)
  7028. g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
  7029. }
  7030. void ImGui::EndGroup()
  7031. {
  7032. ImGuiContext& g = *GImGui;
  7033. ImGuiWindow* window = GetCurrentWindow();
  7034. IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
  7035. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  7036. ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
  7037. window->DC.CursorPos = group_data.BackupCursorPos;
  7038. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  7039. window->DC.Indent = group_data.BackupIndent;
  7040. window->DC.GroupOffset = group_data.BackupGroupOffset;
  7041. window->DC.CurrLineSize = group_data.BackupCurrLineSize;
  7042. window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
  7043. if (g.LogEnabled)
  7044. g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
  7045. if (!group_data.EmitItem)
  7046. {
  7047. window->DC.GroupStack.pop_back();
  7048. return;
  7049. }
  7050. 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.
  7051. ItemSize(group_bb.GetSize());
  7052. ItemAdd(group_bb, 0);
  7053. // 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.
  7054. // 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.
  7055. // Also if you grep for LastItemId you'll notice it is only used in that context.
  7056. // (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
  7057. const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
  7058. const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive;
  7059. if (group_contains_curr_active_id)
  7060. window->DC.LastItemId = g.ActiveId;
  7061. else if (group_contains_prev_active_id)
  7062. window->DC.LastItemId = g.ActiveIdPreviousFrame;
  7063. window->DC.LastItemRect = group_bb;
  7064. // Forward Edited flag
  7065. if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
  7066. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
  7067. // Forward Deactivated flag
  7068. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
  7069. if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
  7070. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
  7071. window->DC.GroupStack.pop_back();
  7072. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  7073. }
  7074. //-----------------------------------------------------------------------------
  7075. // [SECTION] SCROLLING
  7076. //-----------------------------------------------------------------------------
  7077. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
  7078. {
  7079. ImGuiContext& g = *GImGui;
  7080. ImVec2 scroll = window->Scroll;
  7081. if (window->ScrollTarget.x < FLT_MAX)
  7082. {
  7083. float cr_x = window->ScrollTargetCenterRatio.x;
  7084. float target_x = window->ScrollTarget.x;
  7085. if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x)
  7086. target_x = 0.0f;
  7087. else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x)
  7088. target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f;
  7089. scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
  7090. }
  7091. if (window->ScrollTarget.y < FLT_MAX)
  7092. {
  7093. // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
  7094. float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  7095. float cr_y = window->ScrollTargetCenterRatio.y;
  7096. float target_y = window->ScrollTarget.y;
  7097. if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
  7098. target_y = 0.0f;
  7099. if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y)
  7100. target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f;
  7101. scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
  7102. }
  7103. scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
  7104. if (!window->Collapsed && !window->SkipItems)
  7105. {
  7106. scroll.x = ImMin(scroll.x, window->ScrollMax.x);
  7107. scroll.y = ImMin(scroll.y, window->ScrollMax.y);
  7108. }
  7109. return scroll;
  7110. }
  7111. // Scroll to keep newly navigated item fully into view
  7112. ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
  7113. {
  7114. ImGuiContext& g = *GImGui;
  7115. ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
  7116. //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
  7117. ImVec2 delta_scroll;
  7118. if (!window_rect.Contains(item_rect))
  7119. {
  7120. if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
  7121. SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f);
  7122. else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
  7123. SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
  7124. if (item_rect.Min.y < window_rect.Min.y)
  7125. SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
  7126. else if (item_rect.Max.y >= window_rect.Max.y)
  7127. SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
  7128. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false);
  7129. delta_scroll = next_scroll - window->Scroll;
  7130. }
  7131. // Also scroll parent window to keep us into view if necessary
  7132. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  7133. delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
  7134. return delta_scroll;
  7135. }
  7136. float ImGui::GetScrollX()
  7137. {
  7138. ImGuiWindow* window = GImGui->CurrentWindow;
  7139. return window->Scroll.x;
  7140. }
  7141. float ImGui::GetScrollY()
  7142. {
  7143. ImGuiWindow* window = GImGui->CurrentWindow;
  7144. return window->Scroll.y;
  7145. }
  7146. float ImGui::GetScrollMaxX()
  7147. {
  7148. ImGuiWindow* window = GImGui->CurrentWindow;
  7149. return window->ScrollMax.x;
  7150. }
  7151. float ImGui::GetScrollMaxY()
  7152. {
  7153. ImGuiWindow* window = GImGui->CurrentWindow;
  7154. return window->ScrollMax.y;
  7155. }
  7156. void ImGui::SetScrollX(float scroll_x)
  7157. {
  7158. ImGuiWindow* window = GetCurrentWindow();
  7159. window->ScrollTarget.x = scroll_x;
  7160. window->ScrollTargetCenterRatio.x = 0.0f;
  7161. }
  7162. void ImGui::SetScrollY(float scroll_y)
  7163. {
  7164. ImGuiWindow* window = GetCurrentWindow();
  7165. window->ScrollTarget.y = scroll_y;
  7166. window->ScrollTargetCenterRatio.y = 0.0f;
  7167. }
  7168. void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x)
  7169. {
  7170. window->ScrollTarget.x = new_scroll_x;
  7171. window->ScrollTargetCenterRatio.x = 0.0f;
  7172. }
  7173. void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y)
  7174. {
  7175. window->ScrollTarget.y = new_scroll_y;
  7176. window->ScrollTargetCenterRatio.y = 0.0f;
  7177. }
  7178. void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
  7179. {
  7180. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  7181. IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
  7182. window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x);
  7183. window->ScrollTargetCenterRatio.x = center_x_ratio;
  7184. }
  7185. void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
  7186. {
  7187. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  7188. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  7189. const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
  7190. local_y -= decoration_up_height;
  7191. window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y);
  7192. window->ScrollTargetCenterRatio.y = center_y_ratio;
  7193. }
  7194. void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
  7195. {
  7196. ImGuiContext& g = *GImGui;
  7197. SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
  7198. }
  7199. void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
  7200. {
  7201. ImGuiContext& g = *GImGui;
  7202. SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
  7203. }
  7204. // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
  7205. void ImGui::SetScrollHereX(float center_x_ratio)
  7206. {
  7207. ImGuiContext& g = *GImGui;
  7208. ImGuiWindow* window = g.CurrentWindow;
  7209. float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space
  7210. float last_item_width = window->DC.LastItemRect.GetWidth();
  7211. target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item.
  7212. SetScrollFromPosX(target_x, center_x_ratio);
  7213. }
  7214. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  7215. void ImGui::SetScrollHereY(float center_y_ratio)
  7216. {
  7217. ImGuiContext& g = *GImGui;
  7218. ImGuiWindow* window = g.CurrentWindow;
  7219. float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
  7220. target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
  7221. SetScrollFromPosY(target_y, center_y_ratio);
  7222. }
  7223. //-----------------------------------------------------------------------------
  7224. // [SECTION] TOOLTIPS
  7225. //-----------------------------------------------------------------------------
  7226. void ImGui::BeginTooltip()
  7227. {
  7228. BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
  7229. }
  7230. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
  7231. {
  7232. ImGuiContext& g = *GImGui;
  7233. if (g.DragDropWithinSourceOrTarget)
  7234. {
  7235. // 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)
  7236. // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
  7237. // 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.
  7238. //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
  7239. ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
  7240. SetNextWindowPos(tooltip_pos);
  7241. SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
  7242. //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
  7243. tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
  7244. }
  7245. char window_name[16];
  7246. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
  7247. if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
  7248. if (ImGuiWindow* window = FindWindowByName(window_name))
  7249. if (window->Active)
  7250. {
  7251. // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
  7252. window->Hidden = true;
  7253. window->HiddenFramesCanSkipItems = 1;
  7254. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
  7255. }
  7256. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoDocking;
  7257. Begin(window_name, NULL, flags | extra_flags);
  7258. }
  7259. void ImGui::EndTooltip()
  7260. {
  7261. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  7262. End();
  7263. }
  7264. void ImGui::SetTooltipV(const char* fmt, va_list args)
  7265. {
  7266. BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
  7267. TextV(fmt, args);
  7268. EndTooltip();
  7269. }
  7270. void ImGui::SetTooltip(const char* fmt, ...)
  7271. {
  7272. va_list args;
  7273. va_start(args, fmt);
  7274. SetTooltipV(fmt, args);
  7275. va_end(args);
  7276. }
  7277. //-----------------------------------------------------------------------------
  7278. // [SECTION] POPUPS
  7279. //-----------------------------------------------------------------------------
  7280. bool ImGui::IsPopupOpen(ImGuiID id)
  7281. {
  7282. ImGuiContext& g = *GImGui;
  7283. return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
  7284. }
  7285. bool ImGui::IsPopupOpen(const char* str_id)
  7286. {
  7287. ImGuiContext& g = *GImGui;
  7288. return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
  7289. }
  7290. ImGuiWindow* ImGui::GetTopMostPopupModal()
  7291. {
  7292. ImGuiContext& g = *GImGui;
  7293. for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
  7294. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  7295. if (popup->Flags & ImGuiWindowFlags_Modal)
  7296. return popup;
  7297. return NULL;
  7298. }
  7299. void ImGui::OpenPopup(const char* str_id)
  7300. {
  7301. ImGuiContext& g = *GImGui;
  7302. OpenPopupEx(g.CurrentWindow->GetID(str_id));
  7303. }
  7304. // Mark popup as open (toggle toward open state).
  7305. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  7306. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  7307. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  7308. void ImGui::OpenPopupEx(ImGuiID id)
  7309. {
  7310. ImGuiContext& g = *GImGui;
  7311. ImGuiWindow* parent_window = g.CurrentWindow;
  7312. int current_stack_size = g.BeginPopupStack.Size;
  7313. ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
  7314. popup_ref.PopupId = id;
  7315. popup_ref.Window = NULL;
  7316. popup_ref.SourceWindow = g.NavWindow;
  7317. popup_ref.OpenFrameCount = g.FrameCount;
  7318. popup_ref.OpenParentId = parent_window->IDStack.back();
  7319. popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
  7320. popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
  7321. IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id);
  7322. if (g.OpenPopupStack.Size < current_stack_size + 1)
  7323. {
  7324. g.OpenPopupStack.push_back(popup_ref);
  7325. }
  7326. else
  7327. {
  7328. // 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
  7329. // 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
  7330. // 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.
  7331. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
  7332. {
  7333. g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
  7334. }
  7335. else
  7336. {
  7337. // Close child popups if any, then flag popup for open/reopen
  7338. g.OpenPopupStack.resize(current_stack_size + 1);
  7339. g.OpenPopupStack[current_stack_size] = popup_ref;
  7340. }
  7341. // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
  7342. // This is equivalent to what ClosePopupToLevel() does.
  7343. //if (g.OpenPopupStack[current_stack_size].PopupId == id)
  7344. // FocusWindow(parent_window);
  7345. }
  7346. }
  7347. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
  7348. {
  7349. ImGuiContext& g = *GImGui;
  7350. if (g.OpenPopupStack.empty())
  7351. return;
  7352. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  7353. // Don't close our own child popup windows.
  7354. int popup_count_to_keep = 0;
  7355. if (ref_window)
  7356. {
  7357. // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
  7358. for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
  7359. {
  7360. ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
  7361. if (!popup.Window)
  7362. continue;
  7363. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  7364. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  7365. continue;
  7366. // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow)
  7367. bool popup_or_descendent_is_ref_window = false;
  7368. for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++)
  7369. if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window)
  7370. if (popup_window->RootWindow == ref_window->RootWindow)
  7371. popup_or_descendent_is_ref_window = true;
  7372. if (!popup_or_descendent_is_ref_window)
  7373. break;
  7374. }
  7375. }
  7376. 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
  7377. {
  7378. IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
  7379. ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
  7380. }
  7381. }
  7382. void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
  7383. {
  7384. ImGuiContext& g = *GImGui;
  7385. IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
  7386. IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
  7387. ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
  7388. ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
  7389. g.OpenPopupStack.resize(remaining);
  7390. if (restore_focus_to_window_under_popup)
  7391. {
  7392. if (focus_window && !focus_window->WasActive && popup_window)
  7393. {
  7394. // Fallback
  7395. FocusTopMostWindowUnderOne(popup_window, NULL);
  7396. }
  7397. else
  7398. {
  7399. if (g.NavLayer == 0 && focus_window)
  7400. focus_window = NavRestoreLastChildNavWindow(focus_window);
  7401. FocusWindow(focus_window);
  7402. }
  7403. }
  7404. }
  7405. // Close the popup we have begin-ed into.
  7406. void ImGui::CloseCurrentPopup()
  7407. {
  7408. ImGuiContext& g = *GImGui;
  7409. int popup_idx = g.BeginPopupStack.Size - 1;
  7410. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  7411. return;
  7412. // Closing a menu closes its top-most parent popup (unless a modal)
  7413. while (popup_idx > 0)
  7414. {
  7415. ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
  7416. ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
  7417. bool close_parent = false;
  7418. if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
  7419. if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
  7420. close_parent = true;
  7421. if (!close_parent)
  7422. break;
  7423. popup_idx--;
  7424. }
  7425. IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
  7426. ClosePopupToLevel(popup_idx, true);
  7427. // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
  7428. // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
  7429. // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
  7430. if (ImGuiWindow* window = g.NavWindow)
  7431. window->DC.NavHideHighlightOneFrame = true;
  7432. }
  7433. bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
  7434. {
  7435. ImGuiContext& g = *GImGui;
  7436. if (!IsPopupOpen(id))
  7437. {
  7438. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7439. return false;
  7440. }
  7441. char name[20];
  7442. if (flags & ImGuiWindowFlags_ChildMenu)
  7443. ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
  7444. else
  7445. ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
  7446. flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
  7447. bool is_open = Begin(name, NULL, flags);
  7448. if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
  7449. EndPopup();
  7450. return is_open;
  7451. }
  7452. bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
  7453. {
  7454. ImGuiContext& g = *GImGui;
  7455. if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
  7456. {
  7457. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7458. return false;
  7459. }
  7460. flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
  7461. return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
  7462. }
  7463. // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
  7464. // 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.
  7465. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
  7466. {
  7467. ImGuiContext& g = *GImGui;
  7468. ImGuiWindow* window = g.CurrentWindow;
  7469. const ImGuiID id = window->GetID(name);
  7470. if (!IsPopupOpen(id))
  7471. {
  7472. g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
  7473. return false;
  7474. }
  7475. // Center modal windows by default
  7476. // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
  7477. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
  7478. {
  7479. ImGuiViewportP* viewport = window->WasActive ? window->Viewport : (ImGuiViewportP*)GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
  7480. SetNextWindowPos(viewport->GetMainRect().GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
  7481. }
  7482. flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking;
  7483. const bool is_open = Begin(name, p_open, flags);
  7484. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  7485. {
  7486. EndPopup();
  7487. if (is_open)
  7488. ClosePopupToLevel(g.BeginPopupStack.Size, true);
  7489. return false;
  7490. }
  7491. return is_open;
  7492. }
  7493. void ImGui::EndPopup()
  7494. {
  7495. ImGuiContext& g = *GImGui;
  7496. ImGuiWindow* window = g.CurrentWindow;
  7497. IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  7498. IM_ASSERT(g.BeginPopupStack.Size > 0);
  7499. // Make all menus and popups wrap around for now, may need to expose that policy.
  7500. NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
  7501. // Child-popups don't need to be layed out
  7502. IM_ASSERT(g.WithinEndChild == false);
  7503. if (window->Flags & ImGuiWindowFlags_ChildWindow)
  7504. g.WithinEndChild = true;
  7505. End();
  7506. g.WithinEndChild = false;
  7507. }
  7508. bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiMouseButton mouse_button)
  7509. {
  7510. ImGuiWindow* window = GImGui->CurrentWindow;
  7511. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  7512. {
  7513. 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!
  7514. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  7515. OpenPopupEx(id);
  7516. return true;
  7517. }
  7518. return false;
  7519. }
  7520. // This is a helper to handle the simplest case of associating one named popup to one given widget.
  7521. // You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
  7522. // You can pass a NULL str_id to use the identifier of the last item.
  7523. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button)
  7524. {
  7525. ImGuiWindow* window = GImGui->CurrentWindow;
  7526. if (window->SkipItems)
  7527. return false;
  7528. 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!
  7529. IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  7530. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  7531. OpenPopupEx(id);
  7532. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  7533. }
  7534. bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items)
  7535. {
  7536. if (!str_id)
  7537. str_id = "window_context";
  7538. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  7539. if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  7540. if (also_over_items || !IsAnyItemHovered())
  7541. OpenPopupEx(id);
  7542. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  7543. }
  7544. bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button)
  7545. {
  7546. if (!str_id)
  7547. str_id = "void_context";
  7548. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  7549. if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
  7550. OpenPopupEx(id);
  7551. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  7552. }
  7553. // 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.)
  7554. // 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.
  7555. // (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
  7556. // information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
  7557. // this allows us to have tooltips/popups displayed out of the parent viewport.)
  7558. ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
  7559. {
  7560. ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
  7561. //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
  7562. //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
  7563. // Combo Box policy (we want a connecting edge)
  7564. if (policy == ImGuiPopupPositionPolicy_ComboBox)
  7565. {
  7566. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
  7567. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  7568. {
  7569. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  7570. if (n != -1 && dir == *last_dir) // Already tried this direction?
  7571. continue;
  7572. ImVec2 pos;
  7573. if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
  7574. if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
  7575. if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
  7576. if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
  7577. if (!r_outer.Contains(ImRect(pos, pos + size)))
  7578. continue;
  7579. *last_dir = dir;
  7580. return pos;
  7581. }
  7582. }
  7583. // Default popup policy
  7584. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
  7585. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  7586. {
  7587. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  7588. if (n != -1 && dir == *last_dir) // Already tried this direction?
  7589. continue;
  7590. 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);
  7591. 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);
  7592. if (avail_w < size.x || avail_h < size.y)
  7593. continue;
  7594. ImVec2 pos;
  7595. pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
  7596. pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
  7597. *last_dir = dir;
  7598. return pos;
  7599. }
  7600. // Fallback, try to keep within display
  7601. *last_dir = ImGuiDir_None;
  7602. ImVec2 pos = ref_pos;
  7603. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  7604. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  7605. return pos;
  7606. }
  7607. // Note that this is used for popups, which can overlap the non work-area of individual viewports.
  7608. ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
  7609. {
  7610. ImGuiContext& g = *GImGui;
  7611. ImRect r_screen;
  7612. if (window->ViewportAllowPlatformMonitorExtend >= 0)
  7613. {
  7614. // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
  7615. const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
  7616. r_screen.Min = monitor.WorkPos;
  7617. r_screen.Max = monitor.WorkPos + monitor.WorkSize;
  7618. }
  7619. else
  7620. {
  7621. // Use the full viewport area (not work area) for popups
  7622. r_screen.Min = window->Viewport->Pos;
  7623. r_screen.Max = window->Viewport->Pos + window->Viewport->Size;
  7624. }
  7625. ImVec2 padding = g.Style.DisplaySafeAreaPadding;
  7626. r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
  7627. return r_screen;
  7628. }
  7629. ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
  7630. {
  7631. ImGuiContext& g = *GImGui;
  7632. if (window->Flags & ImGuiWindowFlags_ChildMenu)
  7633. {
  7634. // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
  7635. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  7636. ImGuiWindow* parent_window = window->ParentWindow;
  7637. 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).
  7638. ImRect r_outer = GetWindowAllowedExtentRect(window);
  7639. ImRect r_avoid;
  7640. if (parent_window->DC.MenuBarAppending)
  7641. 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
  7642. else
  7643. 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);
  7644. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
  7645. }
  7646. if (window->Flags & ImGuiWindowFlags_Popup)
  7647. {
  7648. ImRect r_outer = GetWindowAllowedExtentRect(window);
  7649. ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
  7650. return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
  7651. }
  7652. if (window->Flags & ImGuiWindowFlags_Tooltip)
  7653. {
  7654. // Position tooltip (always follows mouse)
  7655. float sc = g.Style.MouseCursorScale;
  7656. ImVec2 ref_pos = NavCalcPreferredRefPos();
  7657. ImRect r_outer = GetWindowAllowedExtentRect(window);
  7658. ImRect r_avoid;
  7659. if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
  7660. r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
  7661. else
  7662. 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.
  7663. ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
  7664. if (window->AutoPosLastDirection == ImGuiDir_None)
  7665. pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  7666. return pos;
  7667. }
  7668. IM_ASSERT(0);
  7669. return window->Pos;
  7670. }
  7671. //-----------------------------------------------------------------------------
  7672. // [SECTION] KEYBOARD/GAMEPAD NAVIGATION
  7673. //-----------------------------------------------------------------------------
  7674. // FIXME-NAV: The existence of SetNavID vs SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing,
  7675. // and needs some explanation or serious refactoring.
  7676. void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id)
  7677. {
  7678. ImGuiContext& g = *GImGui;
  7679. IM_ASSERT(g.NavWindow);
  7680. IM_ASSERT(nav_layer == 0 || nav_layer == 1);
  7681. g.NavId = id;
  7682. g.NavFocusScopeId = focus_scope_id;
  7683. g.NavWindow->NavLastIds[nav_layer] = id;
  7684. }
  7685. void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
  7686. {
  7687. ImGuiContext& g = *GImGui;
  7688. SetNavID(id, nav_layer, focus_scope_id);
  7689. g.NavWindow->NavRectRel[nav_layer] = rect_rel;
  7690. g.NavMousePosDirty = true;
  7691. g.NavDisableHighlight = false;
  7692. g.NavDisableMouseHover = true;
  7693. }
  7694. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
  7695. {
  7696. ImGuiContext& g = *GImGui;
  7697. IM_ASSERT(id != 0);
  7698. // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
  7699. // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
  7700. const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
  7701. if (g.NavWindow != window)
  7702. g.NavInitRequest = false;
  7703. g.NavWindow = window;
  7704. g.NavId = id;
  7705. g.NavLayer = nav_layer;
  7706. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  7707. window->NavLastIds[nav_layer] = id;
  7708. if (window->DC.LastItemId == id)
  7709. window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
  7710. if (g.ActiveIdSource == ImGuiInputSource_Nav)
  7711. g.NavDisableMouseHover = true;
  7712. else
  7713. g.NavDisableHighlight = true;
  7714. }
  7715. ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
  7716. {
  7717. if (ImFabs(dx) > ImFabs(dy))
  7718. return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
  7719. return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
  7720. }
  7721. static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
  7722. {
  7723. if (a1 < b0)
  7724. return a1 - b0;
  7725. if (b1 < a0)
  7726. return a0 - b1;
  7727. return 0.0f;
  7728. }
  7729. static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
  7730. {
  7731. if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
  7732. {
  7733. r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
  7734. r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
  7735. }
  7736. else
  7737. {
  7738. r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
  7739. r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
  7740. }
  7741. }
  7742. // Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
  7743. static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
  7744. {
  7745. ImGuiContext& g = *GImGui;
  7746. ImGuiWindow* window = g.CurrentWindow;
  7747. if (g.NavLayer != window->DC.NavLayerCurrent)
  7748. return false;
  7749. const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
  7750. g.NavScoringCount++;
  7751. // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
  7752. if (window->ParentWindow == g.NavWindow)
  7753. {
  7754. IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
  7755. if (!window->ClipRect.Overlaps(cand))
  7756. return false;
  7757. cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
  7758. }
  7759. // 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)
  7760. // For example, this ensure that items in one column are not reached when moving vertically from items in another column.
  7761. NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
  7762. // Compute distance between boxes
  7763. // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
  7764. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
  7765. 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
  7766. if (dby != 0.0f && dbx != 0.0f)
  7767. dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
  7768. float dist_box = ImFabs(dbx) + ImFabs(dby);
  7769. // 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)
  7770. float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
  7771. float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
  7772. float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
  7773. // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
  7774. ImGuiDir quadrant;
  7775. float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
  7776. if (dbx != 0.0f || dby != 0.0f)
  7777. {
  7778. // For non-overlapping boxes, use distance between boxes
  7779. dax = dbx;
  7780. day = dby;
  7781. dist_axial = dist_box;
  7782. quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
  7783. }
  7784. else if (dcx != 0.0f || dcy != 0.0f)
  7785. {
  7786. // For overlapping boxes with different centers, use distance between centers
  7787. dax = dcx;
  7788. day = dcy;
  7789. dist_axial = dist_center;
  7790. quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
  7791. }
  7792. else
  7793. {
  7794. // 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)
  7795. quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
  7796. }
  7797. #if IMGUI_DEBUG_NAV_SCORING
  7798. char buf[128];
  7799. if (IsMouseHoveringRect(cand.Min, cand.Max))
  7800. {
  7801. 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]);
  7802. ImDrawList* draw_list = GetForegroundDrawList(window);
  7803. draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
  7804. draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
  7805. draw_list->AddRectFilled(cand.Max - ImVec2(4,4), cand.Max + CalcTextSize(buf) + ImVec2(4,4), IM_COL32(40,0,0,150));
  7806. draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
  7807. }
  7808. else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
  7809. {
  7810. if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
  7811. if (quadrant == g.NavMoveDir)
  7812. {
  7813. ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
  7814. ImDrawList* draw_list = GetForegroundDrawList(window);
  7815. draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
  7816. draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
  7817. }
  7818. }
  7819. #endif
  7820. // Is it in the quadrant we're interesting in moving to?
  7821. bool new_best = false;
  7822. if (quadrant == g.NavMoveDir)
  7823. {
  7824. // Does it beat the current best candidate?
  7825. if (dist_box < result->DistBox)
  7826. {
  7827. result->DistBox = dist_box;
  7828. result->DistCenter = dist_center;
  7829. return true;
  7830. }
  7831. if (dist_box == result->DistBox)
  7832. {
  7833. // Try using distance between center points to break ties
  7834. if (dist_center < result->DistCenter)
  7835. {
  7836. result->DistCenter = dist_center;
  7837. new_best = true;
  7838. }
  7839. else if (dist_center == result->DistCenter)
  7840. {
  7841. // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
  7842. // (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),
  7843. // 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.
  7844. if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
  7845. new_best = true;
  7846. }
  7847. }
  7848. }
  7849. // 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
  7850. // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
  7851. // 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.
  7852. // 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.
  7853. // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
  7854. if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
  7855. if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
  7856. 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))
  7857. {
  7858. result->DistAxial = dist_axial;
  7859. new_best = true;
  7860. }
  7861. return new_best;
  7862. }
  7863. // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
  7864. static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
  7865. {
  7866. ImGuiContext& g = *GImGui;
  7867. //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.
  7868. // return;
  7869. const ImGuiItemFlags item_flags = window->DC.ItemFlags;
  7870. const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
  7871. // Process Init Request
  7872. if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
  7873. {
  7874. // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
  7875. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
  7876. {
  7877. g.NavInitResultId = id;
  7878. g.NavInitResultRectRel = nav_bb_rel;
  7879. }
  7880. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
  7881. {
  7882. g.NavInitRequest = false; // Found a match, clear request
  7883. NavUpdateAnyRequestFlag();
  7884. }
  7885. }
  7886. // Process Move Request (scoring for navigation)
  7887. // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
  7888. if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav)))
  7889. {
  7890. ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  7891. #if IMGUI_DEBUG_NAV_SCORING
  7892. // [DEBUG] Score all items in NavWindow at all times
  7893. if (!g.NavMoveRequest)
  7894. g.NavMoveDir = g.NavMoveDirLast;
  7895. bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
  7896. #else
  7897. bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
  7898. #endif
  7899. if (new_best)
  7900. {
  7901. result->Window = window;
  7902. result->ID = id;
  7903. result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
  7904. result->RectRel = nav_bb_rel;
  7905. }
  7906. // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
  7907. const float VISIBLE_RATIO = 0.70f;
  7908. if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
  7909. 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)
  7910. if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
  7911. {
  7912. result = &g.NavMoveResultLocalVisibleSet;
  7913. result->Window = window;
  7914. result->ID = id;
  7915. result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
  7916. result->RectRel = nav_bb_rel;
  7917. }
  7918. }
  7919. // Update window-relative bounding box of navigated item
  7920. if (g.NavId == id)
  7921. {
  7922. g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
  7923. g.NavLayer = window->DC.NavLayerCurrent;
  7924. g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
  7925. g.NavIdIsAlive = true;
  7926. g.NavIdTabCounter = window->DC.FocusCounterTabStop;
  7927. window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
  7928. }
  7929. }
  7930. bool ImGui::NavMoveRequestButNoResultYet()
  7931. {
  7932. ImGuiContext& g = *GImGui;
  7933. return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
  7934. }
  7935. void ImGui::NavMoveRequestCancel()
  7936. {
  7937. ImGuiContext& g = *GImGui;
  7938. g.NavMoveRequest = false;
  7939. NavUpdateAnyRequestFlag();
  7940. }
  7941. void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
  7942. {
  7943. ImGuiContext& g = *GImGui;
  7944. IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
  7945. NavMoveRequestCancel();
  7946. g.NavMoveDir = move_dir;
  7947. g.NavMoveClipDir = clip_dir;
  7948. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
  7949. g.NavMoveRequestFlags = move_flags;
  7950. g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
  7951. }
  7952. void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
  7953. {
  7954. ImGuiContext& g = *GImGui;
  7955. if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
  7956. return;
  7957. IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
  7958. ImRect bb_rel = window->NavRectRel[0];
  7959. ImGuiDir clip_dir = g.NavMoveDir;
  7960. if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  7961. {
  7962. bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
  7963. if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
  7964. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  7965. }
  7966. if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
  7967. {
  7968. bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
  7969. if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
  7970. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  7971. }
  7972. if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  7973. {
  7974. bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
  7975. if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
  7976. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  7977. }
  7978. if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
  7979. {
  7980. bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
  7981. if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
  7982. NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
  7983. }
  7984. }
  7985. // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
  7986. // This way we could find the last focused window among our children. It would be much less confusing this way?
  7987. static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
  7988. {
  7989. ImGuiWindow* parent = nav_window;
  7990. while (parent && parent->RootWindowDockStop != parent && (parent->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  7991. parent = parent->ParentWindow;
  7992. if (parent && parent != nav_window)
  7993. parent->NavLastChildNavWindow = nav_window;
  7994. }
  7995. // Restore the last focused child.
  7996. // Call when we are expected to land on the Main Layer (0) after FocusWindow()
  7997. static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
  7998. {
  7999. if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
  8000. return window->NavLastChildNavWindow;
  8001. if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
  8002. if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
  8003. return tab->Window;
  8004. return window;
  8005. }
  8006. static void NavRestoreLayer(ImGuiNavLayer layer)
  8007. {
  8008. ImGuiContext& g = *GImGui;
  8009. g.NavLayer = layer;
  8010. if (layer == 0)
  8011. g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
  8012. ImGuiWindow* window = g.NavWindow;
  8013. if (window->NavLastIds[layer] != 0)
  8014. ImGui::SetNavIDWithRectRel(window->NavLastIds[layer], layer, 0, g.NavWindow->NavRectRel[layer]);
  8015. else
  8016. ImGui::NavInitWindow(window, true);
  8017. }
  8018. static inline void ImGui::NavUpdateAnyRequestFlag()
  8019. {
  8020. ImGuiContext& g = *GImGui;
  8021. g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
  8022. if (g.NavAnyRequest)
  8023. IM_ASSERT(g.NavWindow != NULL);
  8024. }
  8025. // This needs to be called before we submit any widget (aka in or before Begin)
  8026. void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
  8027. {
  8028. ImGuiContext& g = *GImGui;
  8029. IM_ASSERT(window == g.NavWindow);
  8030. bool init_for_nav = false;
  8031. if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
  8032. if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
  8033. init_for_nav = true;
  8034. //IMGUI_DEBUG_LOG("[Nav] NavInitWindow() init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
  8035. if (init_for_nav)
  8036. {
  8037. SetNavID(0, g.NavLayer, 0);
  8038. g.NavInitRequest = true;
  8039. g.NavInitRequestFromMove = false;
  8040. g.NavInitResultId = 0;
  8041. g.NavInitResultRectRel = ImRect();
  8042. NavUpdateAnyRequestFlag();
  8043. }
  8044. else
  8045. {
  8046. g.NavId = window->NavLastIds[0];
  8047. g.NavFocusScopeId = 0;
  8048. }
  8049. }
  8050. static ImVec2 ImGui::NavCalcPreferredRefPos()
  8051. {
  8052. ImGuiContext& g = *GImGui;
  8053. if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
  8054. {
  8055. // Mouse (we need a fallback in case the mouse becomes invalid after being used)
  8056. if (IsMousePosValid(&g.IO.MousePos))
  8057. return g.IO.MousePos;
  8058. return g.LastValidMousePos;
  8059. }
  8060. else
  8061. {
  8062. // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
  8063. const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
  8064. 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()));
  8065. ImRect visible_rect = g.NavWindow->Viewport->GetMainRect();
  8066. return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
  8067. }
  8068. }
  8069. float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
  8070. {
  8071. ImGuiContext& g = *GImGui;
  8072. if (mode == ImGuiInputReadMode_Down)
  8073. return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
  8074. const float t = g.IO.NavInputsDownDuration[n];
  8075. if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
  8076. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
  8077. if (t < 0.0f)
  8078. return 0.0f;
  8079. if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
  8080. return (t == 0.0f) ? 1.0f : 0.0f;
  8081. if (mode == ImGuiInputReadMode_Repeat)
  8082. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
  8083. if (mode == ImGuiInputReadMode_RepeatSlow)
  8084. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
  8085. if (mode == ImGuiInputReadMode_RepeatFast)
  8086. return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
  8087. return 0.0f;
  8088. }
  8089. ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
  8090. {
  8091. ImVec2 delta(0.0f, 0.0f);
  8092. if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
  8093. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
  8094. if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
  8095. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
  8096. if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
  8097. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
  8098. if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
  8099. delta *= slow_factor;
  8100. if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
  8101. delta *= fast_factor;
  8102. return delta;
  8103. }
  8104. static void ImGui::NavUpdate()
  8105. {
  8106. ImGuiContext& g = *GImGui;
  8107. g.IO.WantSetMousePos = false;
  8108. #if 0
  8109. 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);
  8110. #endif
  8111. // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
  8112. // (do it before we map Keyboard input!)
  8113. bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
  8114. bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
  8115. if (nav_gamepad_active)
  8116. if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
  8117. g.NavInputSource = ImGuiInputSource_NavGamepad;
  8118. // Update Keyboard->Nav inputs mapping
  8119. if (nav_keyboard_active)
  8120. {
  8121. #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
  8122. NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
  8123. NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
  8124. NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
  8125. NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
  8126. NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
  8127. NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
  8128. NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
  8129. if (g.IO.KeyCtrl)
  8130. g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
  8131. if (g.IO.KeyShift)
  8132. g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
  8133. if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
  8134. g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
  8135. #undef NAV_MAP_KEY
  8136. }
  8137. memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
  8138. for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
  8139. g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  8140. // Process navigation init request (select first/default focus)
  8141. // 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)
  8142. if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow)
  8143. {
  8144. // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
  8145. //IMGUI_DEBUG_LOG("[Nav] Apply NavInitRequest result: 0x%08X Layer %d in \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
  8146. if (g.NavInitRequestFromMove)
  8147. SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
  8148. else
  8149. SetNavID(g.NavInitResultId, g.NavLayer, 0);
  8150. g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
  8151. }
  8152. g.NavInitRequest = false;
  8153. g.NavInitRequestFromMove = false;
  8154. g.NavInitResultId = 0;
  8155. g.NavJustMovedToId = 0;
  8156. // Process navigation move request
  8157. if (g.NavMoveRequest)
  8158. NavUpdateMoveResult();
  8159. // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
  8160. if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
  8161. {
  8162. IM_ASSERT(g.NavMoveRequest);
  8163. if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
  8164. g.NavDisableHighlight = false;
  8165. g.NavMoveRequestForward = ImGuiNavForward_None;
  8166. }
  8167. // Apply application mouse position movement, after we had a chance to process move request result.
  8168. if (g.NavMousePosDirty && g.NavIdIsAlive)
  8169. {
  8170. // Set mouse position given our knowledge of the navigated item position from last frame
  8171. if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
  8172. {
  8173. if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
  8174. {
  8175. g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
  8176. g.IO.WantSetMousePos = true;
  8177. }
  8178. }
  8179. g.NavMousePosDirty = false;
  8180. }
  8181. g.NavIdIsAlive = false;
  8182. g.NavJustTabbedId = 0;
  8183. IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
  8184. // 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
  8185. if (g.NavWindow)
  8186. NavSaveLastChildNavWindowIntoParent(g.NavWindow);
  8187. if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
  8188. g.NavWindow->NavLastChildNavWindow = NULL;
  8189. // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
  8190. NavUpdateWindowing();
  8191. // Set output flags for user application
  8192. g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
  8193. g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
  8194. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  8195. if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
  8196. {
  8197. if (g.ActiveId != 0)
  8198. {
  8199. if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
  8200. ClearActiveID();
  8201. }
  8202. else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow && g.NavWindow != g.NavWindow->RootWindowDockStop)
  8203. {
  8204. // Exit child window
  8205. ImGuiWindow* child_window = g.NavWindow;
  8206. ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
  8207. IM_ASSERT(child_window->ChildId != 0);
  8208. FocusWindow(parent_window);
  8209. SetNavID(child_window->ChildId, 0, 0);
  8210. // Reassigning with same value, we're being explicit here.
  8211. g.NavIdIsAlive = false; // -V1048
  8212. if (g.NavDisableMouseHover)
  8213. g.NavMousePosDirty = true;
  8214. }
  8215. else if (g.OpenPopupStack.Size > 0)
  8216. {
  8217. // Close open popup/menu
  8218. if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
  8219. ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
  8220. }
  8221. else if (g.NavLayer != 0)
  8222. {
  8223. // Leave the "menu" layer
  8224. NavRestoreLayer(ImGuiNavLayer_Main);
  8225. }
  8226. else
  8227. {
  8228. // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
  8229. if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
  8230. g.NavWindow->NavLastIds[0] = 0;
  8231. g.NavId = g.NavFocusScopeId = 0;
  8232. }
  8233. }
  8234. // Process manual activation request
  8235. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
  8236. if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8237. {
  8238. bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
  8239. bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
  8240. if (g.ActiveId == 0 && activate_pressed)
  8241. g.NavActivateId = g.NavId;
  8242. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
  8243. g.NavActivateDownId = g.NavId;
  8244. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
  8245. g.NavActivatePressedId = g.NavId;
  8246. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
  8247. g.NavInputId = g.NavId;
  8248. }
  8249. if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8250. g.NavDisableHighlight = true;
  8251. if (g.NavActivateId != 0)
  8252. IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
  8253. g.NavMoveRequest = false;
  8254. // Process programmatic activation request
  8255. if (g.NavNextActivateId != 0)
  8256. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
  8257. g.NavNextActivateId = 0;
  8258. // Initiate directional inputs request
  8259. if (g.NavMoveRequestForward == ImGuiNavForward_None)
  8260. {
  8261. g.NavMoveDir = ImGuiDir_None;
  8262. g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
  8263. if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  8264. {
  8265. const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
  8266. if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
  8267. if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
  8268. if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
  8269. if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
  8270. }
  8271. g.NavMoveClipDir = g.NavMoveDir;
  8272. }
  8273. else
  8274. {
  8275. // 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)
  8276. // (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
  8277. IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
  8278. IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
  8279. g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
  8280. }
  8281. // Update PageUp/PageDown/Home/End scroll
  8282. // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
  8283. float nav_scoring_rect_offset_y = 0.0f;
  8284. if (nav_keyboard_active)
  8285. nav_scoring_rect_offset_y = NavUpdatePageUpPageDown();
  8286. // 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
  8287. if (g.NavMoveDir != ImGuiDir_None)
  8288. {
  8289. g.NavMoveRequest = true;
  8290. g.NavMoveDirLast = g.NavMoveDir;
  8291. }
  8292. if (g.NavMoveRequest && g.NavId == 0)
  8293. {
  8294. //IMGUI_DEBUG_LOG("[Nav] NavInitRequest from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
  8295. g.NavInitRequest = g.NavInitRequestFromMove = true;
  8296. // Reassigning with same value, we're being explicit here.
  8297. g.NavInitResultId = 0; // -V1048
  8298. g.NavDisableHighlight = false;
  8299. }
  8300. NavUpdateAnyRequestFlag();
  8301. // Scrolling
  8302. if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
  8303. {
  8304. // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
  8305. ImGuiWindow* window = g.NavWindow;
  8306. const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * g.IO.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
  8307. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
  8308. {
  8309. if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
  8310. SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
  8311. if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
  8312. SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
  8313. }
  8314. // *Normal* Manual scroll with NavScrollXXX keys
  8315. // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
  8316. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
  8317. if (scroll_dir.x != 0.0f && window->ScrollbarX)
  8318. {
  8319. SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
  8320. g.NavMoveFromClampedRefRect = true;
  8321. }
  8322. if (scroll_dir.y != 0.0f)
  8323. {
  8324. SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
  8325. g.NavMoveFromClampedRefRect = true;
  8326. }
  8327. }
  8328. // Reset search results
  8329. g.NavMoveResultLocal.Clear();
  8330. g.NavMoveResultLocalVisibleSet.Clear();
  8331. g.NavMoveResultOther.Clear();
  8332. // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
  8333. if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
  8334. {
  8335. ImGuiWindow* window = g.NavWindow;
  8336. ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
  8337. if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
  8338. {
  8339. float pad = window->CalcFontSize() * 0.5f;
  8340. 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
  8341. window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
  8342. g.NavId = g.NavFocusScopeId = 0;
  8343. }
  8344. g.NavMoveFromClampedRefRect = false;
  8345. }
  8346. // 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)
  8347. ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
  8348. g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : ImRect(0,0,0,0);
  8349. g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
  8350. g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
  8351. g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
  8352. IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
  8353. //GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
  8354. g.NavScoringCount = 0;
  8355. #if IMGUI_DEBUG_NAV_RECTS
  8356. if (g.NavWindow)
  8357. {
  8358. ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
  8359. 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]
  8360. 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); }
  8361. }
  8362. #endif
  8363. }
  8364. // Apply result from previous frame navigation directional move request
  8365. static void ImGui::NavUpdateMoveResult()
  8366. {
  8367. ImGuiContext& g = *GImGui;
  8368. if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
  8369. {
  8370. // 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)
  8371. if (g.NavId != 0)
  8372. {
  8373. g.NavDisableHighlight = false;
  8374. g.NavDisableMouseHover = true;
  8375. }
  8376. return;
  8377. }
  8378. // Select which result to use
  8379. ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  8380. // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
  8381. if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
  8382. if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
  8383. result = &g.NavMoveResultLocalVisibleSet;
  8384. // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
  8385. if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
  8386. if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
  8387. result = &g.NavMoveResultOther;
  8388. IM_ASSERT(g.NavWindow && result->Window);
  8389. // Scroll to keep newly navigated item fully into view.
  8390. if (g.NavLayer == 0)
  8391. {
  8392. ImVec2 delta_scroll;
  8393. if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
  8394. {
  8395. float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
  8396. delta_scroll.y = result->Window->Scroll.y - scroll_target;
  8397. SetScrollY(result->Window, scroll_target);
  8398. }
  8399. else
  8400. {
  8401. ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
  8402. delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
  8403. }
  8404. // Offset our result position so mouse position can be applied immediately after in NavUpdate()
  8405. result->RectRel.TranslateX(-delta_scroll.x);
  8406. result->RectRel.TranslateY(-delta_scroll.y);
  8407. }
  8408. ClearActiveID();
  8409. g.NavWindow = result->Window;
  8410. if (g.NavId != result->ID)
  8411. {
  8412. // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
  8413. g.NavJustMovedToId = result->ID;
  8414. g.NavJustMovedToFocusScopeId = result->FocusScopeId;
  8415. }
  8416. SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
  8417. g.NavMoveFromClampedRefRect = false;
  8418. }
  8419. // Handle PageUp/PageDown/Home/End keys
  8420. static float ImGui::NavUpdatePageUpPageDown()
  8421. {
  8422. ImGuiContext& g = *GImGui;
  8423. if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
  8424. return 0.0f;
  8425. if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != 0)
  8426. return 0.0f;
  8427. ImGuiWindow* window = g.NavWindow;
  8428. const bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
  8429. const bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
  8430. const bool home_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
  8431. const bool end_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
  8432. if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
  8433. {
  8434. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
  8435. {
  8436. // Fallback manual-scroll when window has no navigable item
  8437. if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
  8438. SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
  8439. else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
  8440. SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
  8441. else if (home_pressed)
  8442. SetScrollY(window, 0.0f);
  8443. else if (end_pressed)
  8444. SetScrollY(window, window->ScrollMax.y);
  8445. }
  8446. else
  8447. {
  8448. ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
  8449. const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
  8450. float nav_scoring_rect_offset_y = 0.0f;
  8451. if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
  8452. {
  8453. nav_scoring_rect_offset_y = -page_offset_y;
  8454. 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)
  8455. g.NavMoveClipDir = ImGuiDir_Up;
  8456. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  8457. }
  8458. else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
  8459. {
  8460. nav_scoring_rect_offset_y = +page_offset_y;
  8461. 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)
  8462. g.NavMoveClipDir = ImGuiDir_Down;
  8463. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
  8464. }
  8465. else if (home_pressed)
  8466. {
  8467. // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
  8468. // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
  8469. // Preserve current horizontal position if we have any.
  8470. nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
  8471. if (nav_rect_rel.IsInverted())
  8472. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  8473. g.NavMoveDir = ImGuiDir_Down;
  8474. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
  8475. }
  8476. else if (end_pressed)
  8477. {
  8478. nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
  8479. if (nav_rect_rel.IsInverted())
  8480. nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
  8481. g.NavMoveDir = ImGuiDir_Up;
  8482. g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
  8483. }
  8484. return nav_scoring_rect_offset_y;
  8485. }
  8486. }
  8487. return 0.0f;
  8488. }
  8489. static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
  8490. {
  8491. ImGuiContext& g = *GImGui;
  8492. for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
  8493. if (g.WindowsFocusOrder[i] == window)
  8494. return i;
  8495. return -1;
  8496. }
  8497. static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
  8498. {
  8499. ImGuiContext& g = *GImGui;
  8500. for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
  8501. if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
  8502. return g.WindowsFocusOrder[i];
  8503. return NULL;
  8504. }
  8505. static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
  8506. {
  8507. ImGuiContext& g = *GImGui;
  8508. IM_ASSERT(g.NavWindowingTarget);
  8509. if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
  8510. return;
  8511. const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
  8512. ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
  8513. if (!window_target)
  8514. window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
  8515. if (window_target) // Don't reset windowing target if there's a single window in the list
  8516. g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
  8517. g.NavWindowingToggleLayer = false;
  8518. }
  8519. // Windowing management mode
  8520. // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
  8521. // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
  8522. static void ImGui::NavUpdateWindowing()
  8523. {
  8524. ImGuiContext& g = *GImGui;
  8525. ImGuiWindow* apply_focus_window = NULL;
  8526. bool apply_toggle_layer = false;
  8527. ImGuiWindow* modal_window = GetTopMostPopupModal();
  8528. if (modal_window != NULL)
  8529. {
  8530. g.NavWindowingTarget = NULL;
  8531. return;
  8532. }
  8533. // Fade out
  8534. if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
  8535. {
  8536. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
  8537. if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
  8538. g.NavWindowingTargetAnim = NULL;
  8539. }
  8540. // Start CTRL-TAB or Square+L/R window selection
  8541. bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
  8542. bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
  8543. if (start_windowing_with_gamepad || start_windowing_with_keyboard)
  8544. if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
  8545. {
  8546. g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindowDockStop;
  8547. g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
  8548. g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
  8549. g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
  8550. }
  8551. // Gamepad update
  8552. g.NavWindowingTimer += g.IO.DeltaTime;
  8553. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
  8554. {
  8555. // 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
  8556. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
  8557. // Select window to focus
  8558. const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
  8559. if (focus_change_dir != 0)
  8560. {
  8561. NavUpdateWindowingHighlightWindow(focus_change_dir);
  8562. g.NavWindowingHighlightAlpha = 1.0f;
  8563. }
  8564. // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
  8565. if (!IsNavInputDown(ImGuiNavInput_Menu))
  8566. {
  8567. g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
  8568. if (g.NavWindowingToggleLayer && g.NavWindow)
  8569. apply_toggle_layer = true;
  8570. else if (!g.NavWindowingToggleLayer)
  8571. apply_focus_window = g.NavWindowingTarget;
  8572. g.NavWindowingTarget = NULL;
  8573. }
  8574. }
  8575. // Keyboard: Focus
  8576. if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
  8577. {
  8578. // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
  8579. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
  8580. if (IsKeyPressedMap(ImGuiKey_Tab, true))
  8581. NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
  8582. if (!g.IO.KeyCtrl)
  8583. apply_focus_window = g.NavWindowingTarget;
  8584. }
  8585. // Keyboard: Press and Release ALT to toggle menu layer
  8586. // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
  8587. if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
  8588. g.NavWindowingToggleLayer = true;
  8589. if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
  8590. if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
  8591. apply_toggle_layer = true;
  8592. // Move window
  8593. if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
  8594. {
  8595. ImVec2 move_delta;
  8596. if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
  8597. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  8598. if (g.NavInputSource == ImGuiInputSource_NavGamepad)
  8599. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
  8600. if (move_delta.x != 0.0f || move_delta.y != 0.0f)
  8601. {
  8602. const float NAV_MOVE_SPEED = 800.0f;
  8603. const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
  8604. SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always);
  8605. g.NavDisableMouseHover = true;
  8606. MarkIniSettingsDirty(g.NavWindowingTarget);
  8607. }
  8608. }
  8609. // Apply final focus
  8610. if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindowDockStop))
  8611. {
  8612. ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
  8613. ClearActiveID();
  8614. g.NavDisableHighlight = false;
  8615. g.NavDisableMouseHover = true;
  8616. apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
  8617. ClosePopupsOverWindow(apply_focus_window, false);
  8618. FocusWindow(apply_focus_window);
  8619. if (apply_focus_window->NavLastIds[0] == 0)
  8620. NavInitWindow(apply_focus_window, false);
  8621. // If the window only has a menu layer, select it directly
  8622. if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
  8623. g.NavLayer = ImGuiNavLayer_Menu;
  8624. // Request OS level focus
  8625. if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
  8626. g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
  8627. }
  8628. if (apply_focus_window)
  8629. g.NavWindowingTarget = NULL;
  8630. // Apply menu/layer toggle
  8631. if (apply_toggle_layer && g.NavWindow)
  8632. {
  8633. // Move to parent menu if necessary
  8634. ImGuiWindow* new_nav_window = g.NavWindow;
  8635. while (new_nav_window->ParentWindow
  8636. && (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
  8637. && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
  8638. && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  8639. new_nav_window = new_nav_window->ParentWindow;
  8640. if (new_nav_window != g.NavWindow)
  8641. {
  8642. ImGuiWindow* old_nav_window = g.NavWindow;
  8643. FocusWindow(new_nav_window);
  8644. new_nav_window->NavLastChildNavWindow = old_nav_window;
  8645. }
  8646. g.NavDisableHighlight = false;
  8647. g.NavDisableMouseHover = true;
  8648. // When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID. It however persist on docking tab tabs.
  8649. const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
  8650. const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
  8651. if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
  8652. g.NavWindow->NavLastIds[ImGuiNavLayer_Menu] = 0;
  8653. NavRestoreLayer(new_nav_layer);
  8654. }
  8655. }
  8656. // Window has already passed the IsWindowNavFocusable()
  8657. static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
  8658. {
  8659. if (window->Flags & ImGuiWindowFlags_Popup)
  8660. return "(Popup)";
  8661. if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
  8662. return "(Main menu bar)";
  8663. if (window->DockNodeAsHost)
  8664. return "(Dock node)";
  8665. return "(Untitled)";
  8666. }
  8667. // Overlay displayed when using CTRL+TAB. Called by EndFrame().
  8668. void ImGui::NavUpdateWindowingOverlay()
  8669. {
  8670. ImGuiContext& g = *GImGui;
  8671. IM_ASSERT(g.NavWindowingTarget != NULL);
  8672. if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
  8673. return;
  8674. if (g.NavWindowingList == NULL)
  8675. g.NavWindowingList = FindWindowByName("###NavWindowingList");
  8676. ImGuiViewportP* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ (ImGuiViewportP*)GetMainViewport();
  8677. SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
  8678. SetNextWindowPos(viewport->Pos + viewport->Size * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
  8679. PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
  8680. Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
  8681. for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
  8682. {
  8683. ImGuiWindow* window = g.WindowsFocusOrder[n];
  8684. if (!IsWindowNavFocusable(window))
  8685. continue;
  8686. const char* label = window->Name;
  8687. if (label == FindRenderedTextEnd(label))
  8688. label = GetFallbackWindowNameForWindowingList(window);
  8689. Selectable(label, g.NavWindowingTarget == window);
  8690. }
  8691. End();
  8692. PopStyleVar();
  8693. }
  8694. //-----------------------------------------------------------------------------
  8695. // [SECTION] DRAG AND DROP
  8696. //-----------------------------------------------------------------------------
  8697. void ImGui::ClearDragDrop()
  8698. {
  8699. ImGuiContext& g = *GImGui;
  8700. g.DragDropActive = false;
  8701. g.DragDropPayload.Clear();
  8702. g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
  8703. g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
  8704. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  8705. g.DragDropAcceptFrameCount = -1;
  8706. g.DragDropPayloadBufHeap.clear();
  8707. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  8708. }
  8709. // Call when current ID is active.
  8710. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
  8711. bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
  8712. {
  8713. ImGuiContext& g = *GImGui;
  8714. ImGuiWindow* window = g.CurrentWindow;
  8715. bool source_drag_active = false;
  8716. ImGuiID source_id = 0;
  8717. ImGuiID source_parent_id = 0;
  8718. ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
  8719. if (!(flags & ImGuiDragDropFlags_SourceExtern))
  8720. {
  8721. source_id = window->DC.LastItemId;
  8722. if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
  8723. return false;
  8724. if (g.IO.MouseDown[mouse_button] == false)
  8725. return false;
  8726. if (source_id == 0)
  8727. {
  8728. // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
  8729. // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
  8730. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
  8731. {
  8732. IM_ASSERT(0);
  8733. return false;
  8734. }
  8735. // Early out
  8736. if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
  8737. return false;
  8738. // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
  8739. // We build a throwaway ID based on current ID stack + relative AABB of items in window.
  8740. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
  8741. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
  8742. source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
  8743. bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
  8744. if (is_hovered && g.IO.MouseClicked[mouse_button])
  8745. {
  8746. SetActiveID(source_id, window);
  8747. FocusWindow(window);
  8748. }
  8749. if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
  8750. g.ActiveIdAllowOverlap = is_hovered;
  8751. }
  8752. else
  8753. {
  8754. g.ActiveIdAllowOverlap = false;
  8755. }
  8756. if (g.ActiveId != source_id)
  8757. return false;
  8758. source_parent_id = window->IDStack.back();
  8759. source_drag_active = IsMouseDragging(mouse_button);
  8760. // Disable navigation and key inputs while dragging
  8761. g.ActiveIdUsingNavDirMask = ~(ImU32)0;
  8762. g.ActiveIdUsingNavInputMask = ~(ImU32)0;
  8763. g.ActiveIdUsingKeyInputMask = ~(ImU64)0;
  8764. }
  8765. else
  8766. {
  8767. window = NULL;
  8768. source_id = ImHashStr("#SourceExtern");
  8769. source_drag_active = true;
  8770. }
  8771. if (source_drag_active)
  8772. {
  8773. if (!g.DragDropActive)
  8774. {
  8775. IM_ASSERT(source_id != 0);
  8776. ClearDragDrop();
  8777. ImGuiPayload& payload = g.DragDropPayload;
  8778. payload.SourceId = source_id;
  8779. payload.SourceParentId = source_parent_id;
  8780. g.DragDropActive = true;
  8781. g.DragDropSourceFlags = flags;
  8782. g.DragDropMouseButton = mouse_button;
  8783. }
  8784. g.DragDropSourceFrameCount = g.FrameCount;
  8785. g.DragDropWithinSourceOrTarget = true;
  8786. if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  8787. {
  8788. // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
  8789. // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
  8790. BeginTooltip();
  8791. if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
  8792. {
  8793. ImGuiWindow* tooltip_window = g.CurrentWindow;
  8794. tooltip_window->SkipItems = true;
  8795. tooltip_window->HiddenFramesCanSkipItems = 1;
  8796. }
  8797. }
  8798. if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
  8799. window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
  8800. return true;
  8801. }
  8802. return false;
  8803. }
  8804. void ImGui::EndDragDropSource()
  8805. {
  8806. ImGuiContext& g = *GImGui;
  8807. IM_ASSERT(g.DragDropActive);
  8808. IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?");
  8809. if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  8810. EndTooltip();
  8811. // Discard the drag if have not called SetDragDropPayload()
  8812. if (g.DragDropPayload.DataFrameCount == -1)
  8813. ClearDragDrop();
  8814. g.DragDropWithinSourceOrTarget = false;
  8815. }
  8816. // Use 'cond' to choose to submit payload on drag start or every frame
  8817. bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
  8818. {
  8819. ImGuiContext& g = *GImGui;
  8820. ImGuiPayload& payload = g.DragDropPayload;
  8821. if (cond == 0)
  8822. cond = ImGuiCond_Always;
  8823. IM_ASSERT(type != NULL);
  8824. IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
  8825. IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
  8826. IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
  8827. IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
  8828. if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
  8829. {
  8830. // Copy payload
  8831. ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
  8832. g.DragDropPayloadBufHeap.resize(0);
  8833. if (data_size > sizeof(g.DragDropPayloadBufLocal))
  8834. {
  8835. // Store in heap
  8836. g.DragDropPayloadBufHeap.resize((int)data_size);
  8837. payload.Data = g.DragDropPayloadBufHeap.Data;
  8838. memcpy(payload.Data, data, data_size);
  8839. }
  8840. else if (data_size > 0)
  8841. {
  8842. // Store locally
  8843. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  8844. payload.Data = g.DragDropPayloadBufLocal;
  8845. memcpy(payload.Data, data, data_size);
  8846. }
  8847. else
  8848. {
  8849. payload.Data = NULL;
  8850. }
  8851. payload.DataSize = (int)data_size;
  8852. }
  8853. payload.DataFrameCount = g.FrameCount;
  8854. return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
  8855. }
  8856. bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
  8857. {
  8858. ImGuiContext& g = *GImGui;
  8859. if (!g.DragDropActive)
  8860. return false;
  8861. ImGuiWindow* window = g.CurrentWindow;
  8862. if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->RootWindow)
  8863. return false;
  8864. IM_ASSERT(id != 0);
  8865. if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
  8866. return false;
  8867. if (window->SkipItems)
  8868. return false;
  8869. IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
  8870. g.DragDropTargetRect = bb;
  8871. g.DragDropTargetId = id;
  8872. g.DragDropWithinSourceOrTarget = true;
  8873. return true;
  8874. }
  8875. // We don't use BeginDragDropTargetCustom() and duplicate its code because:
  8876. // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
  8877. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
  8878. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
  8879. bool ImGui::BeginDragDropTarget()
  8880. {
  8881. ImGuiContext& g = *GImGui;
  8882. if (!g.DragDropActive)
  8883. return false;
  8884. ImGuiWindow* window = g.CurrentWindow;
  8885. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  8886. return false;
  8887. if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->RootWindow)
  8888. return false;
  8889. const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
  8890. ImGuiID id = window->DC.LastItemId;
  8891. if (id == 0)
  8892. id = window->GetIDFromRectangle(display_rect);
  8893. if (g.DragDropPayload.SourceId == id)
  8894. return false;
  8895. IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
  8896. g.DragDropTargetRect = display_rect;
  8897. g.DragDropTargetId = id;
  8898. g.DragDropWithinSourceOrTarget = true;
  8899. return true;
  8900. }
  8901. bool ImGui::IsDragDropPayloadBeingAccepted()
  8902. {
  8903. ImGuiContext& g = *GImGui;
  8904. return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
  8905. }
  8906. const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
  8907. {
  8908. ImGuiContext& g = *GImGui;
  8909. ImGuiWindow* window = g.CurrentWindow;
  8910. ImGuiPayload& payload = g.DragDropPayload;
  8911. IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
  8912. IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
  8913. if (type != NULL && !payload.IsDataType(type))
  8914. return NULL;
  8915. // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
  8916. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
  8917. const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
  8918. ImRect r = g.DragDropTargetRect;
  8919. float r_surface = r.GetWidth() * r.GetHeight();
  8920. if (r_surface < g.DragDropAcceptIdCurrRectSurface)
  8921. {
  8922. g.DragDropAcceptFlags = flags;
  8923. g.DragDropAcceptIdCurr = g.DragDropTargetId;
  8924. g.DragDropAcceptIdCurrRectSurface = r_surface;
  8925. }
  8926. // Render default drop visuals
  8927. payload.Preview = was_accepted_previously;
  8928. flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
  8929. if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
  8930. {
  8931. // FIXME-DRAG: Settle on a proper default visuals for drop target.
  8932. r.Expand(3.5f);
  8933. bool push_clip_rect = !window->ClipRect.Contains(r);
  8934. if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
  8935. window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
  8936. if (push_clip_rect) window->DrawList->PopClipRect();
  8937. }
  8938. g.DragDropAcceptFrameCount = g.FrameCount;
  8939. 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()
  8940. if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
  8941. return NULL;
  8942. return &payload;
  8943. }
  8944. const ImGuiPayload* ImGui::GetDragDropPayload()
  8945. {
  8946. ImGuiContext& g = *GImGui;
  8947. return g.DragDropActive ? &g.DragDropPayload : NULL;
  8948. }
  8949. // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
  8950. void ImGui::EndDragDropTarget()
  8951. {
  8952. ImGuiContext& g = *GImGui;
  8953. IM_ASSERT(g.DragDropActive);
  8954. IM_ASSERT(g.DragDropWithinSourceOrTarget);
  8955. g.DragDropWithinSourceOrTarget = false;
  8956. }
  8957. //-----------------------------------------------------------------------------
  8958. // [SECTION] LOGGING/CAPTURING
  8959. //-----------------------------------------------------------------------------
  8960. // All text output from the interface can be captured into tty/file/clipboard.
  8961. // By default, tree nodes are automatically opened during logging.
  8962. //-----------------------------------------------------------------------------
  8963. // Pass text data straight to log (without being displayed)
  8964. void ImGui::LogText(const char* fmt, ...)
  8965. {
  8966. ImGuiContext& g = *GImGui;
  8967. if (!g.LogEnabled)
  8968. return;
  8969. va_list args;
  8970. va_start(args, fmt);
  8971. if (g.LogFile)
  8972. {
  8973. g.LogBuffer.Buf.resize(0);
  8974. g.LogBuffer.appendfv(fmt, args);
  8975. ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
  8976. }
  8977. else
  8978. {
  8979. g.LogBuffer.appendfv(fmt, args);
  8980. }
  8981. va_end(args);
  8982. }
  8983. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  8984. // We split text into individual lines to add current tree level padding
  8985. void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
  8986. {
  8987. ImGuiContext& g = *GImGui;
  8988. ImGuiWindow* window = g.CurrentWindow;
  8989. if (!text_end)
  8990. text_end = FindRenderedTextEnd(text, text_end);
  8991. const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1);
  8992. if (ref_pos)
  8993. g.LogLinePosY = ref_pos->y;
  8994. if (log_new_line)
  8995. g.LogLineFirstItem = true;
  8996. const char* text_remaining = text;
  8997. if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
  8998. g.LogDepthRef = window->DC.TreeDepth;
  8999. const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
  9000. for (;;)
  9001. {
  9002. // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
  9003. // We don't add a trailing \n to allow a subsequent item on the same line to be captured.
  9004. const char* line_start = text_remaining;
  9005. const char* line_end = ImStreolRange(line_start, text_end);
  9006. const bool is_first_line = (line_start == text);
  9007. const bool is_last_line = (line_end == text_end);
  9008. if (!is_last_line || (line_start != line_end))
  9009. {
  9010. const int char_count = (int)(line_end - line_start);
  9011. if (log_new_line || !is_first_line)
  9012. LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start);
  9013. else if (g.LogLineFirstItem)
  9014. LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start);
  9015. else
  9016. LogText(" %.*s", char_count, line_start);
  9017. g.LogLineFirstItem = false;
  9018. }
  9019. else if (log_new_line)
  9020. {
  9021. // An empty "" string at a different Y position should output a carriage return.
  9022. LogText(IM_NEWLINE);
  9023. break;
  9024. }
  9025. if (is_last_line)
  9026. break;
  9027. text_remaining = line_end + 1;
  9028. }
  9029. }
  9030. // Start logging/capturing text output
  9031. void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
  9032. {
  9033. ImGuiContext& g = *GImGui;
  9034. ImGuiWindow* window = g.CurrentWindow;
  9035. IM_ASSERT(g.LogEnabled == false);
  9036. IM_ASSERT(g.LogFile == NULL);
  9037. IM_ASSERT(g.LogBuffer.empty());
  9038. g.LogEnabled = true;
  9039. g.LogType = type;
  9040. g.LogDepthRef = window->DC.TreeDepth;
  9041. g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
  9042. g.LogLinePosY = FLT_MAX;
  9043. g.LogLineFirstItem = true;
  9044. }
  9045. void ImGui::LogToTTY(int auto_open_depth)
  9046. {
  9047. ImGuiContext& g = *GImGui;
  9048. if (g.LogEnabled)
  9049. return;
  9050. IM_UNUSED(auto_open_depth);
  9051. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9052. LogBegin(ImGuiLogType_TTY, auto_open_depth);
  9053. g.LogFile = stdout;
  9054. #endif
  9055. }
  9056. // Start logging/capturing text output to given file
  9057. void ImGui::LogToFile(int auto_open_depth, const char* filename)
  9058. {
  9059. ImGuiContext& g = *GImGui;
  9060. if (g.LogEnabled)
  9061. return;
  9062. // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
  9063. // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
  9064. // By opening the file in binary mode "ab" we have consistent output everywhere.
  9065. if (!filename)
  9066. filename = g.IO.LogFilename;
  9067. if (!filename || !filename[0])
  9068. return;
  9069. ImFileHandle f = ImFileOpen(filename, "ab");
  9070. if (!f)
  9071. {
  9072. IM_ASSERT(0);
  9073. return;
  9074. }
  9075. LogBegin(ImGuiLogType_File, auto_open_depth);
  9076. g.LogFile = f;
  9077. }
  9078. // Start logging/capturing text output to clipboard
  9079. void ImGui::LogToClipboard(int auto_open_depth)
  9080. {
  9081. ImGuiContext& g = *GImGui;
  9082. if (g.LogEnabled)
  9083. return;
  9084. LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
  9085. }
  9086. void ImGui::LogToBuffer(int auto_open_depth)
  9087. {
  9088. ImGuiContext& g = *GImGui;
  9089. if (g.LogEnabled)
  9090. return;
  9091. LogBegin(ImGuiLogType_Buffer, auto_open_depth);
  9092. }
  9093. void ImGui::LogFinish()
  9094. {
  9095. ImGuiContext& g = *GImGui;
  9096. if (!g.LogEnabled)
  9097. return;
  9098. LogText(IM_NEWLINE);
  9099. switch (g.LogType)
  9100. {
  9101. case ImGuiLogType_TTY:
  9102. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9103. fflush(g.LogFile);
  9104. #endif
  9105. break;
  9106. case ImGuiLogType_File:
  9107. ImFileClose(g.LogFile);
  9108. break;
  9109. case ImGuiLogType_Buffer:
  9110. break;
  9111. case ImGuiLogType_Clipboard:
  9112. if (!g.LogBuffer.empty())
  9113. SetClipboardText(g.LogBuffer.begin());
  9114. break;
  9115. case ImGuiLogType_None:
  9116. IM_ASSERT(0);
  9117. break;
  9118. }
  9119. g.LogEnabled = false;
  9120. g.LogType = ImGuiLogType_None;
  9121. g.LogFile = NULL;
  9122. g.LogBuffer.clear();
  9123. }
  9124. // Helper to display logging buttons
  9125. // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
  9126. void ImGui::LogButtons()
  9127. {
  9128. ImGuiContext& g = *GImGui;
  9129. PushID("LogButtons");
  9130. #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
  9131. const bool log_to_tty = Button("Log To TTY"); SameLine();
  9132. #else
  9133. const bool log_to_tty = false;
  9134. #endif
  9135. const bool log_to_file = Button("Log To File"); SameLine();
  9136. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  9137. PushAllowKeyboardFocus(false);
  9138. SetNextItemWidth(80.0f);
  9139. SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
  9140. PopAllowKeyboardFocus();
  9141. PopID();
  9142. // Start logging at the end of the function so that the buttons don't appear in the log
  9143. if (log_to_tty)
  9144. LogToTTY();
  9145. if (log_to_file)
  9146. LogToFile();
  9147. if (log_to_clipboard)
  9148. LogToClipboard();
  9149. }
  9150. //-----------------------------------------------------------------------------
  9151. // [SECTION] SETTINGS
  9152. //-----------------------------------------------------------------------------
  9153. // Called by NewFrame()
  9154. void ImGui::UpdateSettings()
  9155. {
  9156. // Load settings on first frame (if not explicitly loaded manually before)
  9157. ImGuiContext& g = *GImGui;
  9158. if (!g.SettingsLoaded)
  9159. {
  9160. IM_ASSERT(g.SettingsWindows.empty());
  9161. if (g.IO.IniFilename)
  9162. LoadIniSettingsFromDisk(g.IO.IniFilename);
  9163. g.SettingsLoaded = true;
  9164. }
  9165. // Save settings (with a delay after the last modification, so we don't spam disk too much)
  9166. if (g.SettingsDirtyTimer > 0.0f)
  9167. {
  9168. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  9169. if (g.SettingsDirtyTimer <= 0.0f)
  9170. {
  9171. if (g.IO.IniFilename != NULL)
  9172. SaveIniSettingsToDisk(g.IO.IniFilename);
  9173. else
  9174. g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
  9175. g.SettingsDirtyTimer = 0.0f;
  9176. }
  9177. }
  9178. }
  9179. void ImGui::MarkIniSettingsDirty()
  9180. {
  9181. ImGuiContext& g = *GImGui;
  9182. if (g.SettingsDirtyTimer <= 0.0f)
  9183. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  9184. }
  9185. void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
  9186. {
  9187. ImGuiContext& g = *GImGui;
  9188. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  9189. if (g.SettingsDirtyTimer <= 0.0f)
  9190. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  9191. }
  9192. ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
  9193. {
  9194. ImGuiContext& g = *GImGui;
  9195. #if !IMGUI_DEBUG_INI_SETTINGS
  9196. // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  9197. // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
  9198. if (const char* p = strstr(name, "###"))
  9199. name = p;
  9200. #endif
  9201. const size_t name_len = strlen(name);
  9202. // Allocate chunk
  9203. const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
  9204. ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
  9205. IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
  9206. settings->ID = ImHashStr(name, name_len);
  9207. memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
  9208. return settings;
  9209. }
  9210. ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
  9211. {
  9212. ImGuiContext& g = *GImGui;
  9213. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  9214. if (settings->ID == id)
  9215. return settings;
  9216. return NULL;
  9217. }
  9218. ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
  9219. {
  9220. if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
  9221. return settings;
  9222. return CreateNewWindowSettings(name);
  9223. }
  9224. void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
  9225. {
  9226. size_t file_data_size = 0;
  9227. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
  9228. if (!file_data)
  9229. return;
  9230. LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
  9231. IM_FREE(file_data);
  9232. }
  9233. ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
  9234. {
  9235. ImGuiContext& g = *GImGui;
  9236. const ImGuiID type_hash = ImHashStr(type_name);
  9237. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  9238. if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
  9239. return &g.SettingsHandlers[handler_n];
  9240. return NULL;
  9241. }
  9242. // Zero-tolerance, no error reporting, cheap .ini parsing
  9243. void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
  9244. {
  9245. ImGuiContext& g = *GImGui;
  9246. IM_ASSERT(g.Initialized);
  9247. IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
  9248. // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
  9249. // 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..
  9250. if (ini_size == 0)
  9251. ini_size = strlen(ini_data);
  9252. char* buf = (char*)IM_ALLOC(ini_size + 1);
  9253. char* buf_end = buf + ini_size;
  9254. memcpy(buf, ini_data, ini_size);
  9255. buf[ini_size] = 0;
  9256. void* entry_data = NULL;
  9257. ImGuiSettingsHandler* entry_handler = NULL;
  9258. char* line_end = NULL;
  9259. for (char* line = buf; line < buf_end; line = line_end + 1)
  9260. {
  9261. // Skip new lines markers, then find end of the line
  9262. while (*line == '\n' || *line == '\r')
  9263. line++;
  9264. line_end = line;
  9265. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  9266. line_end++;
  9267. line_end[0] = 0;
  9268. if (line[0] == ';')
  9269. continue;
  9270. if (line[0] == '[' && line_end > line && line_end[-1] == ']')
  9271. {
  9272. // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
  9273. line_end[-1] = 0;
  9274. const char* name_end = line_end - 1;
  9275. const char* type_start = line + 1;
  9276. char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
  9277. const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
  9278. if (!type_end || !name_start)
  9279. continue;
  9280. *type_end = 0; // Overwrite first ']'
  9281. name_start++; // Skip second '['
  9282. entry_handler = FindSettingsHandler(type_start);
  9283. entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
  9284. }
  9285. else if (entry_handler != NULL && entry_data != NULL)
  9286. {
  9287. // Let type handler parse the line
  9288. entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
  9289. }
  9290. }
  9291. IM_FREE(buf);
  9292. g.SettingsLoaded = true;
  9293. DockContextOnLoadSettings(&g);
  9294. }
  9295. void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
  9296. {
  9297. ImGuiContext& g = *GImGui;
  9298. g.SettingsDirtyTimer = 0.0f;
  9299. if (!ini_filename)
  9300. return;
  9301. size_t ini_data_size = 0;
  9302. const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
  9303. ImFileHandle f = ImFileOpen(ini_filename, "wt");
  9304. if (!f)
  9305. return;
  9306. ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
  9307. ImFileClose(f);
  9308. }
  9309. // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
  9310. const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
  9311. {
  9312. ImGuiContext& g = *GImGui;
  9313. g.SettingsDirtyTimer = 0.0f;
  9314. g.SettingsIniData.Buf.resize(0);
  9315. g.SettingsIniData.Buf.push_back(0);
  9316. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  9317. {
  9318. ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
  9319. handler->WriteAllFn(&g, handler, &g.SettingsIniData);
  9320. }
  9321. if (out_size)
  9322. *out_size = (size_t)g.SettingsIniData.size();
  9323. return g.SettingsIniData.c_str();
  9324. }
  9325. static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  9326. {
  9327. ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name));
  9328. if (!settings)
  9329. settings = ImGui::CreateNewWindowSettings(name);
  9330. return (void*)settings;
  9331. }
  9332. static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  9333. {
  9334. ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
  9335. int x, y;
  9336. int i;
  9337. ImU32 u1;
  9338. if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
  9339. else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
  9340. else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
  9341. else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2) { settings->ViewportPos = ImVec2ih((short)x, (short)y); }
  9342. else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
  9343. else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
  9344. else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
  9345. else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
  9346. }
  9347. static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  9348. {
  9349. // Gather data from windows that were active during this session
  9350. // (if a window wasn't opened in this session we preserve its settings)
  9351. ImGuiContext& g = *ctx;
  9352. for (int i = 0; i != g.Windows.Size; i++)
  9353. {
  9354. ImGuiWindow* window = g.Windows[i];
  9355. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  9356. continue;
  9357. ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
  9358. if (!settings)
  9359. {
  9360. settings = ImGui::CreateNewWindowSettings(window->Name);
  9361. window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
  9362. }
  9363. IM_ASSERT(settings->ID == window->ID);
  9364. settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
  9365. settings->Size = ImVec2ih(window->SizeFull);
  9366. settings->ViewportId = window->ViewportId;
  9367. settings->ViewportPos = ImVec2ih(window->ViewportPos);
  9368. IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
  9369. settings->DockId = window->DockId;
  9370. settings->ClassId = window->WindowClass.ClassId;
  9371. settings->DockOrder = window->DockOrder;
  9372. settings->Collapsed = window->Collapsed;
  9373. }
  9374. // Write to text buffer
  9375. buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
  9376. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  9377. {
  9378. const char* settings_name = settings->GetName();
  9379. buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
  9380. if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
  9381. {
  9382. buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
  9383. buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
  9384. }
  9385. if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
  9386. buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
  9387. if (settings->Size.x != 0 || settings->Size.y != 0)
  9388. buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
  9389. buf->appendf("Collapsed=%d\n", settings->Collapsed);
  9390. if (settings->DockId != 0)
  9391. {
  9392. // Write DockId as 4 digits if possible. Automatic DockId are small numbers, but full explicit DockSpace() are full ImGuiID range.
  9393. if (settings->DockOrder == -1)
  9394. buf->appendf("DockId=0x%08X\n", settings->DockId);
  9395. else
  9396. buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
  9397. if (settings->ClassId != 0)
  9398. buf->appendf("ClassId=0x%08X\n", settings->ClassId);
  9399. }
  9400. buf->append("\n");
  9401. }
  9402. }
  9403. //-----------------------------------------------------------------------------
  9404. // [SECTION] VIEWPORTS, PLATFORM WINDOWS
  9405. //-----------------------------------------------------------------------------
  9406. // - GetMainViewport()
  9407. // - FindViewportByID()
  9408. // - FindViewportByPlatformHandle()
  9409. // - SetCurrentViewport() [Internal]
  9410. // - SetWindowViewport() [Internal]
  9411. // - GetWindowAlwaysWantOwnViewport() [Internal]
  9412. // - UpdateTryMergeWindowIntoHostViewport() [Internal]
  9413. // - UpdateTryMergeWindowIntoHostViewports() [Internal]
  9414. // - TranslateWindowsInViewport() [Internal]
  9415. // - ScaleWindowsInViewport() [Internal]
  9416. // - FindHoveredViewportFromPlatformWindowStack() [Internal]
  9417. // - UpdateViewportsNewFrame() [Internal]
  9418. // - UpdateViewportsEndFrame() [Internal]
  9419. // - AddUpdateViewport() [Internal]
  9420. // - UpdateSelectWindowViewport() [Internal]
  9421. // - PlatformWindowsUpdate()
  9422. // - PlatformWindowsRender()
  9423. // - FindPlatformMonitorForPos() [Internal]
  9424. // - FindPlatformMonitorForRect() [Internal]
  9425. // - UpdateViewportPlatformMonitor() [Internal]
  9426. // - PlatformWindowsDestroyOne() [Internal]
  9427. // - PlatformWindowsDestroy()
  9428. //-----------------------------------------------------------------------------
  9429. ImGuiViewport* ImGui::GetMainViewport()
  9430. {
  9431. ImGuiContext& g = *GImGui;
  9432. return g.Viewports[0];
  9433. }
  9434. ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
  9435. {
  9436. ImGuiContext& g = *GImGui;
  9437. for (int n = 0; n < g.Viewports.Size; n++)
  9438. if (g.Viewports[n]->ID == id)
  9439. return g.Viewports[n];
  9440. return NULL;
  9441. }
  9442. ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
  9443. {
  9444. ImGuiContext& g = *GImGui;
  9445. for (int i = 0; i != g.Viewports.Size; i++)
  9446. if (g.Viewports[i]->PlatformHandle == platform_handle)
  9447. return g.Viewports[i];
  9448. return NULL;
  9449. }
  9450. void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
  9451. {
  9452. ImGuiContext& g = *GImGui;
  9453. (void)current_window;
  9454. if (viewport)
  9455. viewport->LastFrameActive = g.FrameCount;
  9456. if (g.CurrentViewport == viewport)
  9457. return;
  9458. g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
  9459. g.CurrentViewport = viewport;
  9460. //IMGUI_DEBUG_LOG_VIEWPORT("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
  9461. // Notify platform layer of viewport changes
  9462. // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
  9463. if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
  9464. g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
  9465. }
  9466. static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
  9467. {
  9468. window->Viewport = viewport;
  9469. window->ViewportId = viewport->ID;
  9470. window->ViewportOwned = (viewport->Window == window);
  9471. }
  9472. static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
  9473. {
  9474. // 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.
  9475. ImGuiContext& g = *GImGui;
  9476. if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
  9477. if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
  9478. if (!window->DockIsActive)
  9479. if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
  9480. if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
  9481. return true;
  9482. return false;
  9483. }
  9484. static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
  9485. {
  9486. ImGuiContext& g = *GImGui;
  9487. if (!(viewport->Flags & (ImGuiViewportFlags_CanHostOtherWindows | ImGuiViewportFlags_Minimized)) || window->Viewport == viewport)
  9488. return false;
  9489. if (!viewport->GetMainRect().Contains(window->Rect()))
  9490. return false;
  9491. if (GetWindowAlwaysWantOwnViewport(window))
  9492. return false;
  9493. for (int n = 0; n < g.Windows.Size; n++)
  9494. {
  9495. ImGuiWindow* window_behind = g.Windows[n];
  9496. if (window_behind == window)
  9497. break;
  9498. if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
  9499. if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
  9500. return false;
  9501. }
  9502. // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
  9503. ImGuiViewportP* old_viewport = window->Viewport;
  9504. if (window->ViewportOwned)
  9505. for (int n = 0; n < g.Windows.Size; n++)
  9506. if (g.Windows[n]->Viewport == old_viewport)
  9507. SetWindowViewport(g.Windows[n], viewport);
  9508. SetWindowViewport(window, viewport);
  9509. BringWindowToDisplayFront(window);
  9510. return true;
  9511. }
  9512. static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
  9513. {
  9514. ImGuiContext& g = *GImGui;
  9515. return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
  9516. }
  9517. // Translate imgui windows when a Host Viewport has been moved
  9518. // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
  9519. void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
  9520. {
  9521. ImGuiContext& g = *GImGui;
  9522. IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
  9523. // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
  9524. // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
  9525. // 2) If it's not going to fit into the new size, keep it at same absolute position.
  9526. // One problem with this is that most Win32 applications doesn't update their render while dragging,
  9527. // and so the window will appear to teleport when releasing the mouse.
  9528. const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
  9529. ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
  9530. ImVec2 delta_pos = new_pos - old_pos;
  9531. for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
  9532. if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
  9533. TranslateWindow(g.Windows[window_n], delta_pos);
  9534. }
  9535. // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
  9536. void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
  9537. {
  9538. ImGuiContext& g = *GImGui;
  9539. if (viewport->Window)
  9540. {
  9541. ScaleWindow(viewport->Window, scale);
  9542. }
  9543. else
  9544. {
  9545. for (int i = 0; i != g.Windows.Size; i++)
  9546. if (g.Windows[i]->Viewport == viewport)
  9547. ScaleWindow(g.Windows[i], scale);
  9548. }
  9549. }
  9550. // If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
  9551. // A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
  9552. // B) It requires Platform_GetWindowFocus to be implemented by back-end.
  9553. static ImGuiViewportP* FindHoveredViewportFromPlatformWindowStack(const ImVec2 mouse_platform_pos)
  9554. {
  9555. ImGuiContext& g = *GImGui;
  9556. ImGuiViewportP* best_candidate = NULL;
  9557. for (int n = 0; n < g.Viewports.Size; n++)
  9558. {
  9559. ImGuiViewportP* viewport = g.Viewports[n];
  9560. if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
  9561. if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
  9562. best_candidate = viewport;
  9563. }
  9564. return best_candidate;
  9565. }
  9566. // Update viewports and monitor infos
  9567. // Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
  9568. static void ImGui::UpdateViewportsNewFrame()
  9569. {
  9570. ImGuiContext& g = *GImGui;
  9571. IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
  9572. // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
  9573. const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
  9574. if (viewports_enabled)
  9575. {
  9576. for (int n = 0; n < g.Viewports.Size; n++)
  9577. {
  9578. ImGuiViewportP* viewport = g.Viewports[n];
  9579. const bool platform_funcs_available = viewport->PlatformWindowCreated;
  9580. if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
  9581. {
  9582. bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
  9583. if (minimized)
  9584. viewport->Flags |= ImGuiViewportFlags_Minimized;
  9585. else
  9586. viewport->Flags &= ~ImGuiViewportFlags_Minimized;
  9587. }
  9588. }
  9589. }
  9590. // Create/update main viewport with current platform position.
  9591. // FIXME-VIEWPORT: Size is driven by back-end/user code for backward-compatibility but we should aim to make this more consistent.
  9592. ImGuiViewportP* main_viewport = g.Viewports[0];
  9593. IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
  9594. IM_ASSERT(main_viewport->Window == NULL);
  9595. ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
  9596. ImVec2 main_viewport_size = g.IO.DisplaySize;
  9597. if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized))
  9598. {
  9599. 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)
  9600. main_viewport_size = main_viewport->Size;
  9601. }
  9602. AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_CanHostOtherWindows);
  9603. g.CurrentDpiScale = 0.0f;
  9604. g.CurrentViewport = NULL;
  9605. g.MouseViewport = NULL;
  9606. for (int n = 0; n < g.Viewports.Size; n++)
  9607. {
  9608. ImGuiViewportP* viewport = g.Viewports[n];
  9609. viewport->Idx = n;
  9610. // Erase unused viewports
  9611. if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
  9612. {
  9613. // Clear references to this viewport in windows (window->ViewportId becomes the master data)
  9614. for (int window_n = 0; window_n < g.Windows.Size; window_n++)
  9615. if (g.Windows[window_n]->Viewport == viewport)
  9616. {
  9617. g.Windows[window_n]->Viewport = NULL;
  9618. g.Windows[window_n]->ViewportOwned = false;
  9619. }
  9620. if (viewport == g.MouseLastHoveredViewport)
  9621. g.MouseLastHoveredViewport = NULL;
  9622. g.Viewports.erase(g.Viewports.Data + n);
  9623. // Destroy
  9624. IMGUI_DEBUG_LOG_VIEWPORT("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
  9625. PlatformWindowsDestroyOne(viewport); // In most circumstances the platform window will already be destroyed here.
  9626. IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
  9627. IM_DELETE(viewport);
  9628. n--;
  9629. continue;
  9630. }
  9631. const bool platform_funcs_available = viewport->PlatformWindowCreated;
  9632. if (viewports_enabled)
  9633. {
  9634. // Update Position and Size (from Platform Window to ImGui) if requested.
  9635. // We do it early in the frame instead of waiting for PlatformWindowsUpdate() to avoid a frame of lag when moving/resizing using OS facilities.
  9636. if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
  9637. {
  9638. if (viewport->PlatformRequestMove)
  9639. viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
  9640. if (viewport->PlatformRequestResize)
  9641. viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
  9642. }
  9643. }
  9644. // Update/copy monitor info
  9645. UpdateViewportPlatformMonitor(viewport);
  9646. // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again.
  9647. viewport->WorkOffsetMin = viewport->CurrWorkOffsetMin;
  9648. viewport->WorkOffsetMax = viewport->CurrWorkOffsetMax;
  9649. viewport->CurrWorkOffsetMin = viewport->CurrWorkOffsetMax = ImVec2(0.0f, 0.0f);
  9650. // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
  9651. viewport->Alpha = 1.0f;
  9652. // Translate imgui windows when a Host Viewport has been moved
  9653. // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
  9654. const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
  9655. if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
  9656. TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
  9657. // Update DPI scale
  9658. float new_dpi_scale;
  9659. if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
  9660. new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
  9661. else if (viewport->PlatformMonitor != -1)
  9662. new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
  9663. else
  9664. new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
  9665. if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
  9666. {
  9667. float scale_factor = new_dpi_scale / viewport->DpiScale;
  9668. if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
  9669. ScaleWindowsInViewport(viewport, scale_factor);
  9670. //if (viewport == GetMainViewport())
  9671. // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
  9672. // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
  9673. // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
  9674. // (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.)
  9675. //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
  9676. // g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
  9677. }
  9678. viewport->DpiScale = new_dpi_scale;
  9679. }
  9680. if (!viewports_enabled)
  9681. {
  9682. g.MouseViewport = main_viewport;
  9683. return;
  9684. }
  9685. // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
  9686. // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
  9687. ImGuiViewportP* viewport_hovered = NULL;
  9688. if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
  9689. {
  9690. viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
  9691. if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
  9692. {
  9693. // Back-end failed at honoring its contract if it returned a viewport with the _NoInputs flag.
  9694. IM_ASSERT(0);
  9695. viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
  9696. }
  9697. }
  9698. else
  9699. {
  9700. // If the back-end doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
  9701. // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
  9702. // 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)
  9703. viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
  9704. }
  9705. if (viewport_hovered != NULL)
  9706. g.MouseLastHoveredViewport = viewport_hovered;
  9707. else if (g.MouseLastHoveredViewport == NULL)
  9708. g.MouseLastHoveredViewport = g.Viewports[0];
  9709. // Update mouse reference viewport
  9710. // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
  9711. if (g.MovingWindow)
  9712. g.MouseViewport = g.MovingWindow->Viewport;
  9713. else
  9714. g.MouseViewport = g.MouseLastHoveredViewport;
  9715. // When dragging something, always refer to the last hovered viewport.
  9716. // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
  9717. // - 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)
  9718. // - 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.
  9719. const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
  9720. if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
  9721. viewport_hovered = g.MouseLastHoveredViewport;
  9722. if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
  9723. if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
  9724. g.MouseViewport = viewport_hovered;
  9725. IM_ASSERT(g.MouseViewport != NULL);
  9726. }
  9727. // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
  9728. static void ImGui::UpdateViewportsEndFrame()
  9729. {
  9730. ImGuiContext& g = *GImGui;
  9731. g.PlatformIO.MainViewport = g.Viewports[0];
  9732. g.PlatformIO.Viewports.resize(0);
  9733. for (int i = 0; i < g.Viewports.Size; i++)
  9734. {
  9735. ImGuiViewportP* viewport = g.Viewports[i];
  9736. viewport->LastPos = viewport->Pos;
  9737. if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
  9738. if (i > 0) // Always include main viewport in the list
  9739. continue;
  9740. if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
  9741. continue;
  9742. if (i > 0)
  9743. IM_ASSERT(viewport->Window != NULL);
  9744. g.PlatformIO.Viewports.push_back(viewport);
  9745. }
  9746. g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because PlatformWindowsUpdate() won't do it and may not even be called
  9747. }
  9748. // FIXME: We should ideally refactor the system to call this every frame (we currently don't)
  9749. ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
  9750. {
  9751. ImGuiContext& g = *GImGui;
  9752. IM_ASSERT(id != 0);
  9753. if (window != NULL)
  9754. {
  9755. if (g.MovingWindow && g.MovingWindow->RootWindow == window)
  9756. flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
  9757. if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
  9758. flags |= ImGuiViewportFlags_NoInputs;
  9759. if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
  9760. flags |= ImGuiViewportFlags_NoFocusOnAppearing;
  9761. }
  9762. ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
  9763. if (viewport)
  9764. {
  9765. if (!viewport->PlatformRequestMove)
  9766. viewport->Pos = pos;
  9767. if (!viewport->PlatformRequestResize)
  9768. viewport->Size = size;
  9769. viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
  9770. }
  9771. else
  9772. {
  9773. // New viewport
  9774. viewport = IM_NEW(ImGuiViewportP)();
  9775. viewport->ID = id;
  9776. viewport->Idx = g.Viewports.Size;
  9777. viewport->Pos = viewport->LastPos = pos;
  9778. viewport->Size = size;
  9779. viewport->Flags = flags;
  9780. UpdateViewportPlatformMonitor(viewport);
  9781. g.Viewports.push_back(viewport);
  9782. IMGUI_DEBUG_LOG_VIEWPORT("Add Viewport %08X (%s)\n", id, window->Name);
  9783. // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
  9784. // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
  9785. g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
  9786. g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
  9787. g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
  9788. g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
  9789. // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
  9790. // This is so we can select an appropriate font size on the first frame of our window lifetime
  9791. if (viewport->PlatformMonitor != -1)
  9792. viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
  9793. }
  9794. viewport->Window = window;
  9795. viewport->LastFrameActive = g.FrameCount;
  9796. IM_ASSERT(window == NULL || viewport->ID == window->ID);
  9797. if (window != NULL)
  9798. window->ViewportOwned = true;
  9799. return viewport;
  9800. }
  9801. // FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
  9802. static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window)
  9803. {
  9804. ImGuiContext& g = *GImGui;
  9805. ImGuiWindowFlags flags = window->Flags;
  9806. window->ViewportAllowPlatformMonitorExtend = -1;
  9807. // Restore main viewport if multi-viewport is not supported by the back-end
  9808. ImGuiViewportP* main_viewport = g.Viewports[0];
  9809. if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
  9810. {
  9811. SetWindowViewport(window, main_viewport);
  9812. return;
  9813. }
  9814. window->ViewportOwned = false;
  9815. // Appearing popups reset their viewport so they can inherit again
  9816. if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
  9817. {
  9818. window->Viewport = NULL;
  9819. window->ViewportId = 0;
  9820. }
  9821. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
  9822. {
  9823. // By default inherit from parent window
  9824. if (window->Viewport == NULL && window->ParentWindow && !window->ParentWindow->IsFallbackWindow)
  9825. window->Viewport = window->ParentWindow->Viewport;
  9826. // 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
  9827. if (window->Viewport == NULL && window->ViewportId != 0)
  9828. {
  9829. window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
  9830. if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
  9831. window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
  9832. }
  9833. }
  9834. bool lock_viewport = false;
  9835. if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
  9836. {
  9837. // Code explicitly request a viewport
  9838. window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
  9839. window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
  9840. lock_viewport = true;
  9841. }
  9842. else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
  9843. {
  9844. // Always inherit viewport from parent window
  9845. window->Viewport = window->ParentWindow->Viewport;
  9846. }
  9847. else if (flags & ImGuiWindowFlags_Tooltip)
  9848. {
  9849. window->Viewport = g.MouseViewport;
  9850. }
  9851. else if (GetWindowAlwaysWantOwnViewport(window))
  9852. {
  9853. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
  9854. }
  9855. else if (g.MovingWindow && g.MovingWindow->RootWindow == window && IsMousePosValid())
  9856. {
  9857. if (window->Viewport != NULL && window->Viewport->Window == window)
  9858. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
  9859. }
  9860. else
  9861. {
  9862. // Merge into host viewport?
  9863. // We cannot test window->ViewportOwned as it set lower in the function.
  9864. bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0);
  9865. if (try_to_merge_into_host_viewport)
  9866. UpdateTryMergeWindowIntoHostViewports(window);
  9867. }
  9868. // Fallback to default viewport
  9869. if (window->Viewport == NULL)
  9870. window->Viewport = main_viewport;
  9871. // Mark window as allowed to protrude outside of its viewport and into the current monitor
  9872. if (!lock_viewport)
  9873. {
  9874. if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  9875. {
  9876. // We need to take account of the possibility that mouse may become invalid.
  9877. // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
  9878. ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
  9879. bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
  9880. bool mouse_valid = IsMousePosValid(&mouse_ref);
  9881. if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
  9882. window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
  9883. else
  9884. window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
  9885. }
  9886. else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow))
  9887. {
  9888. // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
  9889. const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
  9890. if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
  9891. {
  9892. // Steal/transfer ownership
  9893. IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
  9894. window->Viewport->Window = window;
  9895. window->Viewport->ID = window->ID;
  9896. window->Viewport->LastNameHash = 0;
  9897. }
  9898. else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
  9899. {
  9900. // New viewport
  9901. window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
  9902. }
  9903. }
  9904. else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
  9905. {
  9906. // Regular (non-child, non-popup) windows by default are also allowed to protrude
  9907. // Child windows are kept contained within their parent.
  9908. window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
  9909. }
  9910. }
  9911. // Update flags
  9912. window->ViewportOwned = (window == window->Viewport->Window);
  9913. window->ViewportId = window->Viewport->ID;
  9914. // If the OS window has a title bar, hide our imgui title bar
  9915. //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
  9916. // window->Flags |= ImGuiWindowFlags_NoTitleBar;
  9917. }
  9918. // Called by user at the end of the main loop, after EndFrame()
  9919. // This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO API.
  9920. void ImGui::PlatformWindowsUpdate()
  9921. {
  9922. ImGuiContext& g = *GImGui;
  9923. IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before PlatformWindowsUpdate()?");
  9924. IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
  9925. g.FrameCountPlatformEnded = g.FrameCount;
  9926. if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
  9927. return;
  9928. // Create/resize/destroy platform windows to match each active viewport.
  9929. // Skip the main viewport (index 0), which is always fully handled by the application!
  9930. for (int i = 1; i < g.Viewports.Size; i++)
  9931. {
  9932. ImGuiViewportP* viewport = g.Viewports[i];
  9933. // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
  9934. // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy PlatformWindowsDestroyOne to be made each frame)
  9935. bool destroy_platform_window = false;
  9936. destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
  9937. destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
  9938. if (destroy_platform_window)
  9939. {
  9940. PlatformWindowsDestroyOne(viewport);
  9941. continue;
  9942. }
  9943. // New windows that appears directly in a new viewport won't always have a size on their first frame
  9944. if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
  9945. continue;
  9946. // Create window
  9947. bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
  9948. if (is_new_platform_window)
  9949. {
  9950. IMGUI_DEBUG_LOG_VIEWPORT("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
  9951. g.PlatformIO.Platform_CreateWindow(viewport);
  9952. if (g.PlatformIO.Renderer_CreateWindow != NULL)
  9953. g.PlatformIO.Renderer_CreateWindow(viewport);
  9954. viewport->LastNameHash = 0;
  9955. 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?)
  9956. viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
  9957. viewport->PlatformWindowCreated = true;
  9958. }
  9959. // Apply Position and Size (from ImGui to Platform/Renderer back-ends)
  9960. if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
  9961. g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
  9962. if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
  9963. g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
  9964. if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
  9965. g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
  9966. viewport->LastPlatformPos = viewport->Pos;
  9967. viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
  9968. // Update title bar (if it changed)
  9969. if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
  9970. {
  9971. const char* title_begin = window_for_title->Name;
  9972. char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
  9973. const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
  9974. if (viewport->LastNameHash != title_hash)
  9975. {
  9976. char title_end_backup_c = *title_end;
  9977. *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
  9978. g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
  9979. *title_end = title_end_backup_c;
  9980. viewport->LastNameHash = title_hash;
  9981. }
  9982. }
  9983. // Update alpha (if it changed)
  9984. if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
  9985. g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
  9986. viewport->LastAlpha = viewport->Alpha;
  9987. // Optional, general purpose call to allow the back-end to perform general book-keeping even if things haven't changed.
  9988. if (g.PlatformIO.Platform_UpdateWindow)
  9989. g.PlatformIO.Platform_UpdateWindow(viewport);
  9990. if (is_new_platform_window)
  9991. {
  9992. // 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)
  9993. if (g.FrameCount < 3)
  9994. viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
  9995. // Show window
  9996. g.PlatformIO.Platform_ShowWindow(viewport);
  9997. // Even without focus, we assume the window becomes front-most.
  9998. // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
  9999. if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
  10000. viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
  10001. }
  10002. // Clear request flags
  10003. viewport->ClearRequestFlags();
  10004. }
  10005. // Update our implicit z-order knowledge of platform windows, which is used when the back-end cannot provide io.MouseHoveredViewport.
  10006. // When setting Platform_GetWindowFocus, it is expected that the platform back-end can handle calls without crashing if it doesn't have data stored.
  10007. if (g.PlatformIO.Platform_GetWindowFocus != NULL)
  10008. {
  10009. ImGuiViewportP* focused_viewport = NULL;
  10010. for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
  10011. {
  10012. ImGuiViewportP* viewport = g.Viewports[n];
  10013. if (viewport->PlatformWindowCreated)
  10014. if (g.PlatformIO.Platform_GetWindowFocus(viewport))
  10015. focused_viewport = viewport;
  10016. }
  10017. if (focused_viewport && g.PlatformLastFocusedViewport != focused_viewport->ID)
  10018. {
  10019. if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
  10020. focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
  10021. g.PlatformLastFocusedViewport = focused_viewport->ID;
  10022. }
  10023. }
  10024. }
  10025. // This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
  10026. // Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
  10027. // The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
  10028. //
  10029. // ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  10030. // for (int i = 1; i < platform_io.Viewports.Size; i++)
  10031. // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
  10032. // MyRenderFunction(platform_io.Viewports[i], my_args);
  10033. // for (int i = 1; i < platform_io.Viewports.Size; i++)
  10034. // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
  10035. // MySwapBufferFunction(platform_io.Viewports[i], my_args);
  10036. //
  10037. void ImGui::PlatformWindowsRender(void* platform_render_arg, void* renderer_render_arg)
  10038. {
  10039. // Skip the main viewport (index 0), which is always fully handled by the application!
  10040. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  10041. for (int i = 1; i < platform_io.Viewports.Size; i++)
  10042. {
  10043. ImGuiViewport* viewport = platform_io.Viewports[i];
  10044. if (viewport->Flags & ImGuiViewportFlags_Minimized)
  10045. continue;
  10046. if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
  10047. if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
  10048. }
  10049. for (int i = 1; i < platform_io.Viewports.Size; i++)
  10050. {
  10051. ImGuiViewport* viewport = platform_io.Viewports[i];
  10052. if (viewport->Flags & ImGuiViewportFlags_Minimized)
  10053. continue;
  10054. if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
  10055. if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
  10056. }
  10057. }
  10058. static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
  10059. {
  10060. ImGuiContext& g = *GImGui;
  10061. for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
  10062. {
  10063. const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
  10064. if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
  10065. return monitor_n;
  10066. }
  10067. return -1;
  10068. }
  10069. // Search for the monitor with the largest intersection area with the given rectangle
  10070. // We generally try to avoid searching loops but the monitor count should be very small here
  10071. // FIXME-OPT: We could test the last monitor used for that viewport first, and early
  10072. static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
  10073. {
  10074. ImGuiContext& g = *GImGui;
  10075. const int monitor_count = g.PlatformIO.Monitors.Size;
  10076. if (monitor_count <= 1)
  10077. return monitor_count - 1;
  10078. // 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.
  10079. // This is necessary for tooltips which always resize down to zero at first.
  10080. const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
  10081. int best_monitor_n = -1;
  10082. float best_monitor_surface = 0.001f;
  10083. for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
  10084. {
  10085. const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
  10086. const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
  10087. if (monitor_rect.Contains(rect))
  10088. return monitor_n;
  10089. ImRect overlapping_rect = rect;
  10090. overlapping_rect.ClipWithFull(monitor_rect);
  10091. float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
  10092. if (overlapping_surface < best_monitor_surface)
  10093. continue;
  10094. best_monitor_surface = overlapping_surface;
  10095. best_monitor_n = monitor_n;
  10096. }
  10097. return best_monitor_n;
  10098. }
  10099. // Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
  10100. static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
  10101. {
  10102. viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
  10103. }
  10104. void ImGui::PlatformWindowsDestroyOne(ImGuiViewportP* viewport)
  10105. {
  10106. ImGuiContext& g = *GImGui;
  10107. if (viewport->PlatformWindowCreated)
  10108. {
  10109. if (g.PlatformIO.Renderer_DestroyWindow)
  10110. g.PlatformIO.Renderer_DestroyWindow(viewport);
  10111. if (g.PlatformIO.Platform_DestroyWindow)
  10112. g.PlatformIO.Platform_DestroyWindow(viewport);
  10113. IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
  10114. // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
  10115. // The right-er way may be to leave it to the back-end to set this flag all-together, and made the flag public.
  10116. if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
  10117. viewport->PlatformWindowCreated = false;
  10118. }
  10119. else
  10120. {
  10121. IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
  10122. }
  10123. viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
  10124. viewport->ClearRequestFlags();
  10125. }
  10126. void ImGui::PlatformWindowsDestroy()
  10127. {
  10128. // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the back-end
  10129. // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
  10130. // It is convenient for the platform back-end code to store something in the main viewport, in order for e.g. the mouse handling
  10131. // code to operator a consistent manner.
  10132. // It is expected that the back-end can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
  10133. // crashing if it doesn't have data stored.
  10134. ImGuiContext& g = *GImGui;
  10135. for (int i = 0; i < g.Viewports.Size; i++)
  10136. PlatformWindowsDestroyOne(g.Viewports[i]);
  10137. }
  10138. //-----------------------------------------------------------------------------
  10139. // [SECTION] DOCKING
  10140. //-----------------------------------------------------------------------------
  10141. // Docking: Internal Types
  10142. // Docking: Forward Declarations
  10143. // Docking: ImGuiDockContext
  10144. // Docking: ImGuiDockContext Docking/Undocking functions
  10145. // Docking: ImGuiDockNode
  10146. // Docking: ImGuiDockNode Tree manipulation functions
  10147. // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
  10148. // Docking: Builder Functions
  10149. // Docking: Begin/End Support Functions (called from Begin/End)
  10150. // Docking: Settings
  10151. //-----------------------------------------------------------------------------
  10152. //-----------------------------------------------------------------------------
  10153. // Docking: Internal Types
  10154. //-----------------------------------------------------------------------------
  10155. // - ImGuiDockRequestType
  10156. // - ImGuiDockRequest
  10157. // - ImGuiDockPreviewData
  10158. // - ImGuiDockNodeSettings
  10159. // - ImGuiDockContext
  10160. //-----------------------------------------------------------------------------
  10161. static float IMGUI_DOCK_SPLITTER_SIZE = 2.0f;
  10162. enum ImGuiDockRequestType
  10163. {
  10164. ImGuiDockRequestType_None = 0,
  10165. ImGuiDockRequestType_Dock,
  10166. ImGuiDockRequestType_Undock,
  10167. ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
  10168. };
  10169. struct ImGuiDockRequest
  10170. {
  10171. ImGuiDockRequestType Type;
  10172. 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)
  10173. ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
  10174. ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
  10175. ImGuiDir DockSplitDir;
  10176. float DockSplitRatio;
  10177. bool DockSplitOuter;
  10178. ImGuiWindow* UndockTargetWindow;
  10179. ImGuiDockNode* UndockTargetNode;
  10180. ImGuiDockRequest()
  10181. {
  10182. Type = ImGuiDockRequestType_None;
  10183. DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
  10184. DockTargetNode = UndockTargetNode = NULL;
  10185. DockSplitDir = ImGuiDir_None;
  10186. DockSplitRatio = 0.5f;
  10187. DockSplitOuter = false;
  10188. }
  10189. };
  10190. struct ImGuiDockPreviewData
  10191. {
  10192. ImGuiDockNode FutureNode;
  10193. bool IsDropAllowed;
  10194. bool IsCenterAvailable;
  10195. bool IsSidesAvailable; // Hold your breath, grammar freaks..
  10196. bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
  10197. ImGuiDockNode* SplitNode;
  10198. ImGuiDir SplitDir;
  10199. float SplitRatio;
  10200. ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
  10201. ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; }
  10202. };
  10203. // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
  10204. struct ImGuiDockNodeSettings
  10205. {
  10206. ImGuiID ID;
  10207. ImGuiID ParentNodeId;
  10208. ImGuiID ParentWindowId;
  10209. ImGuiID SelectedWindowId;
  10210. signed char SplitAxis;
  10211. char Depth;
  10212. ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
  10213. ImVec2ih Pos;
  10214. ImVec2ih Size;
  10215. ImVec2ih SizeRef;
  10216. ImGuiDockNodeSettings() { ID = ParentNodeId = ParentWindowId = SelectedWindowId = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; }
  10217. };
  10218. struct ImGuiDockContext
  10219. {
  10220. ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes
  10221. ImVector<ImGuiDockRequest> Requests;
  10222. ImVector<ImGuiDockNodeSettings> SettingsNodes;
  10223. bool WantFullRebuild;
  10224. ImGuiDockContext() { WantFullRebuild = false; }
  10225. };
  10226. //-----------------------------------------------------------------------------
  10227. // Docking: Forward Declarations
  10228. //-----------------------------------------------------------------------------
  10229. namespace ImGui
  10230. {
  10231. // ImGuiDockContext
  10232. static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
  10233. static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
  10234. static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
  10235. static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
  10236. static void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true);
  10237. static void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
  10238. static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
  10239. static ImGuiDockNode* DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id);
  10240. static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
  10241. static void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_refs); // Use root_id==0 to clear all
  10242. static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
  10243. static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
  10244. // ImGuiDockNode
  10245. static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
  10246. static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
  10247. static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
  10248. static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
  10249. static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
  10250. static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
  10251. static void DockNodeHideHostWindow(ImGuiDockNode* node);
  10252. static void DockNodeUpdate(ImGuiDockNode* node);
  10253. static void DockNodeUpdateForRootNode(ImGuiDockNode* node);
  10254. static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node);
  10255. static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
  10256. static void DockNodeAddTabBar(ImGuiDockNode* node);
  10257. static void DockNodeRemoveTabBar(ImGuiDockNode* node);
  10258. static ImGuiID DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
  10259. static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
  10260. static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
  10261. static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
  10262. static void DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
  10263. static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
  10264. static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos);
  10265. static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
  10266. static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
  10267. static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
  10268. static int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; }
  10269. static int DockNodeGetTabOrder(ImGuiWindow* window);
  10270. // ImGuiDockNode tree manipulations
  10271. static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
  10272. static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
  10273. static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes = false);
  10274. static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
  10275. static ImGuiDockNode* DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos);
  10276. static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
  10277. // Settings
  10278. static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
  10279. static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
  10280. static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
  10281. static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
  10282. static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
  10283. static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
  10284. }
  10285. //-----------------------------------------------------------------------------
  10286. // Docking: ImGuiDockContext
  10287. //-----------------------------------------------------------------------------
  10288. // The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
  10289. // 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.
  10290. // At boot time only, we run a simple GC to remove nodes that have no references.
  10291. // Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
  10292. // we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
  10293. // This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
  10294. //-----------------------------------------------------------------------------
  10295. // - DockContextInitialize()
  10296. // - DockContextShutdown()
  10297. // - DockContextOnLoadSettings()
  10298. // - DockContextClearNodes()
  10299. // - DockContextRebuildNodes()
  10300. // - DockContextUpdateUndocking()
  10301. // - DockContextUpdateDocking()
  10302. // - DockContextFindNodeByID()
  10303. // - DockContextBindNodeToWindow()
  10304. // - DockContextGenNodeID()
  10305. // - DockContextAddNode()
  10306. // - DockContextRemoveNode()
  10307. // - ImGuiDockContextPruneNodeData
  10308. // - DockContextPruneUnusedSettingsNodes()
  10309. // - DockContextBuildNodesFromSettings()
  10310. // - DockContextBuildAddWindowsToNodes()
  10311. //-----------------------------------------------------------------------------
  10312. void ImGui::DockContextInitialize(ImGuiContext* ctx)
  10313. {
  10314. ImGuiContext& g = *ctx;
  10315. IM_ASSERT(g.DockContext == NULL);
  10316. g.DockContext = IM_NEW(ImGuiDockContext)();
  10317. // Add .ini handle for persistent docking data
  10318. ImGuiSettingsHandler ini_handler;
  10319. ini_handler.TypeName = "Docking";
  10320. ini_handler.TypeHash = ImHashStr("Docking");
  10321. ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
  10322. ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
  10323. ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
  10324. g.SettingsHandlers.push_back(ini_handler);
  10325. }
  10326. void ImGui::DockContextShutdown(ImGuiContext* ctx)
  10327. {
  10328. ImGuiContext& g = *ctx;
  10329. ImGuiDockContext* dc = ctx->DockContext;
  10330. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  10331. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  10332. IM_DELETE(node);
  10333. IM_DELETE(g.DockContext);
  10334. g.DockContext = NULL;
  10335. }
  10336. void ImGui::DockContextOnLoadSettings(ImGuiContext* ctx)
  10337. {
  10338. ImGuiDockContext* dc = ctx->DockContext;
  10339. DockContextPruneUnusedSettingsNodes(ctx);
  10340. DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size);
  10341. }
  10342. void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references)
  10343. {
  10344. IM_UNUSED(ctx);
  10345. IM_ASSERT(ctx == GImGui);
  10346. DockBuilderRemoveNodeDockedWindows(root_id, clear_persistent_docking_references);
  10347. DockBuilderRemoveNodeChildNodes(root_id);
  10348. }
  10349. // This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
  10350. void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
  10351. {
  10352. IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n");
  10353. ImGuiDockContext* dc = ctx->DockContext;
  10354. SaveIniSettingsToMemory();
  10355. ImGuiID root_id = 0; // Rebuild all
  10356. DockContextClearNodes(ctx, root_id, false);
  10357. DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size);
  10358. DockContextBuildAddWindowsToNodes(ctx, root_id);
  10359. }
  10360. // Docking context update function, called by NewFrame()
  10361. void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx)
  10362. {
  10363. ImGuiContext& g = *ctx;
  10364. ImGuiDockContext* dc = ctx->DockContext;
  10365. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  10366. {
  10367. if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
  10368. DockContextClearNodes(ctx, 0, true);
  10369. return;
  10370. }
  10371. // Setting NoSplit at runtime merges all nodes
  10372. if (g.IO.ConfigDockingNoSplit)
  10373. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  10374. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  10375. if (node->IsRootNode() && node->IsSplitNode())
  10376. {
  10377. DockBuilderRemoveNodeChildNodes(node->ID);
  10378. //dc->WantFullRebuild = true;
  10379. }
  10380. // Process full rebuild
  10381. #if 0
  10382. if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
  10383. dc->WantFullRebuild = true;
  10384. #endif
  10385. if (dc->WantFullRebuild)
  10386. {
  10387. DockContextRebuildNodes(ctx);
  10388. dc->WantFullRebuild = false;
  10389. }
  10390. // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
  10391. for (int n = 0; n < dc->Requests.Size; n++)
  10392. {
  10393. ImGuiDockRequest* req = &dc->Requests[n];
  10394. if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
  10395. DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
  10396. else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
  10397. DockContextProcessUndockNode(ctx, req->UndockTargetNode);
  10398. }
  10399. }
  10400. // Docking context update function, called by NewFrame()
  10401. void ImGui::DockContextUpdateDocking(ImGuiContext* ctx)
  10402. {
  10403. ImGuiContext& g = *ctx;
  10404. ImGuiDockContext* dc = ctx->DockContext;
  10405. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  10406. return;
  10407. // Process Docking requests
  10408. for (int n = 0; n < dc->Requests.Size; n++)
  10409. if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
  10410. DockContextProcessDock(ctx, &dc->Requests[n]);
  10411. dc->Requests.resize(0);
  10412. // Create windows for each automatic docking nodes
  10413. // 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)
  10414. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  10415. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  10416. if (node->IsFloatingNode())
  10417. DockNodeUpdate(node);
  10418. }
  10419. static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
  10420. {
  10421. return (ImGuiDockNode*)ctx->DockContext->Nodes.GetVoidPtr(id);
  10422. }
  10423. ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
  10424. {
  10425. // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
  10426. // 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.
  10427. ImGuiID id = 0x0001;
  10428. while (DockContextFindNodeByID(ctx, id) != NULL)
  10429. id++;
  10430. return id;
  10431. }
  10432. static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
  10433. {
  10434. // 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.
  10435. if (id == 0)
  10436. id = DockContextGenNodeID(ctx);
  10437. else
  10438. IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
  10439. // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
  10440. IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id);
  10441. ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
  10442. ctx->DockContext->Nodes.SetVoidPtr(node->ID, node);
  10443. return node;
  10444. }
  10445. static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
  10446. {
  10447. ImGuiContext& g = *ctx;
  10448. ImGuiDockContext* dc = ctx->DockContext;
  10449. IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID);
  10450. IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
  10451. IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
  10452. IM_ASSERT(node->Windows.Size == 0);
  10453. if (node->HostWindow)
  10454. node->HostWindow->DockNodeAsHost = NULL;
  10455. ImGuiDockNode* parent_node = node->ParentNode;
  10456. const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
  10457. if (merge)
  10458. {
  10459. IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
  10460. ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
  10461. DockNodeTreeMerge(&g, parent_node, sibling_node);
  10462. }
  10463. else
  10464. {
  10465. for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
  10466. if (parent_node->ChildNodes[n] == node)
  10467. node->ParentNode->ChildNodes[n] = NULL;
  10468. dc->Nodes.SetVoidPtr(node->ID, NULL);
  10469. IM_DELETE(node);
  10470. }
  10471. }
  10472. static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
  10473. {
  10474. const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
  10475. const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
  10476. return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
  10477. }
  10478. // Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
  10479. struct ImGuiDockContextPruneNodeData
  10480. {
  10481. int CountWindows, CountChildWindows, CountChildNodes;
  10482. ImGuiID RootId;
  10483. ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
  10484. };
  10485. // Garbage collect unused nodes (run once at init time)
  10486. static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
  10487. {
  10488. ImGuiContext& g = *ctx;
  10489. ImGuiDockContext* dc = ctx->DockContext;
  10490. IM_ASSERT(g.Windows.Size == 0);
  10491. ImPool<ImGuiDockContextPruneNodeData> pool;
  10492. pool.Reserve(dc->SettingsNodes.Size);
  10493. // Count child nodes and compute RootID
  10494. for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
  10495. {
  10496. ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
  10497. ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
  10498. pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
  10499. if (settings->ParentNodeId)
  10500. pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
  10501. }
  10502. // Count reference to dock ids from dockspaces
  10503. // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
  10504. for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
  10505. {
  10506. ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
  10507. if (settings->ParentWindowId != 0)
  10508. if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId))
  10509. if (window_settings->DockId)
  10510. if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
  10511. data->CountChildNodes++;
  10512. }
  10513. // Count reference to dock ids from window settings
  10514. // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
  10515. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  10516. if (ImGuiID dock_id = settings->DockId)
  10517. if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
  10518. {
  10519. data->CountWindows++;
  10520. if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
  10521. data_root->CountChildWindows++;
  10522. }
  10523. // Prune
  10524. for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
  10525. {
  10526. ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
  10527. ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
  10528. if (data->CountWindows > 1)
  10529. continue;
  10530. ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
  10531. bool remove = false;
  10532. remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window
  10533. remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
  10534. remove |= (data_root->CountChildWindows == 0);
  10535. if (remove)
  10536. {
  10537. IMGUI_DEBUG_LOG_DOCKING("DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
  10538. DockSettingsRemoveNodeReferences(&settings->ID, 1);
  10539. settings->ID = 0;
  10540. }
  10541. }
  10542. }
  10543. static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
  10544. {
  10545. // Build nodes
  10546. for (int node_n = 0; node_n < node_settings_count; node_n++)
  10547. {
  10548. ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
  10549. if (settings->ID == 0)
  10550. continue;
  10551. ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
  10552. node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
  10553. node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
  10554. node->Size = ImVec2(settings->Size.x, settings->Size.y);
  10555. node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
  10556. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
  10557. if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
  10558. node->ParentNode->ChildNodes[0] = node;
  10559. else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
  10560. node->ParentNode->ChildNodes[1] = node;
  10561. node->SelectedTabId = settings->SelectedWindowId;
  10562. node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
  10563. node->LocalFlags |= (settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
  10564. // Bind host window immediately if it already exist (in case of a rebuild)
  10565. // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
  10566. char host_window_title[20];
  10567. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  10568. node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
  10569. }
  10570. }
  10571. void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
  10572. {
  10573. // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
  10574. ImGuiContext& g = *ctx;
  10575. for (int n = 0; n < g.Windows.Size; n++)
  10576. {
  10577. ImGuiWindow* window = g.Windows[n];
  10578. if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
  10579. continue;
  10580. if (window->DockNode != NULL)
  10581. continue;
  10582. ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
  10583. IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
  10584. if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
  10585. DockNodeAddWindow(node, window, true);
  10586. }
  10587. }
  10588. //-----------------------------------------------------------------------------
  10589. // Docking: ImGuiDockContext Docking/Undocking functions
  10590. //-----------------------------------------------------------------------------
  10591. // - DockContextQueueDock()
  10592. // - DockContextQueueUndockWindow()
  10593. // - DockContextQueueUndockNode()
  10594. // - DockContextQueueNotifyRemovedNode()
  10595. // - DockContextProcessDock()
  10596. // - DockContextProcessUndockWindow()
  10597. // - DockContextProcessUndockNode()
  10598. // - DockContextCalcDropPosForDocking()
  10599. //-----------------------------------------------------------------------------
  10600. void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
  10601. {
  10602. IM_ASSERT(target != payload);
  10603. ImGuiDockRequest req;
  10604. req.Type = ImGuiDockRequestType_Dock;
  10605. req.DockTargetWindow = target;
  10606. req.DockTargetNode = target_node;
  10607. req.DockPayload = payload;
  10608. req.DockSplitDir = split_dir;
  10609. req.DockSplitRatio = split_ratio;
  10610. req.DockSplitOuter = split_outer;
  10611. ctx->DockContext->Requests.push_back(req);
  10612. }
  10613. void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
  10614. {
  10615. ImGuiDockRequest req;
  10616. req.Type = ImGuiDockRequestType_Undock;
  10617. req.UndockTargetWindow = window;
  10618. ctx->DockContext->Requests.push_back(req);
  10619. }
  10620. void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
  10621. {
  10622. ImGuiDockRequest req;
  10623. req.Type = ImGuiDockRequestType_Undock;
  10624. req.UndockTargetNode = node;
  10625. ctx->DockContext->Requests.push_back(req);
  10626. }
  10627. void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
  10628. {
  10629. ImGuiDockContext* dc = ctx->DockContext;
  10630. for (int n = 0; n < dc->Requests.Size; n++)
  10631. if (dc->Requests[n].DockTargetNode == node)
  10632. dc->Requests[n].Type = ImGuiDockRequestType_None;
  10633. }
  10634. void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
  10635. {
  10636. IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
  10637. IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
  10638. ImGuiContext& g = *ctx;
  10639. IM_UNUSED(g);
  10640. ImGuiWindow* payload_window = req->DockPayload; // Optional
  10641. ImGuiWindow* target_window = req->DockTargetWindow;
  10642. ImGuiDockNode* node = req->DockTargetNode;
  10643. if (payload_window)
  10644. 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);
  10645. else
  10646. IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
  10647. // Decide which Tab will be selected at the end of the operation
  10648. ImGuiID next_selected_id = 0;
  10649. ImGuiDockNode* payload_node = NULL;
  10650. if (payload_window)
  10651. {
  10652. payload_node = payload_window->DockNodeAsHost;
  10653. payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
  10654. if (payload_node && payload_node->IsLeafNode())
  10655. next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
  10656. if (payload_node == NULL)
  10657. next_selected_id = payload_window->ID;
  10658. }
  10659. // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
  10660. // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
  10661. if (node)
  10662. IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
  10663. if (node && target_window && node == target_window->DockNodeAsHost)
  10664. IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
  10665. // Create new node and add existing window to it
  10666. if (node == NULL)
  10667. {
  10668. node = DockContextAddNode(ctx, 0);
  10669. node->Pos = target_window->Pos;
  10670. node->Size = target_window->Size;
  10671. if (target_window->DockNodeAsHost == NULL)
  10672. {
  10673. DockNodeAddWindow(node, target_window, true);
  10674. node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
  10675. target_window->DockIsActive = true;
  10676. }
  10677. }
  10678. ImGuiDir split_dir = req->DockSplitDir;
  10679. if (split_dir != ImGuiDir_None)
  10680. {
  10681. // Split into one, one side will be our payload node unless we are dropping a loose window
  10682. const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  10683. 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
  10684. const float split_ratio = req->DockSplitRatio;
  10685. DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here!
  10686. ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
  10687. new_node->HostWindow = node->HostWindow;
  10688. node = new_node;
  10689. }
  10690. node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar;
  10691. if (node != payload_node)
  10692. {
  10693. // 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!)
  10694. if (node->Windows.Size > 0 && node->TabBar == NULL)
  10695. {
  10696. DockNodeAddTabBar(node);
  10697. for (int n = 0; n < node->Windows.Size; n++)
  10698. TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
  10699. }
  10700. if (payload_node != NULL)
  10701. {
  10702. // Transfer full payload node (with 1+ child windows or child nodes)
  10703. if (payload_node->IsSplitNode())
  10704. {
  10705. if (node->Windows.Size > 0)
  10706. {
  10707. // 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.
  10708. // In this situation, we move the windows of the target node into the currently visible node of the payload.
  10709. // This allows us to preserve some of the underlying dock tree settings nicely.
  10710. IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
  10711. ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
  10712. if (visible_node->TabBar)
  10713. IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
  10714. DockNodeMoveWindows(node, visible_node);
  10715. DockNodeMoveWindows(visible_node, node);
  10716. DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
  10717. }
  10718. if (node->IsCentralNode())
  10719. {
  10720. // Central node property needs to be moved to a leaf node, pick the last focused one.
  10721. // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
  10722. ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
  10723. IM_ASSERT(last_focused_node != NULL);
  10724. ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
  10725. IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
  10726. last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  10727. node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode;
  10728. last_focused_root_node->CentralNode = last_focused_node;
  10729. }
  10730. IM_ASSERT(node->Windows.Size == 0);
  10731. DockNodeMoveChildNodes(node, payload_node);
  10732. }
  10733. else
  10734. {
  10735. const ImGuiID payload_dock_id = payload_node->ID;
  10736. DockNodeMoveWindows(node, payload_node);
  10737. DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
  10738. }
  10739. DockContextRemoveNode(ctx, payload_node, true);
  10740. }
  10741. else if (payload_window)
  10742. {
  10743. // Transfer single window
  10744. const ImGuiID payload_dock_id = payload_window->DockId;
  10745. node->VisibleWindow = payload_window;
  10746. DockNodeAddWindow(node, payload_window, true);
  10747. if (payload_dock_id != 0)
  10748. DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
  10749. }
  10750. }
  10751. else
  10752. {
  10753. // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
  10754. node->WantHiddenTabBarUpdate = true;
  10755. }
  10756. // Update selection immediately
  10757. if (ImGuiTabBar* tab_bar = node->TabBar)
  10758. tab_bar->NextSelectedTabId = next_selected_id;
  10759. MarkIniSettingsDirty();
  10760. }
  10761. void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
  10762. {
  10763. (void)ctx;
  10764. if (window->DockNode)
  10765. DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
  10766. else
  10767. window->DockId = 0;
  10768. window->Collapsed = false;
  10769. window->DockIsActive = false;
  10770. window->DockTabIsVisible = false;
  10771. MarkIniSettingsDirty();
  10772. }
  10773. void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
  10774. {
  10775. IM_ASSERT(node->IsLeafNode());
  10776. IM_ASSERT(node->Windows.Size >= 1);
  10777. if (node->IsRootNode() || node->IsCentralNode())
  10778. {
  10779. // 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.
  10780. ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
  10781. DockNodeMoveWindows(new_node, node);
  10782. DockSettingsRenameNodeReferences(node->ID, new_node->ID);
  10783. for (int n = 0; n < new_node->Windows.Size; n++)
  10784. UpdateWindowParentAndRootLinks(new_node->Windows[n], new_node->Windows[n]->Flags, NULL);
  10785. node = new_node;
  10786. }
  10787. else
  10788. {
  10789. // Otherwise extract our node and merging our sibling back into the parent node.
  10790. IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
  10791. int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
  10792. node->ParentNode->ChildNodes[index_in_parent] = NULL;
  10793. DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
  10794. 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
  10795. node->ParentNode = NULL;
  10796. }
  10797. node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_Window;
  10798. node->WantMouseMove = true;
  10799. MarkIniSettingsDirty();
  10800. }
  10801. // This is mostly used for automation.
  10802. bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
  10803. {
  10804. if (split_outer)
  10805. {
  10806. IM_ASSERT(0);
  10807. }
  10808. else
  10809. {
  10810. ImGuiDockPreviewData split_data;
  10811. DockNodePreviewDockSetup(target, target_node, payload, &split_data, false, split_outer);
  10812. if (split_data.DropRectsDraw[split_dir+1].IsInverted())
  10813. return false;
  10814. *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
  10815. return true;
  10816. }
  10817. return false;
  10818. }
  10819. //-----------------------------------------------------------------------------
  10820. // Docking: ImGuiDockNode
  10821. //-----------------------------------------------------------------------------
  10822. // - DockNodeGetTabOrder()
  10823. // - DockNodeAddWindow()
  10824. // - DockNodeRemoveWindow()
  10825. // - DockNodeMoveChildNodes()
  10826. // - DockNodeMoveWindows()
  10827. // - DockNodeApplyPosSizeToWindows()
  10828. // - DockNodeHideHostWindow()
  10829. // - ImGuiDockNodeFindInfoResults
  10830. // - DockNodeFindInfo()
  10831. // - DockNodeFindWindowByID()
  10832. // - DockNodeUpdateVisibleFlagAndInactiveChilds()
  10833. // - DockNodeUpdateVisibleFlag()
  10834. // - DockNodeStartMouseMovingWindow()
  10835. // - DockNodeUpdate()
  10836. // - DockNodeUpdateWindowMenu()
  10837. // - DockNodeUpdateTabBar()
  10838. // - DockNodeAddTabBar()
  10839. // - DockNodeRemoveTabBar()
  10840. // - DockNodeIsDropAllowedOne()
  10841. // - DockNodeIsDropAllowed()
  10842. // - DockNodeCalcTabBarLayout()
  10843. // - DockNodeCalcSplitRects()
  10844. // - DockNodeCalcDropRectsAndTestMousePos()
  10845. // - DockNodePreviewDockSetup()
  10846. // - DockNodePreviewDockRender()
  10847. //-----------------------------------------------------------------------------
  10848. ImGuiDockNode::ImGuiDockNode(ImGuiID id)
  10849. {
  10850. ID = id;
  10851. SharedFlags = LocalFlags = ImGuiDockNodeFlags_None;
  10852. ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
  10853. TabBar = NULL;
  10854. SplitAxis = ImGuiAxis_None;
  10855. State = ImGuiDockNodeState_Unknown;
  10856. HostWindow = VisibleWindow = NULL;
  10857. CentralNode = OnlyNodeWithWindows = NULL;
  10858. LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
  10859. LastFocusedNodeId = 0;
  10860. SelectedTabId = 0;
  10861. WantCloseTabId = 0;
  10862. AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
  10863. AuthorityForViewport = ImGuiDataAuthority_Auto;
  10864. IsVisible = true;
  10865. IsFocused = HasCloseButton = HasWindowMenuButton = EnableCloseButton = false;
  10866. WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
  10867. MarkedForPosSizeWrite = false;
  10868. }
  10869. ImGuiDockNode::~ImGuiDockNode()
  10870. {
  10871. IM_DELETE(TabBar);
  10872. TabBar = NULL;
  10873. ChildNodes[0] = ChildNodes[1] = NULL;
  10874. }
  10875. int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
  10876. {
  10877. ImGuiTabBar* tab_bar = window->DockNode->TabBar;
  10878. if (tab_bar == NULL)
  10879. return -1;
  10880. ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->ID);
  10881. return tab ? tab_bar->GetTabOrder(tab) : -1;
  10882. }
  10883. static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
  10884. {
  10885. ImGuiContext& g = *GImGui; (void)g;
  10886. if (window->DockNode)
  10887. {
  10888. // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
  10889. IM_ASSERT(window->DockNode->ID != node->ID);
  10890. DockNodeRemoveWindow(window->DockNode, window, 0);
  10891. }
  10892. IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
  10893. IMGUI_DEBUG_LOG_DOCKING("DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
  10894. node->Windows.push_back(window);
  10895. node->WantHiddenTabBarUpdate = true;
  10896. window->DockNode = node;
  10897. window->DockId = node->ID;
  10898. window->DockIsActive = (node->Windows.Size > 1);
  10899. window->DockTabWantClose = false;
  10900. // If more than 2 windows appeared on the same frame, we'll create a new hosting DockNode from the point of the second window submission.
  10901. // Then we need to hide the first window (after its been output) otherwise it would be visible as a standalone window for one frame.
  10902. if (node->HostWindow == NULL && node->Windows.Size == 2 && node->Windows[0]->WasActive == false)
  10903. {
  10904. node->Windows[0]->Hidden = true;
  10905. node->Windows[0]->HiddenFramesCanSkipItems = 1;
  10906. }
  10907. // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
  10908. // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
  10909. if (node->HostWindow == NULL && node->IsFloatingNode())
  10910. {
  10911. if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
  10912. node->AuthorityForPos = ImGuiDataAuthority_Window;
  10913. if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
  10914. node->AuthorityForSize = ImGuiDataAuthority_Window;
  10915. if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
  10916. node->AuthorityForViewport = ImGuiDataAuthority_Window;
  10917. }
  10918. // Add to tab bar if requested
  10919. if (add_to_tab_bar)
  10920. {
  10921. if (node->TabBar == NULL)
  10922. {
  10923. DockNodeAddTabBar(node);
  10924. node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
  10925. // Add existing windows
  10926. for (int n = 0; n < node->Windows.Size - 1; n++)
  10927. TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
  10928. }
  10929. TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
  10930. }
  10931. DockNodeUpdateVisibleFlag(node);
  10932. // 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.
  10933. if (node->HostWindow)
  10934. UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
  10935. }
  10936. static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
  10937. {
  10938. ImGuiContext& g = *GImGui;
  10939. IM_ASSERT(window->DockNode == node);
  10940. //IM_ASSERT(window->RootWindow == node->HostWindow);
  10941. //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
  10942. IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
  10943. IMGUI_DEBUG_LOG_DOCKING("DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
  10944. window->DockNode = NULL;
  10945. window->DockIsActive = window->DockTabWantClose = false;
  10946. window->DockId = save_dock_id;
  10947. UpdateWindowParentAndRootLinks(window, window->Flags & ~ImGuiWindowFlags_ChildWindow, NULL); // Update immediately
  10948. // Remove window
  10949. bool erased = false;
  10950. for (int n = 0; n < node->Windows.Size; n++)
  10951. if (node->Windows[n] == window)
  10952. {
  10953. node->Windows.erase(node->Windows.Data + n);
  10954. erased = true;
  10955. break;
  10956. }
  10957. IM_ASSERT(erased);
  10958. if (node->VisibleWindow == window)
  10959. node->VisibleWindow = NULL;
  10960. // Remove tab and possibly tab bar
  10961. node->WantHiddenTabBarUpdate = true;
  10962. if (node->TabBar)
  10963. {
  10964. TabBarRemoveTab(node->TabBar, window->ID);
  10965. const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
  10966. if (node->Windows.Size < tab_count_threshold_for_tab_bar)
  10967. DockNodeRemoveTabBar(node);
  10968. }
  10969. if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
  10970. {
  10971. // Automatic dock node delete themselves if they are not holding at least one tab
  10972. DockContextRemoveNode(&g, node, true);
  10973. return;
  10974. }
  10975. if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
  10976. {
  10977. ImGuiWindow* remaining_window = node->Windows[0];
  10978. if (node->HostWindow->ViewportOwned && node->IsRootNode())
  10979. {
  10980. // Transfer viewport back to the remaining loose window
  10981. IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
  10982. node->HostWindow->Viewport->Window = remaining_window;
  10983. node->HostWindow->Viewport->ID = remaining_window->ID;
  10984. }
  10985. remaining_window->Collapsed = node->HostWindow->Collapsed;
  10986. }
  10987. // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
  10988. DockNodeUpdateVisibleFlag(node);
  10989. }
  10990. static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
  10991. {
  10992. IM_ASSERT(dst_node->Windows.Size == 0);
  10993. dst_node->ChildNodes[0] = src_node->ChildNodes[0];
  10994. dst_node->ChildNodes[1] = src_node->ChildNodes[1];
  10995. if (dst_node->ChildNodes[0])
  10996. dst_node->ChildNodes[0]->ParentNode = dst_node;
  10997. if (dst_node->ChildNodes[1])
  10998. dst_node->ChildNodes[1]->ParentNode = dst_node;
  10999. dst_node->SplitAxis = src_node->SplitAxis;
  11000. dst_node->SizeRef = src_node->SizeRef;
  11001. src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
  11002. }
  11003. static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
  11004. {
  11005. // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
  11006. IM_ASSERT(src_node && dst_node && dst_node != src_node);
  11007. ImGuiTabBar* src_tab_bar = src_node->TabBar;
  11008. if (src_tab_bar != NULL)
  11009. IM_ASSERT(src_node->Windows.Size == src_node->TabBar->Tabs.Size);
  11010. // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
  11011. bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
  11012. if (move_tab_bar)
  11013. {
  11014. dst_node->TabBar = src_node->TabBar;
  11015. src_node->TabBar = NULL;
  11016. }
  11017. for (int n = 0; n < src_node->Windows.Size; n++)
  11018. {
  11019. ImGuiWindow* window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n];
  11020. window->DockNode = NULL;
  11021. window->DockIsActive = false;
  11022. DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true);
  11023. }
  11024. src_node->Windows.clear();
  11025. if (!move_tab_bar && src_node->TabBar)
  11026. {
  11027. if (dst_node->TabBar)
  11028. dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
  11029. DockNodeRemoveTabBar(src_node);
  11030. }
  11031. }
  11032. static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
  11033. {
  11034. for (int n = 0; n < node->Windows.Size; n++)
  11035. {
  11036. 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
  11037. SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
  11038. }
  11039. }
  11040. static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
  11041. {
  11042. if (node->HostWindow)
  11043. {
  11044. if (node->HostWindow->DockNodeAsHost == node)
  11045. node->HostWindow->DockNodeAsHost = NULL;
  11046. node->HostWindow = NULL;
  11047. }
  11048. if (node->Windows.Size == 1)
  11049. {
  11050. node->VisibleWindow = node->Windows[0];
  11051. node->Windows[0]->DockIsActive = false;
  11052. }
  11053. if (node->TabBar)
  11054. DockNodeRemoveTabBar(node);
  11055. }
  11056. // Search function called once by root node in DockNodeUpdate()
  11057. struct ImGuiDockNodeFindInfoResults
  11058. {
  11059. ImGuiDockNode* CentralNode;
  11060. ImGuiDockNode* FirstNodeWithWindows;
  11061. int CountNodesWithWindows;
  11062. //ImGuiWindowClass WindowClassForMerges;
  11063. ImGuiDockNodeFindInfoResults() { CentralNode = FirstNodeWithWindows = NULL; CountNodesWithWindows = 0; }
  11064. };
  11065. static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeFindInfoResults* results)
  11066. {
  11067. if (node->Windows.Size > 0)
  11068. {
  11069. if (results->FirstNodeWithWindows == NULL)
  11070. results->FirstNodeWithWindows = node;
  11071. results->CountNodesWithWindows++;
  11072. }
  11073. if (node->IsCentralNode())
  11074. {
  11075. IM_ASSERT(results->CentralNode == NULL); // Should be only one
  11076. IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
  11077. results->CentralNode = node;
  11078. }
  11079. if (results->CountNodesWithWindows > 1 && results->CentralNode != NULL)
  11080. return;
  11081. if (node->ChildNodes[0])
  11082. DockNodeFindInfo(node->ChildNodes[0], results);
  11083. if (node->ChildNodes[1])
  11084. DockNodeFindInfo(node->ChildNodes[1], results);
  11085. }
  11086. static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
  11087. {
  11088. IM_ASSERT(id != 0);
  11089. for (int n = 0; n < node->Windows.Size; n++)
  11090. if (node->Windows[n]->ID == id)
  11091. return node->Windows[n];
  11092. return NULL;
  11093. }
  11094. // - Remove inactive windows/nodes.
  11095. // - Update visibility flag.
  11096. static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node)
  11097. {
  11098. ImGuiContext& g = *GImGui;
  11099. IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
  11100. // Inherit most flags
  11101. if (node->ParentNode)
  11102. node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
  11103. // Recurse into children
  11104. // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
  11105. // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
  11106. // 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)
  11107. if (node->ChildNodes[0])
  11108. DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[0]);
  11109. if (node->ChildNodes[1])
  11110. DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[1]);
  11111. // Remove inactive windows
  11112. // Merge node flags overrides stored in windows
  11113. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  11114. {
  11115. ImGuiWindow* window = node->Windows[window_n];
  11116. IM_ASSERT(window->DockNode == node);
  11117. bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
  11118. bool remove = false;
  11119. remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
  11120. remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
  11121. remove |= (window->DockTabWantClose);
  11122. if (remove)
  11123. {
  11124. window->DockTabWantClose = false;
  11125. if (node->Windows.Size == 1 && !node->IsCentralNode())
  11126. {
  11127. DockNodeHideHostWindow(node);
  11128. node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
  11129. DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
  11130. return;
  11131. }
  11132. DockNodeRemoveWindow(node, window, node->ID);
  11133. window_n--;
  11134. }
  11135. else
  11136. {
  11137. node->LocalFlags &= ~window->WindowClass.DockNodeFlagsOverrideClear;
  11138. node->LocalFlags |= window->WindowClass.DockNodeFlagsOverrideSet;
  11139. }
  11140. }
  11141. // Auto-hide tab bar option
  11142. ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
  11143. if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
  11144. node->WantHiddenTabBarToggle = true;
  11145. node->WantHiddenTabBarUpdate = false;
  11146. // Cancel toggling if we know our tab bar is enforced to be hidden at all times
  11147. if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
  11148. node->WantHiddenTabBarToggle = false;
  11149. // Apply toggles at a single point of the frame (here!)
  11150. if (node->Windows.Size > 1)
  11151. node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar;
  11152. else if (node->WantHiddenTabBarToggle)
  11153. node->LocalFlags ^= ImGuiDockNodeFlags_HiddenTabBar;
  11154. node->WantHiddenTabBarToggle = false;
  11155. DockNodeUpdateVisibleFlag(node);
  11156. }
  11157. static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
  11158. {
  11159. // Update visibility flag
  11160. bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
  11161. is_visible |= (node->Windows.Size > 0);
  11162. is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
  11163. is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
  11164. node->IsVisible = is_visible;
  11165. }
  11166. static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
  11167. {
  11168. ImGuiContext& g = *GImGui;
  11169. IM_ASSERT(node->WantMouseMove == true);
  11170. ImVec2 backup_active_click_offset = g.ActiveIdClickOffset;
  11171. StartMouseMovingWindow(window);
  11172. g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
  11173. node->WantMouseMove = false;
  11174. g.ActiveIdClickOffset = backup_active_click_offset;
  11175. }
  11176. // Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
  11177. static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
  11178. {
  11179. DockNodeUpdateVisibleFlagAndInactiveChilds(node);
  11180. // FIXME-DOCK: Merge this scan into the one above.
  11181. // - Setup central node pointers
  11182. // - 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!)
  11183. ImGuiDockNodeFindInfoResults results;
  11184. DockNodeFindInfo(node, &results);
  11185. node->CentralNode = results.CentralNode;
  11186. node->OnlyNodeWithWindows = (results.CountNodesWithWindows == 1) ? results.FirstNodeWithWindows : NULL;
  11187. if (node->LastFocusedNodeId == 0 && results.FirstNodeWithWindows != NULL)
  11188. node->LastFocusedNodeId = results.FirstNodeWithWindows->ID;
  11189. // Copy the window class from of our first window so it can be used for proper dock filtering.
  11190. // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
  11191. // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
  11192. if (ImGuiDockNode* first_node_with_windows = results.FirstNodeWithWindows)
  11193. {
  11194. node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
  11195. for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
  11196. if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
  11197. {
  11198. node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
  11199. break;
  11200. }
  11201. }
  11202. }
  11203. static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
  11204. {
  11205. ImGuiContext& g = *GImGui;
  11206. IM_ASSERT(node->LastFrameActive != g.FrameCount);
  11207. node->LastFrameAlive = g.FrameCount;
  11208. node->MarkedForPosSizeWrite = false;
  11209. node->CentralNode = node->OnlyNodeWithWindows = NULL;
  11210. if (node->IsRootNode())
  11211. DockNodeUpdateForRootNode(node);
  11212. // Remove tab bar if not needed
  11213. if (node->TabBar && node->IsNoTabBar())
  11214. DockNodeRemoveTabBar(node);
  11215. // 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)
  11216. bool want_to_hide_host_window = false;
  11217. if (node->Windows.Size <= 1 && node->IsFloatingNode() && node->IsLeafNode())
  11218. if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
  11219. want_to_hide_host_window = true;
  11220. if (want_to_hide_host_window)
  11221. {
  11222. if (node->Windows.Size == 1)
  11223. {
  11224. // Floating window pos/size is authoritative
  11225. ImGuiWindow* single_window = node->Windows[0];
  11226. node->Pos = single_window->Pos;
  11227. node->Size = single_window->SizeFull;
  11228. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
  11229. // Transfer focus immediately so when we revert to a regular window it is immediately selected
  11230. if (node->HostWindow && g.NavWindow == node->HostWindow)
  11231. FocusWindow(single_window);
  11232. if (node->HostWindow)
  11233. {
  11234. single_window->Viewport = node->HostWindow->Viewport;
  11235. single_window->ViewportId = node->HostWindow->ViewportId;
  11236. if (node->HostWindow->ViewportOwned)
  11237. {
  11238. single_window->Viewport->Window = single_window;
  11239. single_window->ViewportOwned = true;
  11240. }
  11241. }
  11242. }
  11243. DockNodeHideHostWindow(node);
  11244. node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
  11245. node->WantCloseAll = false;
  11246. node->WantCloseTabId = 0;
  11247. node->HasCloseButton = node->HasWindowMenuButton = node->EnableCloseButton = false;
  11248. node->LastFrameActive = g.FrameCount;
  11249. if (node->WantMouseMove && node->Windows.Size == 1)
  11250. DockNodeStartMouseMovingWindow(node, node->Windows[0]);
  11251. return;
  11252. }
  11253. // In some circumstance we will defer creating the host window (so everything will be kept hidden),
  11254. // while the expected visible window is resizing itself.
  11255. // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
  11256. // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
  11257. // N+0: Begin(): window created (with no known size), node is created
  11258. // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
  11259. // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
  11260. // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
  11261. // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
  11262. // In reality it isn't very important as user quickly ends up with size data in .ini file.
  11263. if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
  11264. {
  11265. IM_ASSERT(node->Windows.Size > 0);
  11266. ImGuiWindow* ref_window = NULL;
  11267. if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
  11268. ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
  11269. if (ref_window == NULL)
  11270. ref_window = node->Windows[0];
  11271. if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
  11272. {
  11273. node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
  11274. return;
  11275. }
  11276. }
  11277. const ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
  11278. // Bind or create host window
  11279. ImGuiWindow* host_window = NULL;
  11280. bool beginned_into_host_window = false;
  11281. if (node->IsDockSpace())
  11282. {
  11283. // [Explicit root dockspace node]
  11284. IM_ASSERT(node->HostWindow);
  11285. node->EnableCloseButton = false;
  11286. node->HasCloseButton = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0;
  11287. node->HasWindowMenuButton = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
  11288. host_window = node->HostWindow;
  11289. }
  11290. else
  11291. {
  11292. // [Automatic root or child nodes]
  11293. node->EnableCloseButton = false;
  11294. node->HasCloseButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0;
  11295. node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
  11296. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  11297. {
  11298. // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
  11299. ImGuiWindow* window = node->Windows[window_n];
  11300. window->DockIsActive = (node->Windows.Size > 1);
  11301. node->EnableCloseButton |= window->HasCloseButton;
  11302. }
  11303. if (node->IsRootNode() && node->IsVisible)
  11304. {
  11305. ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
  11306. // Sync Pos
  11307. if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
  11308. SetNextWindowPos(ref_window->Pos);
  11309. else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
  11310. SetNextWindowPos(node->Pos);
  11311. // Sync Size
  11312. if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
  11313. SetNextWindowSize(ref_window->SizeFull);
  11314. else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
  11315. SetNextWindowSize(node->Size);
  11316. // Sync Collapsed
  11317. if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
  11318. SetNextWindowCollapsed(ref_window->Collapsed);
  11319. // Sync Viewport
  11320. if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
  11321. SetNextWindowViewport(ref_window->ViewportId);
  11322. SetNextWindowClass(&node->WindowClass);
  11323. // Begin into the host window
  11324. char window_label[20];
  11325. DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
  11326. ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
  11327. window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
  11328. window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
  11329. window_flags |= ImGuiWindowFlags_NoTitleBar;
  11330. PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
  11331. Begin(window_label, NULL, window_flags);
  11332. PopStyleVar();
  11333. beginned_into_host_window = true;
  11334. node->HostWindow = host_window = g.CurrentWindow;
  11335. host_window->DockNodeAsHost = node;
  11336. host_window->DC.CursorPos = host_window->Pos;
  11337. node->Pos = host_window->Pos;
  11338. node->Size = host_window->Size;
  11339. // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
  11340. // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
  11341. // 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.
  11342. // 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
  11343. // 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
  11344. // after the dock host window, losing their top-most status.
  11345. if (node->HostWindow->Appearing)
  11346. BringWindowToDisplayFront(node->HostWindow);
  11347. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
  11348. }
  11349. else if (node->ParentNode)
  11350. {
  11351. node->HostWindow = host_window = node->ParentNode->HostWindow;
  11352. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
  11353. }
  11354. if (node->WantMouseMove && node->HostWindow)
  11355. DockNodeStartMouseMovingWindow(node, node->HostWindow);
  11356. }
  11357. // Update focused node (the one whose title bar is highlight) within a node tree
  11358. if (node->IsSplitNode())
  11359. IM_ASSERT(node->TabBar == NULL);
  11360. if (node->IsRootNode())
  11361. if (g.NavWindow && g.NavWindow->RootWindowDockStop->DockNode && g.NavWindow->RootWindowDockStop->ParentWindow == host_window)
  11362. node->LastFocusedNodeId = g.NavWindow->RootWindowDockStop->DockNode->ID;
  11363. // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size after
  11364. // processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
  11365. const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
  11366. if (render_dockspace_bg)
  11367. {
  11368. host_window->DrawList->ChannelsSplit(2);
  11369. host_window->DrawList->ChannelsSetCurrent(1);
  11370. }
  11371. // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
  11372. const ImGuiDockNode* central_node = node->CentralNode;
  11373. const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
  11374. bool central_node_hole_register_hit_test_hole = central_node_hole;
  11375. if (central_node_hole)
  11376. if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
  11377. if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
  11378. central_node_hole_register_hit_test_hole = false;
  11379. if (central_node_hole_register_hit_test_hole)
  11380. {
  11381. // Add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
  11382. 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
  11383. ImRect central_hole(central_node->Pos, central_node->Pos + central_node->Size);
  11384. central_hole.Expand(ImVec2(-WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, -WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS));
  11385. if (central_node_hole && !central_hole.IsInverted())
  11386. {
  11387. SetWindowHitTestHole(host_window, central_hole.Min, central_hole.Max - central_hole.Min);
  11388. SetWindowHitTestHole(host_window->ParentWindow, central_hole.Min, central_hole.Max - central_hole.Min);
  11389. }
  11390. }
  11391. // Update position/size, process and draw resizing splitters
  11392. if (node->IsRootNode() && host_window)
  11393. {
  11394. DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
  11395. DockNodeTreeUpdateSplitter(node);
  11396. }
  11397. // Draw empty node background (currently can only be the Central Node)
  11398. if (host_window && node->IsEmpty() && node->IsVisible && !(node_flags & ImGuiDockNodeFlags_PassthruCentralNode))
  11399. host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_DockingEmptyBg));
  11400. // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
  11401. if (render_dockspace_bg && node->IsVisible)
  11402. {
  11403. host_window->DrawList->ChannelsSetCurrent(0);
  11404. if (central_node_hole)
  11405. RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
  11406. else
  11407. host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
  11408. host_window->DrawList->ChannelsMerge();
  11409. }
  11410. // Draw and populate Tab Bar
  11411. if (host_window && node->Windows.Size > 0)
  11412. {
  11413. DockNodeUpdateTabBar(node, host_window);
  11414. }
  11415. else
  11416. {
  11417. node->WantCloseAll = false;
  11418. node->WantCloseTabId = 0;
  11419. node->IsFocused = false;
  11420. }
  11421. if (node->TabBar && node->TabBar->SelectedTabId)
  11422. node->SelectedTabId = node->TabBar->SelectedTabId;
  11423. else if (node->Windows.Size > 0)
  11424. node->SelectedTabId = node->Windows[0]->ID;
  11425. // Draw payload drop target
  11426. if (host_window && node->IsVisible)
  11427. if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindow != host_window))
  11428. BeginDockableDragDropTarget(host_window);
  11429. // We update this after DockNodeUpdateTabBar()
  11430. node->LastFrameActive = g.FrameCount;
  11431. // Recurse into children
  11432. // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
  11433. if (host_window)
  11434. {
  11435. if (node->ChildNodes[0])
  11436. DockNodeUpdate(node->ChildNodes[0]);
  11437. if (node->ChildNodes[1])
  11438. DockNodeUpdate(node->ChildNodes[1]);
  11439. // Render outer borders last (after the tab bar)
  11440. if (node->IsRootNode())
  11441. RenderWindowOuterBorders(host_window);
  11442. }
  11443. // End host window
  11444. if (beginned_into_host_window) //-V1020
  11445. End();
  11446. }
  11447. // 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.
  11448. static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
  11449. {
  11450. ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
  11451. ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
  11452. if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
  11453. return d;
  11454. return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
  11455. }
  11456. static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
  11457. {
  11458. // Try to position the menu so it is more likely to stays within the same viewport
  11459. ImGuiContext& g = *GImGui;
  11460. ImGuiID ret_tab_id = 0;
  11461. if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
  11462. SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
  11463. else
  11464. SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
  11465. if (BeginPopup("#WindowMenu"))
  11466. {
  11467. node->IsFocused = true;
  11468. if (tab_bar->Tabs.Size == 1)
  11469. {
  11470. if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar()))
  11471. node->WantHiddenTabBarToggle = true;
  11472. }
  11473. else
  11474. {
  11475. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
  11476. {
  11477. ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  11478. IM_ASSERT(tab->Window != NULL);
  11479. if (Selectable(tab->Window->Name, tab->ID == tab_bar->SelectedTabId))
  11480. ret_tab_id = tab->ID;
  11481. SameLine();
  11482. Text(" ");
  11483. }
  11484. }
  11485. EndPopup();
  11486. }
  11487. return ret_tab_id;
  11488. }
  11489. static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
  11490. {
  11491. ImGuiContext& g = *GImGui;
  11492. ImGuiStyle& style = g.Style;
  11493. const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
  11494. const bool closed_all = node->WantCloseAll && node_was_active;
  11495. const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
  11496. node->WantCloseAll = false;
  11497. node->WantCloseTabId = 0;
  11498. // Decide if we should use a focused title bar color
  11499. bool is_focused = false;
  11500. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  11501. if (g.NavWindowingTarget)
  11502. is_focused = (g.NavWindowingTarget->DockNode == node);
  11503. else if (g.NavWindow && g.NavWindow->RootWindowForTitleBarHighlight == host_window->RootWindow && root_node->LastFocusedNodeId == node->ID)
  11504. is_focused = true;
  11505. // Hidden tab bar will show a triangle on the upper-left (in Begin)
  11506. if (node->IsHiddenTabBar() || node->IsNoTabBar())
  11507. {
  11508. node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
  11509. node->IsFocused = is_focused;
  11510. if (is_focused)
  11511. node->LastFrameFocused = g.FrameCount;
  11512. if (node->VisibleWindow)
  11513. {
  11514. // Notify root of visible window (used to display title in OS task bar)
  11515. if (is_focused || root_node->VisibleWindow == NULL)
  11516. root_node->VisibleWindow = node->VisibleWindow;
  11517. if (node->TabBar)
  11518. node->TabBar->VisibleTabId = node->VisibleWindow->ID;
  11519. }
  11520. return;
  11521. }
  11522. // 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
  11523. bool backup_skip_item = host_window->SkipItems;
  11524. if (!node->IsDockSpace())
  11525. {
  11526. host_window->SkipItems = false;
  11527. host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
  11528. host_window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
  11529. }
  11530. // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
  11531. // 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,
  11532. // as docked windows themselves will override the stack with their own root ID.
  11533. PushOverrideID(node->ID);
  11534. ImGuiTabBar* tab_bar = node->TabBar;
  11535. bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
  11536. if (tab_bar == NULL)
  11537. {
  11538. DockNodeAddTabBar(node);
  11539. tab_bar = node->TabBar;
  11540. }
  11541. ImGuiID focus_tab_id = 0;
  11542. node->IsFocused = is_focused;
  11543. const ImGuiDockNodeFlags node_flags = node->GetMergedFlags();
  11544. const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
  11545. const bool has_close_button = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0;
  11546. // In a dock node, the Collapse Button turns into the Window Menu button.
  11547. // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
  11548. if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
  11549. {
  11550. if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar))
  11551. focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
  11552. is_focused |= node->IsFocused;
  11553. }
  11554. // Layout
  11555. ImRect title_bar_rect, tab_bar_rect;
  11556. ImVec2 window_menu_button_pos;
  11557. DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos);
  11558. // Title bar
  11559. if (is_focused)
  11560. node->LastFrameFocused = g.FrameCount;
  11561. ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  11562. host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, ImDrawCornerFlags_Top);
  11563. // Docking/Collapse button
  11564. if (has_window_menu_button)
  11565. {
  11566. if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node))
  11567. OpenPopup("#WindowMenu");
  11568. if (IsItemActive())
  11569. focus_tab_id = tab_bar->SelectedTabId;
  11570. }
  11571. // Submit new tabs and apply NavWindow focus back to the tab bar. They will be added as Unsorted and sorted below based on relative DockOrder value.
  11572. const int tabs_count_old = tab_bar->Tabs.Size;
  11573. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  11574. {
  11575. ImGuiWindow* window = node->Windows[window_n];
  11576. if (g.NavWindow && g.NavWindow->RootWindowDockStop == window)
  11577. tab_bar->SelectedTabId = window->ID;
  11578. if (TabBarFindTabByID(tab_bar, window->ID) == NULL)
  11579. TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
  11580. }
  11581. // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
  11582. int tabs_unsorted_start = tab_bar->Tabs.Size;
  11583. for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
  11584. {
  11585. // 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?
  11586. tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
  11587. tabs_unsorted_start = tab_n;
  11588. }
  11589. if (tab_bar->Tabs.Size > tabs_unsorted_start)
  11590. {
  11591. 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)" : "");
  11592. for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
  11593. IMGUI_DEBUG_LOG_DOCKING(" - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
  11594. if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
  11595. ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
  11596. }
  11597. // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
  11598. if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
  11599. tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
  11600. else if (tab_bar->Tabs.Size > tabs_count_old)
  11601. tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->ID;
  11602. // Begin tab bar
  11603. ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
  11604. tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
  11605. if (!host_window->Collapsed && is_focused)
  11606. tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
  11607. BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
  11608. //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
  11609. // Submit actual tabs
  11610. node->VisibleWindow = NULL;
  11611. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  11612. {
  11613. ImGuiWindow* window = node->Windows[window_n];
  11614. if ((closed_all || closed_one == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
  11615. continue;
  11616. if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
  11617. {
  11618. ImGuiTabItemFlags tab_item_flags = 0;
  11619. if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
  11620. tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
  11621. if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
  11622. tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
  11623. bool tab_open = true;
  11624. TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
  11625. if (!tab_open)
  11626. node->WantCloseTabId = window->ID;
  11627. if (tab_bar->VisibleTabId == window->ID)
  11628. node->VisibleWindow = window;
  11629. // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
  11630. window->DockTabItemStatusFlags = host_window->DC.LastItemStatusFlags;
  11631. window->DockTabItemRect = host_window->DC.LastItemRect;
  11632. // Update navigation ID on menu layer
  11633. if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << 1)) == 0)
  11634. host_window->NavLastIds[1] = window->ID;
  11635. }
  11636. }
  11637. // Notify root of visible window (used to display title in OS task bar)
  11638. if (node->VisibleWindow)
  11639. if (is_focused || root_node->VisibleWindow == NULL)
  11640. root_node->VisibleWindow = node->VisibleWindow;
  11641. // Close button (after VisibleWindow was updated)
  11642. // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->ID may be != from tab_bar->SelectedTabId
  11643. if (has_close_button && node->VisibleWindow)
  11644. {
  11645. if (!node->VisibleWindow->HasCloseButton)
  11646. {
  11647. PushItemFlag(ImGuiItemFlags_Disabled, true);
  11648. PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.5f));
  11649. }
  11650. const float button_sz = g.FontSize;
  11651. if (CloseButton(host_window->GetID("#CLOSE"), title_bar_rect.GetTR() + ImVec2(-style.FramePadding.x * 2.0f - button_sz, 0.0f)))
  11652. if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->VisibleTabId))
  11653. {
  11654. node->WantCloseTabId = tab->ID;
  11655. TabBarCloseTab(tab_bar, tab);
  11656. }
  11657. //if (IsItemActive())
  11658. // focus_tab_id = tab_bar->SelectedTabId;
  11659. if (!node->VisibleWindow->HasCloseButton)
  11660. {
  11661. PopStyleColor();
  11662. PopItemFlag();
  11663. }
  11664. }
  11665. // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
  11666. // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
  11667. ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
  11668. if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
  11669. {
  11670. bool held;
  11671. ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held);
  11672. if (held)
  11673. {
  11674. if (IsMouseClicked(0))
  11675. focus_tab_id = tab_bar->SelectedTabId;
  11676. // Forward moving request to selected window
  11677. if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
  11678. StartMouseMovingWindowOrNode(tab->Window, node, false);
  11679. }
  11680. }
  11681. // Forward focus from host node to selected window
  11682. //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
  11683. // focus_tab_id = tab_bar->SelectedTabId;
  11684. // When clicked on a tab we requested focus to the docked child
  11685. // This overrides the value set by "forward focus from host node to selected window".
  11686. if (tab_bar->NextSelectedTabId)
  11687. focus_tab_id = tab_bar->NextSelectedTabId;
  11688. // Apply navigation focus
  11689. if (focus_tab_id != 0)
  11690. if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
  11691. {
  11692. FocusWindow(tab->Window);
  11693. NavInitWindow(tab->Window, false);
  11694. }
  11695. EndTabBar();
  11696. PopID();
  11697. // Restore SkipItems flag
  11698. if (!node->IsDockSpace())
  11699. {
  11700. host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
  11701. host_window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
  11702. host_window->SkipItems = backup_skip_item;
  11703. }
  11704. }
  11705. static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
  11706. {
  11707. IM_ASSERT(node->TabBar == NULL);
  11708. node->TabBar = IM_NEW(ImGuiTabBar);
  11709. }
  11710. static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
  11711. {
  11712. if (node->TabBar == NULL)
  11713. return;
  11714. IM_DELETE(node->TabBar);
  11715. node->TabBar = NULL;
  11716. }
  11717. static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
  11718. {
  11719. if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
  11720. return false;
  11721. ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
  11722. ImGuiWindowClass* payload_class = &payload->WindowClass;
  11723. if (host_class->ClassId != payload_class->ClassId)
  11724. {
  11725. if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
  11726. return true;
  11727. if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
  11728. return true;
  11729. return false;
  11730. }
  11731. return true;
  11732. }
  11733. static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
  11734. {
  11735. if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode())
  11736. return true;
  11737. const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
  11738. for (int payload_n = 0; payload_n < payload_count; payload_n++)
  11739. {
  11740. ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
  11741. if (DockNodeIsDropAllowedOne(payload, host_window))
  11742. return true;
  11743. }
  11744. return false;
  11745. }
  11746. // window menu button == collapse button when not in a dock node.
  11747. // FIXME: This is similar to RenderWindowTitleBarContents, may want to share code.
  11748. static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos)
  11749. {
  11750. ImGuiContext& g = *GImGui;
  11751. 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);
  11752. if (out_title_rect) { *out_title_rect = r; }
  11753. ImVec2 window_menu_button_pos = r.Min;
  11754. r.Min.x += g.Style.FramePadding.x;
  11755. r.Max.x -= g.Style.FramePadding.x;
  11756. if (node->HasCloseButton)
  11757. {
  11758. r.Max.x -= g.FontSize;// +1.0f; // In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none.
  11759. }
  11760. if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
  11761. {
  11762. r.Min.x += g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a docking tab bar. Instead we adjusted RenderArrowDockMenu()
  11763. }
  11764. else if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Right)
  11765. {
  11766. r.Max.x -= g.FontSize + g.Style.FramePadding.x;
  11767. window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
  11768. }
  11769. if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
  11770. if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
  11771. }
  11772. void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
  11773. {
  11774. ImGuiContext& g = *GImGui;
  11775. const float dock_spacing = g.Style.ItemInnerSpacing.x;
  11776. const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  11777. pos_new[axis ^ 1] = pos_old[axis ^ 1];
  11778. size_new[axis ^ 1] = size_old[axis ^ 1];
  11779. // Distribute size on given axis (with a desired size or equally)
  11780. const float w_avail = size_old[axis] - dock_spacing;
  11781. if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
  11782. {
  11783. size_new[axis] = size_new_desired[axis];
  11784. size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
  11785. }
  11786. else
  11787. {
  11788. size_new[axis] = IM_FLOOR(w_avail * 0.5f);
  11789. size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
  11790. }
  11791. // Position each node
  11792. if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
  11793. {
  11794. pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
  11795. }
  11796. else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
  11797. {
  11798. pos_new[axis] = pos_old[axis];
  11799. pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
  11800. }
  11801. }
  11802. // Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
  11803. bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
  11804. {
  11805. ImGuiContext& g = *GImGui;
  11806. const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
  11807. const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
  11808. float hs_w; // Half-size, longer axis
  11809. float hs_h; // Half-size, smaller axis
  11810. ImVec2 off; // Distance from edge or center
  11811. if (outer_docking)
  11812. {
  11813. //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
  11814. //hs_h = ImFloor(hs_w * 0.15f);
  11815. //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
  11816. hs_w = ImFloor(hs_for_central_nodes * 1.50f);
  11817. hs_h = ImFloor(hs_for_central_nodes * 0.80f);
  11818. off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
  11819. }
  11820. else
  11821. {
  11822. hs_w = ImFloor(hs_for_central_nodes);
  11823. hs_h = ImFloor(hs_for_central_nodes * 0.90f);
  11824. off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
  11825. }
  11826. ImVec2 c = ImFloor(parent.GetCenter());
  11827. if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
  11828. 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); }
  11829. 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); }
  11830. 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); }
  11831. 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); }
  11832. if (test_mouse_pos == NULL)
  11833. return false;
  11834. ImRect hit_r = out_r;
  11835. if (!outer_docking)
  11836. {
  11837. // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
  11838. hit_r.Expand(ImFloor(hs_w * 0.30f));
  11839. ImVec2 mouse_delta = (*test_mouse_pos - c);
  11840. float mouse_delta_len2 = ImLengthSqr(mouse_delta);
  11841. float r_threshold_center = hs_w * 1.4f;
  11842. float r_threshold_sides = hs_w * (1.4f + 1.2f);
  11843. if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
  11844. return (dir == ImGuiDir_None);
  11845. if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
  11846. return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
  11847. }
  11848. return hit_r.Contains(*test_mouse_pos);
  11849. }
  11850. // host_node may be NULL if the window doesn't have a DockNode already.
  11851. // FIXME-DOCK: This is misnamed since it's also doing the filtering.
  11852. static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
  11853. {
  11854. ImGuiContext& g = *GImGui;
  11855. // There is an edge case when docking into a dockspace which only has inactive nodes.
  11856. // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
  11857. // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
  11858. ImGuiDockNode* root_payload_as_host = root_payload->DockNodeAsHost;
  11859. ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
  11860. if (ref_node_for_rect)
  11861. IM_ASSERT(ref_node_for_rect->IsVisible);
  11862. // Filter, figure out where we are allowed to dock
  11863. ImGuiDockNodeFlags host_node_flags = host_node ? host_node->GetMergedFlags() : 0;
  11864. data->IsCenterAvailable = true;
  11865. if (is_outer_docking)
  11866. data->IsCenterAvailable = false;
  11867. else if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDocking))
  11868. data->IsCenterAvailable = false;
  11869. else if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
  11870. data->IsCenterAvailable = false;
  11871. 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?
  11872. data->IsCenterAvailable = false;
  11873. data->IsSidesAvailable = true;
  11874. if ((host_node && (host_node_flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
  11875. data->IsSidesAvailable = false;
  11876. else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
  11877. data->IsSidesAvailable = false;
  11878. // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
  11879. data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton);
  11880. data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
  11881. data->FutureNode.Pos = host_node ? ref_node_for_rect->Pos : host_window->Pos;
  11882. data->FutureNode.Size = host_node ? ref_node_for_rect->Size : host_window->Size;
  11883. // Calculate drop shapes geometry for allowed splitting directions
  11884. IM_ASSERT(ImGuiDir_None == -1);
  11885. data->SplitNode = host_node;
  11886. data->SplitDir = ImGuiDir_None;
  11887. data->IsSplitDirExplicit = false;
  11888. if (!host_window->Collapsed)
  11889. for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
  11890. {
  11891. if (dir == ImGuiDir_None && !data->IsCenterAvailable)
  11892. continue;
  11893. if (dir != ImGuiDir_None && !data->IsSidesAvailable)
  11894. continue;
  11895. if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
  11896. {
  11897. data->SplitDir = (ImGuiDir)dir;
  11898. data->IsSplitDirExplicit = true;
  11899. }
  11900. }
  11901. // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
  11902. data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
  11903. if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
  11904. data->IsDropAllowed = false;
  11905. // Calculate split area
  11906. data->SplitRatio = 0.0f;
  11907. if (data->SplitDir != ImGuiDir_None)
  11908. {
  11909. ImGuiDir split_dir = data->SplitDir;
  11910. ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
  11911. ImVec2 pos_new, pos_old = data->FutureNode.Pos;
  11912. ImVec2 size_new, size_old = data->FutureNode.Size;
  11913. DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, root_payload->Size);
  11914. // Calculate split ratio so we can pass it down the docking request
  11915. float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
  11916. data->FutureNode.Pos = pos_new;
  11917. data->FutureNode.Size = size_new;
  11918. data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
  11919. }
  11920. }
  11921. static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
  11922. {
  11923. ImGuiContext& g = *GImGui;
  11924. IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
  11925. // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
  11926. // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
  11927. const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
  11928. // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
  11929. int overlay_draw_lists_count = 0;
  11930. ImDrawList* overlay_draw_lists[2];
  11931. overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
  11932. if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
  11933. overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
  11934. // Draw main preview rectangle
  11935. const ImU32 overlay_col_tabs = GetColorU32(ImGuiCol_TabActive);
  11936. const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
  11937. const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
  11938. const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
  11939. const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
  11940. // Display area preview
  11941. const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
  11942. if (data->IsDropAllowed)
  11943. {
  11944. ImRect overlay_rect = data->FutureNode.Rect();
  11945. if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
  11946. overlay_rect.Min.y += GetFrameHeight();
  11947. if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
  11948. for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
  11949. overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding);
  11950. }
  11951. // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
  11952. if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
  11953. {
  11954. // Compute target tab bar geometry so we can locate our preview tabs
  11955. ImRect tab_bar_rect;
  11956. DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL);
  11957. ImVec2 tab_pos = tab_bar_rect.Min;
  11958. if (host_node && host_node->TabBar)
  11959. {
  11960. if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
  11961. tab_pos.x += host_node->TabBar->OffsetMax + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
  11962. else
  11963. tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x;
  11964. }
  11965. else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
  11966. {
  11967. 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
  11968. }
  11969. // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
  11970. if (root_payload->DockNodeAsHost)
  11971. IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size == root_payload->DockNodeAsHost->TabBar->Tabs.Size);
  11972. const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs.Size : 1;
  11973. for (int payload_n = 0; payload_n < payload_count; payload_n++)
  11974. {
  11975. // Calculate the tab bounding box for each payload window
  11976. ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs[payload_n].Window : root_payload;
  11977. if (!DockNodeIsDropAllowedOne(payload, host_window))
  11978. continue;
  11979. ImVec2 tab_size = TabItemCalcSize(payload->Name, payload->HasCloseButton);
  11980. ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
  11981. tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
  11982. for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
  11983. {
  11984. ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
  11985. if (!tab_bar_rect.Contains(tab_bb))
  11986. overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
  11987. TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
  11988. TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload->Name, 0, 0);
  11989. if (!tab_bar_rect.Contains(tab_bb))
  11990. overlay_draw_lists[overlay_n]->PopClipRect();
  11991. }
  11992. }
  11993. }
  11994. // Display drop boxes
  11995. const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
  11996. for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
  11997. {
  11998. if (!data->DropRectsDraw[dir + 1].IsInverted())
  11999. {
  12000. ImRect draw_r = data->DropRectsDraw[dir + 1];
  12001. ImRect draw_r_in = draw_r;
  12002. draw_r_in.Expand(-2.0f);
  12003. ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
  12004. for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
  12005. {
  12006. ImVec2 center = ImFloor(draw_r_in.GetCenter());
  12007. overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
  12008. overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
  12009. if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
  12010. 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);
  12011. if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
  12012. 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);
  12013. }
  12014. }
  12015. // Stop after ImGuiDir_None
  12016. if ((host_node && (host_node->GetMergedFlags() & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
  12017. return;
  12018. }
  12019. }
  12020. //-----------------------------------------------------------------------------
  12021. // Docking: ImGuiDockNode Tree manipulation functions
  12022. //-----------------------------------------------------------------------------
  12023. // - DockNodeTreeSplit()
  12024. // - DockNodeTreeMerge()
  12025. // - DockNodeTreeUpdatePosSize()
  12026. // - DockNodeTreeUpdateSplitterFindTouchingNode()
  12027. // - DockNodeTreeUpdateSplitter()
  12028. // - DockNodeTreeFindFallbackLeafNode()
  12029. // - DockNodeTreeFindNodeByPos()
  12030. //-----------------------------------------------------------------------------
  12031. void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
  12032. {
  12033. ImGuiContext& g = *GImGui;
  12034. IM_ASSERT(split_axis != ImGuiAxis_None);
  12035. ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
  12036. child_0->ParentNode = parent_node;
  12037. ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
  12038. child_1->ParentNode = parent_node;
  12039. ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
  12040. DockNodeMoveChildNodes(child_inheritor, parent_node);
  12041. parent_node->ChildNodes[0] = child_0;
  12042. parent_node->ChildNodes[1] = child_1;
  12043. parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
  12044. parent_node->SplitAxis = split_axis;
  12045. parent_node->VisibleWindow = NULL;
  12046. parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
  12047. float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE);
  12048. size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
  12049. IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
  12050. child_0->SizeRef = child_1->SizeRef = parent_node->Size;
  12051. child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
  12052. child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
  12053. DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
  12054. DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
  12055. // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
  12056. child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
  12057. child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
  12058. child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12059. parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12060. if (child_inheritor->IsCentralNode())
  12061. DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
  12062. }
  12063. void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
  12064. {
  12065. // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
  12066. ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
  12067. ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
  12068. IM_ASSERT(child_0 || child_1);
  12069. IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
  12070. if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
  12071. {
  12072. IM_ASSERT(parent_node->TabBar == NULL);
  12073. IM_ASSERT(parent_node->Windows.Size == 0);
  12074. }
  12075. 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);
  12076. ImVec2 backup_last_explicit_size = parent_node->SizeRef;
  12077. DockNodeMoveChildNodes(parent_node, merge_lead_child);
  12078. if (child_0)
  12079. {
  12080. DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
  12081. DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
  12082. }
  12083. if (child_1)
  12084. {
  12085. DockNodeMoveWindows(parent_node, child_1);
  12086. DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
  12087. }
  12088. DockNodeApplyPosSizeToWindows(parent_node);
  12089. parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
  12090. parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
  12091. parent_node->SizeRef = backup_last_explicit_size;
  12092. // Flags transfer
  12093. parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
  12094. parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12095. parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
  12096. if (child_0)
  12097. {
  12098. ctx->DockContext->Nodes.SetVoidPtr(child_0->ID, NULL);
  12099. IM_DELETE(child_0);
  12100. }
  12101. if (child_1)
  12102. {
  12103. ctx->DockContext->Nodes.SetVoidPtr(child_1->ID, NULL);
  12104. IM_DELETE(child_1);
  12105. }
  12106. }
  12107. // Update Pos/Size for a node hierarchy (don't affect child Windows yet)
  12108. void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes)
  12109. {
  12110. // During the regular dock node update we write to all nodes.
  12111. // 'only_write_to_marked_nodes' is only set when turning a node visible mid-frame and we need its size right-away.
  12112. const bool write_to_node = (only_write_to_marked_nodes == false) || (node->MarkedForPosSizeWrite);
  12113. if (write_to_node)
  12114. {
  12115. node->Pos = pos;
  12116. node->Size = size;
  12117. }
  12118. if (node->IsLeafNode())
  12119. return;
  12120. ImGuiDockNode* child_0 = node->ChildNodes[0];
  12121. ImGuiDockNode* child_1 = node->ChildNodes[1];
  12122. ImVec2 child_0_pos = pos, child_1_pos = pos;
  12123. ImVec2 child_0_size = size, child_1_size = size;
  12124. if (child_0->IsVisible && child_1->IsVisible)
  12125. {
  12126. const float spacing = IMGUI_DOCK_SPLITTER_SIZE;
  12127. const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
  12128. const float size_avail = ImMax(size[axis] - spacing, 0.0f);
  12129. // Size allocation policy
  12130. // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
  12131. ImGuiContext& g = *GImGui;
  12132. const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
  12133. // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
  12134. IM_ASSERT(!(child_0->WantLockSizeOnce && child_1->WantLockSizeOnce));
  12135. if (child_0->WantLockSizeOnce)
  12136. {
  12137. child_0->WantLockSizeOnce = false;
  12138. child_0_size[axis] = child_0->SizeRef[axis] = child_0->Size[axis];
  12139. child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
  12140. IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
  12141. }
  12142. else if (child_1->WantLockSizeOnce)
  12143. {
  12144. child_1->WantLockSizeOnce = false;
  12145. child_1_size[axis] = child_1->SizeRef[axis] = child_1->Size[axis];
  12146. child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
  12147. IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
  12148. }
  12149. // 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
  12150. else if (child_1->IsCentralNode() && child_0->SizeRef[axis] != 0.0f)
  12151. {
  12152. child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
  12153. child_1_size[axis] = (size_avail - child_0_size[axis]);
  12154. }
  12155. else if (child_0->IsCentralNode() && child_1->SizeRef[axis] != 0.0f)
  12156. {
  12157. child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
  12158. child_0_size[axis] = (size_avail - child_1_size[axis]);
  12159. }
  12160. else
  12161. {
  12162. // 4) Otherwise distribute according to the relative ratio of each SizeRef value
  12163. float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
  12164. child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5F));
  12165. child_1_size[axis] = (size_avail - child_0_size[axis]);
  12166. }
  12167. child_1_pos[axis] += spacing + child_0_size[axis];
  12168. }
  12169. if (child_0->IsVisible)
  12170. DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
  12171. if (child_1->IsVisible)
  12172. DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
  12173. }
  12174. static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
  12175. {
  12176. if (node->IsLeafNode())
  12177. {
  12178. touching_nodes->push_back(node);
  12179. return;
  12180. }
  12181. if (node->ChildNodes[0]->IsVisible)
  12182. if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
  12183. DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
  12184. if (node->ChildNodes[1]->IsVisible)
  12185. if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
  12186. DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
  12187. }
  12188. void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
  12189. {
  12190. if (node->IsLeafNode())
  12191. return;
  12192. ImGuiContext& g = *GImGui;
  12193. ImGuiDockNode* child_0 = node->ChildNodes[0];
  12194. ImGuiDockNode* child_1 = node->ChildNodes[1];
  12195. if (child_0->IsVisible && child_1->IsVisible)
  12196. {
  12197. // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
  12198. const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
  12199. IM_ASSERT(axis != ImGuiAxis_None);
  12200. ImRect bb;
  12201. bb.Min = child_0->Pos;
  12202. bb.Max = child_1->Pos;
  12203. bb.Min[axis] += child_0->Size[axis];
  12204. bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
  12205. //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
  12206. if ((child_0->GetMergedFlags() | child_1->GetMergedFlags()) & ImGuiDockNodeFlags_NoResize)
  12207. {
  12208. ImGuiWindow* window = g.CurrentWindow;
  12209. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
  12210. }
  12211. else
  12212. {
  12213. //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
  12214. //bb.Max[axis] -= 1;
  12215. PushID(node->ID);
  12216. // Gather list of nodes that are touching the splitter line. Find resizing limits based on those nodes.
  12217. ImVector<ImGuiDockNode*> touching_nodes[2];
  12218. float min_size = g.Style.WindowMinSize[axis];
  12219. float resize_limits[2];
  12220. resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
  12221. resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
  12222. ImGuiID splitter_id = GetID("##Splitter");
  12223. if (g.ActiveId == splitter_id)
  12224. {
  12225. // Only process when splitter is active
  12226. DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
  12227. DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
  12228. for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
  12229. resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
  12230. for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
  12231. resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
  12232. /*
  12233. // [DEBUG] Render limits
  12234. ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport());
  12235. for (int n = 0; n < 2; n++)
  12236. if (axis == ImGuiAxis_X)
  12237. 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);
  12238. else
  12239. 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);
  12240. */
  12241. }
  12242. // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
  12243. float cur_size_0 = child_0->Size[axis];
  12244. float cur_size_1 = child_1->Size[axis];
  12245. float min_size_0 = resize_limits[0] - child_0->Pos[axis];
  12246. float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
  12247. if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER))
  12248. {
  12249. if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
  12250. {
  12251. child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
  12252. child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
  12253. child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
  12254. // Lock the size of every node that is a sibling of the node we are touching
  12255. // This might be less desirable if we can merge sibling of a same axis into the same parental level.
  12256. for (int side_n = 0; side_n < 2; side_n++)
  12257. for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
  12258. {
  12259. ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
  12260. //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport());
  12261. //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
  12262. while (touching_node->ParentNode != node)
  12263. {
  12264. if (touching_node->ParentNode->SplitAxis == axis)
  12265. {
  12266. // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
  12267. ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
  12268. node_to_preserve->WantLockSizeOnce = true;
  12269. //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
  12270. //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
  12271. }
  12272. touching_node = touching_node->ParentNode;
  12273. }
  12274. }
  12275. DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
  12276. DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
  12277. MarkIniSettingsDirty();
  12278. }
  12279. }
  12280. PopID();
  12281. }
  12282. }
  12283. if (child_0->IsVisible)
  12284. DockNodeTreeUpdateSplitter(child_0);
  12285. if (child_1->IsVisible)
  12286. DockNodeTreeUpdateSplitter(child_1);
  12287. }
  12288. ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
  12289. {
  12290. if (node->IsLeafNode())
  12291. return node;
  12292. if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
  12293. return leaf_node;
  12294. if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
  12295. return leaf_node;
  12296. return NULL;
  12297. }
  12298. ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos)
  12299. {
  12300. if (!node->IsVisible)
  12301. return NULL;
  12302. ImGuiContext& g = *GImGui;
  12303. const float dock_spacing = g.Style.ItemInnerSpacing.x;
  12304. ImRect r(node->Pos, node->Pos + node->Size);
  12305. r.Expand(dock_spacing * 0.5f);
  12306. bool inside = r.Contains(pos);
  12307. if (!inside)
  12308. return NULL;
  12309. if (node->IsLeafNode())
  12310. return node;
  12311. if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[0], pos))
  12312. return hovered_node;
  12313. if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[1], pos))
  12314. return hovered_node;
  12315. // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active)
  12316. // In this case we need to fallback into any leaf mode, possibly the central node.
  12317. if (node->IsDockSpace() && node->IsRootNode())
  12318. {
  12319. if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
  12320. return node->CentralNode;
  12321. return DockNodeTreeFindFallbackLeafNode(node);
  12322. }
  12323. return NULL;
  12324. }
  12325. //-----------------------------------------------------------------------------
  12326. // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
  12327. //-----------------------------------------------------------------------------
  12328. // - SetWindowDock() [Internal]
  12329. // - DockSpace()
  12330. // - DockSpaceOverViewport()
  12331. //-----------------------------------------------------------------------------
  12332. // [Internal] Called via SetNextWindowDockID()
  12333. void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
  12334. {
  12335. // Test condition (NB: bit 0 is always true) and clear flags for next time
  12336. if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
  12337. return;
  12338. window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  12339. if (window->DockId == dock_id)
  12340. return;
  12341. // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
  12342. ImGuiContext* ctx = GImGui;
  12343. if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
  12344. if (new_node->IsSplitNode())
  12345. {
  12346. // Policy: Find central node or latest focused node. We first move back to our root node.
  12347. new_node = DockNodeGetRootNode(new_node);
  12348. if (new_node->CentralNode)
  12349. {
  12350. IM_ASSERT(new_node->CentralNode->IsCentralNode());
  12351. dock_id = new_node->CentralNode->ID;
  12352. }
  12353. else
  12354. {
  12355. dock_id = new_node->LastFocusedNodeId;
  12356. }
  12357. }
  12358. if (window->DockId == dock_id)
  12359. return;
  12360. if (window->DockNode)
  12361. DockNodeRemoveWindow(window->DockNode, window, 0);
  12362. window->DockId = dock_id;
  12363. }
  12364. // Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
  12365. // The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
  12366. // DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
  12367. void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
  12368. {
  12369. ImGuiContext* ctx = GImGui;
  12370. ImGuiContext& g = *ctx;
  12371. ImGuiWindow* window = GetCurrentWindow();
  12372. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  12373. return;
  12374. // Early out if parent window is hidden/collapsed
  12375. // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
  12376. // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
  12377. if (window->SkipItems)
  12378. flags |= ImGuiDockNodeFlags_KeepAliveOnly;
  12379. IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
  12380. ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
  12381. if (!node)
  12382. {
  12383. IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X created\n", id);
  12384. node = DockContextAddNode(ctx, id);
  12385. node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  12386. }
  12387. if (window_class && window_class->ClassId != node->WindowClass.ClassId)
  12388. IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
  12389. node->SharedFlags = flags;
  12390. node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
  12391. // When a DockSpace transitioned form implicit to explicit this may be called a second time
  12392. // 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.
  12393. if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
  12394. {
  12395. IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
  12396. node->LocalFlags |= ImGuiDockNodeFlags_DockSpace;
  12397. return;
  12398. }
  12399. node->LocalFlags |= ImGuiDockNodeFlags_DockSpace;
  12400. // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
  12401. if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
  12402. {
  12403. node->LastFrameAlive = g.FrameCount;
  12404. return;
  12405. }
  12406. const ImVec2 content_avail = GetContentRegionAvail();
  12407. ImVec2 size = ImFloor(size_arg);
  12408. if (size.x <= 0.0f)
  12409. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  12410. if (size.y <= 0.0f)
  12411. size.y = ImMax(content_avail.y + size.y, 4.0f);
  12412. IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
  12413. node->Pos = window->DC.CursorPos;
  12414. node->Size = node->SizeRef = size;
  12415. SetNextWindowPos(node->Pos);
  12416. SetNextWindowSize(node->Size);
  12417. g.NextWindowData.PosUndock = false;
  12418. // FIXME-DOCK Why do we need a child window to host a dockspace, could we host it in the existing window?
  12419. ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
  12420. window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
  12421. window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
  12422. char title[256];
  12423. ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
  12424. if (node->Windows.Size > 0 || node->IsSplitNode())
  12425. PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0));
  12426. PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
  12427. Begin(title, NULL, window_flags);
  12428. PopStyleVar();
  12429. if (node->Windows.Size > 0 || node->IsSplitNode())
  12430. PopStyleColor();
  12431. ImGuiWindow* host_window = g.CurrentWindow;
  12432. host_window->DockNodeAsHost = node;
  12433. host_window->ChildId = window->GetID(title);
  12434. node->HostWindow = host_window;
  12435. node->OnlyNodeWithWindows = NULL;
  12436. IM_ASSERT(node->IsRootNode());
  12437. DockNodeUpdate(node);
  12438. g.WithinEndChild = true;
  12439. End();
  12440. g.WithinEndChild = false;
  12441. }
  12442. // Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
  12443. // The limitation with this call is that your window won't have a menu bar.
  12444. // 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.
  12445. // 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.
  12446. ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
  12447. {
  12448. if (viewport == NULL)
  12449. viewport = GetMainViewport();
  12450. SetNextWindowPos(viewport->GetWorkPos());
  12451. SetNextWindowSize(viewport->GetWorkSize());
  12452. SetNextWindowViewport(viewport->ID);
  12453. ImGuiWindowFlags host_window_flags = 0;
  12454. host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
  12455. host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
  12456. if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
  12457. host_window_flags |= ImGuiWindowFlags_NoBackground;
  12458. char label[32];
  12459. ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
  12460. PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  12461. PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
  12462. PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
  12463. Begin(label, NULL, host_window_flags);
  12464. PopStyleVar(3);
  12465. ImGuiID dockspace_id = GetID("DockSpace");
  12466. DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
  12467. End();
  12468. return dockspace_id;
  12469. }
  12470. //-----------------------------------------------------------------------------
  12471. // Docking: Builder Functions
  12472. //-----------------------------------------------------------------------------
  12473. // Very early end-user API to manipulate dock nodes.
  12474. // Only available in imgui_internal.h. Expect this API to change/break!
  12475. // It is expected that those functions are all called _before_ the dockspace node submission.
  12476. //-----------------------------------------------------------------------------
  12477. // - DockBuilderDockWindow()
  12478. // - DockBuilderGetNode()
  12479. // - DockBuilderSetNodePos()
  12480. // - DockBuilderSetNodeSize()
  12481. // - DockBuilderAddNode()
  12482. // - DockBuilderRemoveNode()
  12483. // - DockBuilderRemoveNodeChildNodes()
  12484. // - DockBuilderRemoveNodeDockedWindows()
  12485. // - DockBuilderSplitNode()
  12486. // - DockBuilderCopyNodeRec()
  12487. // - DockBuilderCopyNode()
  12488. // - DockBuilderCopyWindowSettings()
  12489. // - DockBuilderCopyDockSpace()
  12490. // - DockBuilderFinish()
  12491. //-----------------------------------------------------------------------------
  12492. void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
  12493. {
  12494. // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
  12495. ImGuiID window_id = ImHashStr(window_name);
  12496. if (ImGuiWindow* window = FindWindowByID(window_id))
  12497. {
  12498. // Apply to created window
  12499. SetWindowDock(window, node_id, ImGuiCond_Always);
  12500. window->DockOrder = -1;
  12501. }
  12502. else
  12503. {
  12504. // Apply to settings
  12505. ImGuiWindowSettings* settings = FindWindowSettings(window_id);
  12506. if (settings == NULL)
  12507. settings = CreateNewWindowSettings(window_name);
  12508. settings->DockId = node_id;
  12509. settings->DockOrder = -1;
  12510. }
  12511. }
  12512. ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
  12513. {
  12514. ImGuiContext* ctx = GImGui;
  12515. return DockContextFindNodeByID(ctx, node_id);
  12516. }
  12517. void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
  12518. {
  12519. ImGuiContext* ctx = GImGui;
  12520. ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
  12521. if (node == NULL)
  12522. return;
  12523. node->Pos = pos;
  12524. node->AuthorityForPos = ImGuiDataAuthority_DockNode;
  12525. }
  12526. void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
  12527. {
  12528. ImGuiContext* ctx = GImGui;
  12529. ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
  12530. if (node == NULL)
  12531. return;
  12532. IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
  12533. node->Size = node->SizeRef = size;
  12534. node->AuthorityForSize = ImGuiDataAuthority_DockNode;
  12535. }
  12536. // Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
  12537. // - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
  12538. // - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
  12539. // - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
  12540. // For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
  12541. // - Use (id == 0) to let the system allocate a node identifier.
  12542. ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
  12543. {
  12544. ImGuiContext* ctx = GImGui;
  12545. ImGuiDockNode* node = NULL;
  12546. if (flags & ImGuiDockNodeFlags_DockSpace)
  12547. {
  12548. DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
  12549. node = DockContextFindNodeByID(ctx, id);
  12550. }
  12551. else
  12552. {
  12553. if (id != 0)
  12554. node = DockContextFindNodeByID(ctx, id);
  12555. if (!node)
  12556. node = DockContextAddNode(ctx, id);
  12557. node->LocalFlags = flags;
  12558. }
  12559. node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame.
  12560. return node->ID;
  12561. }
  12562. void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
  12563. {
  12564. ImGuiContext* ctx = GImGui;
  12565. ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
  12566. if (node == NULL)
  12567. return;
  12568. DockBuilderRemoveNodeDockedWindows(node_id, true);
  12569. DockBuilderRemoveNodeChildNodes(node_id);
  12570. if (node->IsCentralNode() && node->ParentNode)
  12571. node->ParentNode->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  12572. DockContextRemoveNode(ctx, node, true);
  12573. }
  12574. void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
  12575. {
  12576. ImGuiContext* ctx = GImGui;
  12577. ImGuiDockContext* dc = ctx->DockContext;
  12578. ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
  12579. if (root_id && root_node == NULL)
  12580. return;
  12581. bool has_central_node = false;
  12582. ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
  12583. ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
  12584. // Process active windows
  12585. ImVector<ImGuiDockNode*> nodes_to_remove;
  12586. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  12587. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  12588. {
  12589. bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
  12590. if (want_removal)
  12591. {
  12592. if (node->IsCentralNode())
  12593. has_central_node = true;
  12594. if (root_id != 0)
  12595. DockContextQueueNotifyRemovedNode(ctx, node);
  12596. if (root_node)
  12597. DockNodeMoveWindows(root_node, node);
  12598. nodes_to_remove.push_back(node);
  12599. }
  12600. }
  12601. // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
  12602. // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
  12603. if (root_node)
  12604. {
  12605. root_node->AuthorityForPos = backup_root_node_authority_for_pos;
  12606. root_node->AuthorityForSize = backup_root_node_authority_for_size;
  12607. }
  12608. // Apply to settings
  12609. for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
  12610. if (ImGuiID window_settings_dock_id = settings->DockId)
  12611. for (int n = 0; n < nodes_to_remove.Size; n++)
  12612. if (nodes_to_remove[n]->ID == window_settings_dock_id)
  12613. {
  12614. settings->DockId = root_id;
  12615. break;
  12616. }
  12617. // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
  12618. if (nodes_to_remove.Size > 1)
  12619. ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
  12620. for (int n = 0; n < nodes_to_remove.Size; n++)
  12621. DockContextRemoveNode(ctx, nodes_to_remove[n], false);
  12622. if (root_id == 0)
  12623. {
  12624. dc->Nodes.Clear();
  12625. dc->Requests.clear();
  12626. }
  12627. else if (has_central_node)
  12628. {
  12629. root_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode;
  12630. root_node->CentralNode = root_node;
  12631. }
  12632. }
  12633. void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persistent_docking_references)
  12634. {
  12635. // Clear references in settings
  12636. ImGuiContext* ctx = GImGui;
  12637. ImGuiContext& g = *ctx;
  12638. if (clear_persistent_docking_references)
  12639. {
  12640. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  12641. {
  12642. bool want_removal = (root_id == 0) || (settings->DockId == root_id);
  12643. if (!want_removal && settings->DockId != 0)
  12644. if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
  12645. if (DockNodeGetRootNode(node)->ID == root_id)
  12646. want_removal = true;
  12647. if (want_removal)
  12648. settings->DockId = 0;
  12649. }
  12650. }
  12651. // Clear references in windows
  12652. for (int n = 0; n < g.Windows.Size; n++)
  12653. {
  12654. ImGuiWindow* window = g.Windows[n];
  12655. bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
  12656. if (want_removal)
  12657. {
  12658. const ImGuiID backup_dock_id = window->DockId;
  12659. DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_references);
  12660. if (!clear_persistent_docking_references)
  12661. IM_ASSERT(window->DockId == backup_dock_id);
  12662. }
  12663. }
  12664. }
  12665. // 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.
  12666. // Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
  12667. // FIXME-DOCK: We are not exposing nor using split_outer.
  12668. 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)
  12669. {
  12670. ImGuiContext* ctx = GImGui;
  12671. IM_ASSERT(split_dir != ImGuiDir_None);
  12672. IMGUI_DEBUG_LOG_DOCKING("DockBuilderSplitNode node 0x%08X, split_dir %d\n", id, split_dir);
  12673. ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
  12674. if (node == NULL)
  12675. {
  12676. IM_ASSERT(node != NULL);
  12677. return 0;
  12678. }
  12679. IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
  12680. ImGuiDockRequest req;
  12681. req.Type = ImGuiDockRequestType_Split;
  12682. req.DockTargetWindow = NULL;
  12683. req.DockTargetNode = node;
  12684. req.DockPayload = NULL;
  12685. req.DockSplitDir = split_dir;
  12686. 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);
  12687. req.DockSplitOuter = false;
  12688. DockContextProcessDock(ctx, &req);
  12689. ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
  12690. ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
  12691. if (out_id_at_dir)
  12692. *out_id_at_dir = id_at_dir;
  12693. if (out_id_at_opposite_dir)
  12694. *out_id_at_opposite_dir = id_at_opposite_dir;
  12695. return id_at_dir;
  12696. }
  12697. static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
  12698. {
  12699. ImGuiContext* ctx = GImGui;
  12700. ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx, dst_node_id_if_known);
  12701. dst_node->SharedFlags = src_node->SharedFlags;
  12702. dst_node->LocalFlags = src_node->LocalFlags;
  12703. dst_node->Pos = src_node->Pos;
  12704. dst_node->Size = src_node->Size;
  12705. dst_node->SizeRef = src_node->SizeRef;
  12706. dst_node->SplitAxis = src_node->SplitAxis;
  12707. out_node_remap_pairs->push_back(src_node->ID);
  12708. out_node_remap_pairs->push_back(dst_node->ID);
  12709. for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
  12710. if (src_node->ChildNodes[child_n])
  12711. {
  12712. dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
  12713. dst_node->ChildNodes[child_n]->ParentNode = dst_node;
  12714. }
  12715. IMGUI_DEBUG_LOG_DOCKING("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
  12716. return dst_node;
  12717. }
  12718. void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
  12719. {
  12720. ImGuiContext* ctx = GImGui;
  12721. IM_ASSERT(src_node_id != 0);
  12722. IM_ASSERT(dst_node_id != 0);
  12723. IM_ASSERT(out_node_remap_pairs != NULL);
  12724. ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
  12725. IM_ASSERT(src_node != NULL);
  12726. out_node_remap_pairs->clear();
  12727. DockBuilderRemoveNode(dst_node_id);
  12728. DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
  12729. IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
  12730. }
  12731. void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
  12732. {
  12733. ImGuiWindow* src_window = FindWindowByName(src_name);
  12734. if (src_window == NULL)
  12735. return;
  12736. if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
  12737. {
  12738. dst_window->Pos = src_window->Pos;
  12739. dst_window->Size = src_window->Size;
  12740. dst_window->SizeFull = src_window->SizeFull;
  12741. dst_window->Collapsed = src_window->Collapsed;
  12742. }
  12743. else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name))
  12744. {
  12745. ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
  12746. if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
  12747. {
  12748. dst_settings->ViewportPos = window_pos_2ih;
  12749. dst_settings->ViewportId = src_window->ViewportId;
  12750. dst_settings->Pos = ImVec2ih(0, 0);
  12751. }
  12752. else
  12753. {
  12754. dst_settings->Pos = window_pos_2ih;
  12755. }
  12756. dst_settings->Size = ImVec2ih(src_window->SizeFull);
  12757. dst_settings->Collapsed = src_window->Collapsed;
  12758. }
  12759. }
  12760. // FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
  12761. void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
  12762. {
  12763. IM_ASSERT(src_dockspace_id != 0);
  12764. IM_ASSERT(dst_dockspace_id != 0);
  12765. IM_ASSERT(in_window_remap_pairs != NULL);
  12766. IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
  12767. // Duplicate entire dock
  12768. // 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,
  12769. // whereas we could attempt to at least keep them together in a new, same floating node.
  12770. ImVector<ImGuiID> node_remap_pairs;
  12771. DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
  12772. // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
  12773. // (The windows associated to src_dockspace_id are staying in place)
  12774. ImVector<ImGuiID> src_windows;
  12775. for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
  12776. {
  12777. const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
  12778. const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
  12779. ImGuiID src_window_id = ImHashStr(src_window_name);
  12780. src_windows.push_back(src_window_id);
  12781. // Search in the remapping tables
  12782. ImGuiID src_dock_id = 0;
  12783. if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
  12784. src_dock_id = src_window->DockId;
  12785. else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id))
  12786. src_dock_id = src_window_settings->DockId;
  12787. ImGuiID dst_dock_id = 0;
  12788. for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
  12789. if (node_remap_pairs[dock_remap_n] == src_dock_id)
  12790. {
  12791. dst_dock_id = node_remap_pairs[dock_remap_n + 1];
  12792. //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
  12793. break;
  12794. }
  12795. if (dst_dock_id != 0)
  12796. {
  12797. // Docked windows gets redocked into the new node hierarchy.
  12798. 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);
  12799. DockBuilderDockWindow(dst_window_name, dst_dock_id);
  12800. }
  12801. else
  12802. {
  12803. // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
  12804. // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
  12805. IMGUI_DEBUG_LOG_DOCKING("Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
  12806. DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
  12807. }
  12808. }
  12809. // 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")
  12810. // Find those windows and move to them to the cloned dock node. This may be optional?
  12811. for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
  12812. if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
  12813. {
  12814. ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
  12815. ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
  12816. for (int window_n = 0; window_n < node->Windows.Size; window_n++)
  12817. {
  12818. ImGuiWindow* window = node->Windows[window_n];
  12819. if (src_windows.contains(window->ID))
  12820. continue;
  12821. // Docked windows gets redocked into the new node hierarchy.
  12822. IMGUI_DEBUG_LOG_DOCKING("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
  12823. DockBuilderDockWindow(window->Name, dst_dock_id);
  12824. }
  12825. }
  12826. }
  12827. void ImGui::DockBuilderFinish(ImGuiID root_id)
  12828. {
  12829. ImGuiContext* ctx = GImGui;
  12830. //DockContextRebuild(ctx);
  12831. DockContextBuildAddWindowsToNodes(ctx, root_id);
  12832. }
  12833. //-----------------------------------------------------------------------------
  12834. // Docking: Begin/End Support Functions (called from Begin/End)
  12835. //-----------------------------------------------------------------------------
  12836. // - GetWindowAlwaysWantOwnTabBar()
  12837. // - DockContextBindNodeToWindow()
  12838. // - BeginDocked()
  12839. // - BeginDockableDragDropSource()
  12840. // - BeginDockableDragDropTarget()
  12841. //-----------------------------------------------------------------------------
  12842. bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
  12843. {
  12844. ImGuiContext& g = *GImGui;
  12845. if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
  12846. if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
  12847. if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
  12848. return true;
  12849. return false;
  12850. }
  12851. static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
  12852. {
  12853. ImGuiContext& g = *ctx;
  12854. ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
  12855. IM_ASSERT(window->DockNode == NULL);
  12856. // We should not be docking into a split node (SetWindowDock should avoid this)
  12857. if (node && node->IsSplitNode())
  12858. {
  12859. DockContextProcessUndockWindow(ctx, window);
  12860. return NULL;
  12861. }
  12862. // Create node
  12863. if (node == NULL)
  12864. {
  12865. node = DockContextAddNode(ctx, window->DockId);
  12866. node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
  12867. node->LastFrameAlive = g.FrameCount;
  12868. }
  12869. // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
  12870. // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
  12871. // 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.
  12872. // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
  12873. if (!node->IsVisible)
  12874. {
  12875. ImGuiDockNode* ancestor_node = node;
  12876. while (!ancestor_node->IsVisible)
  12877. {
  12878. ancestor_node->IsVisible = true;
  12879. ancestor_node->MarkedForPosSizeWrite = true;
  12880. if (ancestor_node->ParentNode)
  12881. ancestor_node = ancestor_node->ParentNode;
  12882. }
  12883. IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
  12884. DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, true);
  12885. }
  12886. // Add window to node
  12887. DockNodeAddWindow(node, window, true);
  12888. IM_ASSERT(node == window->DockNode);
  12889. return node;
  12890. }
  12891. void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
  12892. {
  12893. ImGuiContext* ctx = GImGui;
  12894. ImGuiContext& g = *ctx;
  12895. const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
  12896. if (auto_dock_node)
  12897. {
  12898. if (window->DockId == 0)
  12899. {
  12900. IM_ASSERT(window->DockNode == NULL);
  12901. window->DockId = DockContextGenNodeID(ctx);
  12902. }
  12903. }
  12904. else
  12905. {
  12906. // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
  12907. bool want_undock = false;
  12908. want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
  12909. want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
  12910. if (want_undock)
  12911. {
  12912. DockContextProcessUndockWindow(ctx, window);
  12913. return;
  12914. }
  12915. }
  12916. // Bind to our dock node
  12917. ImGuiDockNode* node = window->DockNode;
  12918. if (node != NULL)
  12919. IM_ASSERT(window->DockId == node->ID);
  12920. if (window->DockId != 0 && node == NULL)
  12921. {
  12922. node = DockContextBindNodeToWindow(ctx, window);
  12923. if (node == NULL)
  12924. return;
  12925. }
  12926. #if 0
  12927. // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
  12928. if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
  12929. {
  12930. DockContextProcessUndockWindow(ctx, window);
  12931. return;
  12932. }
  12933. #endif
  12934. // Undock if our dockspace node disappeared
  12935. // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
  12936. if (node->LastFrameAlive < g.FrameCount)
  12937. {
  12938. // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextUpdateDocking()
  12939. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  12940. if (root_node->LastFrameAlive < g.FrameCount)
  12941. {
  12942. DockContextProcessUndockWindow(ctx, window);
  12943. }
  12944. else
  12945. {
  12946. window->DockIsActive = true;
  12947. window->DockTabIsVisible = false;
  12948. }
  12949. return;
  12950. }
  12951. // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
  12952. // and never create neither a host window neither a tab bar.
  12953. // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
  12954. if (node->HostWindow == NULL)
  12955. {
  12956. window->DockIsActive = (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing);
  12957. window->DockTabIsVisible = false;
  12958. return;
  12959. }
  12960. // We can have zero-sized nodes (e.g. children of a small-size dockspace)
  12961. IM_ASSERT(node->HostWindow);
  12962. IM_ASSERT(node->IsLeafNode());
  12963. IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
  12964. node->State = ImGuiDockNodeState_HostWindowVisible;
  12965. // Undock if we are submitted earlier than the host window
  12966. if (window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
  12967. {
  12968. DockContextProcessUndockWindow(ctx, window);
  12969. return;
  12970. }
  12971. // Position/Size window
  12972. SetNextWindowPos(node->Pos);
  12973. SetNextWindowSize(node->Size);
  12974. g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
  12975. window->DockIsActive = true;
  12976. window->DockTabIsVisible = false;
  12977. if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
  12978. return;
  12979. // When the window is selected we mark it as visible.
  12980. if (node->VisibleWindow == window)
  12981. window->DockTabIsVisible = true;
  12982. // Update window flag
  12983. IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
  12984. window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
  12985. if (node->IsHiddenTabBar() || node->IsNoTabBar())
  12986. window->Flags |= ImGuiWindowFlags_NoTitleBar;
  12987. else
  12988. 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!
  12989. // Save new dock order only if the tab bar has been visible once.
  12990. // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
  12991. if (node->TabBar && node->TabBar->CurrFrameVisible != -1)
  12992. window->DockOrder = (short)DockNodeGetTabOrder(window);
  12993. if ((node->WantCloseAll || node->WantCloseTabId == window->ID) && p_open != NULL)
  12994. *p_open = false;
  12995. // Update ChildId to allow returning from Child to Parent with Escape
  12996. ImGuiWindow* parent_window = window->DockNode->HostWindow;
  12997. window->ChildId = parent_window->GetID(window->Name);
  12998. }
  12999. void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
  13000. {
  13001. ImGuiContext& g = *GImGui;
  13002. IM_ASSERT(g.ActiveId == window->MoveId);
  13003. IM_ASSERT(g.MovingWindow == window);
  13004. window->DC.LastItemId = window->MoveId;
  13005. window = window->RootWindow;
  13006. IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
  13007. bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset);
  13008. if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
  13009. {
  13010. SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
  13011. EndDragDropSource();
  13012. }
  13013. }
  13014. void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
  13015. {
  13016. ImGuiContext* ctx = GImGui;
  13017. ImGuiContext& g = *ctx;
  13018. //IM_ASSERT(window->RootWindow == window); // May also be a DockSpace
  13019. IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
  13020. if (!g.DragDropActive)
  13021. return;
  13022. if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
  13023. return;
  13024. // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
  13025. // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
  13026. const ImGuiPayload* payload = &g.DragDropPayload;
  13027. if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
  13028. {
  13029. EndDragDropTarget();
  13030. return;
  13031. }
  13032. ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
  13033. if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
  13034. {
  13035. // Select target node
  13036. ImGuiDockNode* node = NULL;
  13037. bool allow_null_target_node = false;
  13038. if (window->DockNodeAsHost)
  13039. node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
  13040. else if (window->DockNode) // && window->DockIsActive)
  13041. node = window->DockNode;
  13042. else
  13043. allow_null_target_node = true; // Dock into a regular window
  13044. 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()));
  13045. const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
  13046. // Preview docking request and find out split direction/ratio
  13047. //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.
  13048. const bool do_preview = payload->IsPreview() || payload->IsDelivery();
  13049. if (do_preview && (node != NULL || allow_null_target_node))
  13050. {
  13051. ImGuiDockPreviewData split_inner;
  13052. ImGuiDockPreviewData split_outer;
  13053. ImGuiDockPreviewData* split_data = &split_inner;
  13054. if (node && (node->ParentNode || node->IsCentralNode()))
  13055. if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
  13056. {
  13057. DockNodePreviewDockSetup(window, root_node, payload_window, &split_outer, is_explicit_target, true);
  13058. if (split_outer.IsSplitDirExplicit)
  13059. split_data = &split_outer;
  13060. }
  13061. DockNodePreviewDockSetup(window, node, payload_window, &split_inner, is_explicit_target, false);
  13062. if (split_data == &split_outer)
  13063. split_inner.IsDropAllowed = false;
  13064. // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
  13065. DockNodePreviewDockRender(window, node, payload_window, &split_inner);
  13066. DockNodePreviewDockRender(window, node, payload_window, &split_outer);
  13067. // Queue docking request
  13068. if (split_data->IsDropAllowed && payload->IsDelivery())
  13069. DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
  13070. }
  13071. }
  13072. EndDragDropTarget();
  13073. }
  13074. //-----------------------------------------------------------------------------
  13075. // Docking: Settings
  13076. //-----------------------------------------------------------------------------
  13077. // - DockSettingsRenameNodeReferences()
  13078. // - DockSettingsRemoveNodeReferences()
  13079. // - DockSettingsFindNodeSettings()
  13080. // - DockSettingsHandler_ReadOpen()
  13081. // - DockSettingsHandler_ReadLine()
  13082. // - DockSettingsHandler_DockNodeToSettings()
  13083. // - DockSettingsHandler_WriteAll()
  13084. //-----------------------------------------------------------------------------
  13085. static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
  13086. {
  13087. ImGuiContext& g = *GImGui;
  13088. IMGUI_DEBUG_LOG_DOCKING("DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
  13089. for (int window_n = 0; window_n < g.Windows.Size; window_n++)
  13090. {
  13091. ImGuiWindow* window = g.Windows[window_n];
  13092. if (window->DockId == old_node_id && window->DockNode == NULL)
  13093. window->DockId = new_node_id;
  13094. }
  13095. //// FIXME-OPT: We could remove this loop by storing the index in the map
  13096. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  13097. if (settings->DockId == old_node_id)
  13098. settings->DockId = new_node_id;
  13099. }
  13100. // Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
  13101. static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
  13102. {
  13103. ImGuiContext& g = *GImGui;
  13104. int found = 0;
  13105. //// FIXME-OPT: We could remove this loop by storing the index in the map
  13106. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  13107. for (int node_n = 0; node_n < node_ids_count; node_n++)
  13108. if (settings->DockId == node_ids[node_n])
  13109. {
  13110. settings->DockId = 0;
  13111. settings->DockOrder = -1;
  13112. if (++found < node_ids_count)
  13113. break;
  13114. return;
  13115. }
  13116. }
  13117. static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
  13118. {
  13119. // FIXME-OPT
  13120. ImGuiDockContext* dc = ctx->DockContext;
  13121. for (int n = 0; n < dc->SettingsNodes.Size; n++)
  13122. if (dc->SettingsNodes[n].ID == id)
  13123. return &dc->SettingsNodes[n];
  13124. return NULL;
  13125. }
  13126. static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  13127. {
  13128. if (strcmp(name, "Data") != 0)
  13129. return NULL;
  13130. return (void*)1;
  13131. }
  13132. static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
  13133. {
  13134. char c = 0;
  13135. int x = 0, y = 0;
  13136. int r = 0;
  13137. // Parsing, e.g.
  13138. // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
  13139. // " DockNode ID=0x00000002 Parent=0x00000001 "
  13140. // Important: this code expect currently fields in a fixed order.
  13141. ImGuiDockNodeSettings node;
  13142. line = ImStrSkipBlank(line);
  13143. if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); }
  13144. else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
  13145. else return;
  13146. if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
  13147. if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; }
  13148. if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
  13149. if (node.ParentNodeId == 0)
  13150. {
  13151. if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
  13152. if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
  13153. }
  13154. else
  13155. {
  13156. if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
  13157. }
  13158. 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; }
  13159. if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
  13160. if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
  13161. if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
  13162. if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
  13163. if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
  13164. if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
  13165. if (sscanf(line, " Selected=0x%08X%n", &node.SelectedWindowId,&r) == 1) { line += r; }
  13166. ImGuiDockContext* dc = ctx->DockContext;
  13167. if (node.ParentNodeId != 0)
  13168. if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
  13169. node.Depth = parent_settings->Depth + 1;
  13170. dc->SettingsNodes.push_back(node);
  13171. }
  13172. static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
  13173. {
  13174. ImGuiDockNodeSettings node_settings;
  13175. IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
  13176. node_settings.ID = node->ID;
  13177. node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
  13178. node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
  13179. node_settings.SelectedWindowId = node->SelectedTabId;
  13180. node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
  13181. node_settings.Depth = (char)depth;
  13182. node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
  13183. node_settings.Pos = ImVec2ih(node->Pos);
  13184. node_settings.Size = ImVec2ih(node->Size);
  13185. node_settings.SizeRef = ImVec2ih(node->SizeRef);
  13186. dc->SettingsNodes.push_back(node_settings);
  13187. if (node->ChildNodes[0])
  13188. DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
  13189. if (node->ChildNodes[1])
  13190. DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
  13191. }
  13192. static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  13193. {
  13194. ImGuiContext& g = *ctx;
  13195. ImGuiDockContext* dc = g.DockContext;
  13196. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
  13197. return;
  13198. // Gather settings data
  13199. // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
  13200. dc->SettingsNodes.resize(0);
  13201. dc->SettingsNodes.reserve(dc->Nodes.Data.Size);
  13202. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  13203. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  13204. if (node->IsRootNode())
  13205. DockSettingsHandler_DockNodeToSettings(dc, node, 0);
  13206. int max_depth = 0;
  13207. for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++)
  13208. max_depth = ImMax((int)dc->SettingsNodes[node_n].Depth, max_depth);
  13209. // Write to text buffer
  13210. buf->appendf("[%s][Data]\n", handler->TypeName);
  13211. for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++)
  13212. {
  13213. const int line_start_pos = buf->size(); (void)line_start_pos;
  13214. const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n];
  13215. 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
  13216. buf->appendf(" ID=0x%08X", node_settings->ID);
  13217. if (node_settings->ParentNodeId)
  13218. {
  13219. buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
  13220. }
  13221. else
  13222. {
  13223. if (node_settings->ParentWindowId)
  13224. buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
  13225. buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
  13226. }
  13227. if (node_settings->SplitAxis != ImGuiAxis_None)
  13228. buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
  13229. if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
  13230. buf->appendf(" NoResize=1");
  13231. if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
  13232. buf->appendf(" CentralNode=1");
  13233. if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
  13234. buf->appendf(" NoTabBar=1");
  13235. if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
  13236. buf->appendf(" HiddenTabBar=1");
  13237. if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
  13238. buf->appendf(" NoWindowMenuButton=1");
  13239. if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
  13240. buf->appendf(" NoCloseButton=1");
  13241. if (node_settings->SelectedWindowId)
  13242. buf->appendf(" Selected=0x%08X", node_settings->SelectedWindowId);
  13243. #if IMGUI_DEBUG_INI_SETTINGS
  13244. // [DEBUG] Include comments in the .ini file to ease debugging
  13245. if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
  13246. {
  13247. buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything
  13248. if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
  13249. buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
  13250. // Iterate settings so we can give info about windows that didn't exist during the session.
  13251. int contains_window = 0;
  13252. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  13253. if (settings->DockId == node_settings->ID)
  13254. {
  13255. if (contains_window++ == 0)
  13256. buf->appendf(" ; contains ");
  13257. buf->appendf("'%s' ", settings->GetName());
  13258. }
  13259. }
  13260. #endif
  13261. buf->appendf("\n");
  13262. }
  13263. buf->appendf("\n");
  13264. }
  13265. //-----------------------------------------------------------------------------
  13266. // [SECTION] PLATFORM DEPENDENT HELPERS
  13267. //-----------------------------------------------------------------------------
  13268. #if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
  13269. #ifndef WIN32_LEAN_AND_MEAN
  13270. #define WIN32_LEAN_AND_MEAN
  13271. #endif
  13272. #ifndef __MINGW32__
  13273. #include <Windows.h>
  13274. #else
  13275. #include <windows.h>
  13276. #endif
  13277. #include <stringapiset.h>
  13278. #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have Win32 functions
  13279. #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
  13280. #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
  13281. #endif
  13282. #elif defined(__APPLE__)
  13283. #include <TargetConditionals.h>
  13284. #endif
  13285. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
  13286. #ifdef _MSC_VER
  13287. #pragma comment(lib, "user32")
  13288. #pragma comment(lib, "kernel32")
  13289. #endif
  13290. // Win32 clipboard implementation
  13291. static const char* GetClipboardTextFn_DefaultImpl(void*)
  13292. {
  13293. static ImVector<char> buf_local;
  13294. buf_local.clear();
  13295. if (!::OpenClipboard(NULL))
  13296. return NULL;
  13297. HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
  13298. if (wbuf_handle == NULL)
  13299. {
  13300. ::CloseClipboard();
  13301. return NULL;
  13302. }
  13303. if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
  13304. {
  13305. int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
  13306. buf_local.resize(buf_len);
  13307. ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, buf_local.Data, buf_len, NULL, NULL);
  13308. }
  13309. ::GlobalUnlock(wbuf_handle);
  13310. ::CloseClipboard();
  13311. return buf_local.Data;
  13312. }
  13313. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  13314. {
  13315. if (!::OpenClipboard(NULL))
  13316. return;
  13317. const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
  13318. HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
  13319. if (wbuf_handle == NULL)
  13320. {
  13321. ::CloseClipboard();
  13322. return;
  13323. }
  13324. WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
  13325. ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
  13326. ::GlobalUnlock(wbuf_handle);
  13327. ::EmptyClipboard();
  13328. if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
  13329. ::GlobalFree(wbuf_handle);
  13330. ::CloseClipboard();
  13331. }
  13332. #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
  13333. #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
  13334. static PasteboardRef main_clipboard = 0;
  13335. // OSX clipboard implementation
  13336. // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
  13337. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  13338. {
  13339. if (!main_clipboard)
  13340. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  13341. PasteboardClear(main_clipboard);
  13342. CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
  13343. if (cf_data)
  13344. {
  13345. PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
  13346. CFRelease(cf_data);
  13347. }
  13348. }
  13349. static const char* GetClipboardTextFn_DefaultImpl(void*)
  13350. {
  13351. if (!main_clipboard)
  13352. PasteboardCreate(kPasteboardClipboard, &main_clipboard);
  13353. PasteboardSynchronize(main_clipboard);
  13354. ItemCount item_count = 0;
  13355. PasteboardGetItemCount(main_clipboard, &item_count);
  13356. for (ItemCount i = 0; i < item_count; i++)
  13357. {
  13358. PasteboardItemID item_id = 0;
  13359. PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
  13360. CFArrayRef flavor_type_array = 0;
  13361. PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
  13362. for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
  13363. {
  13364. CFDataRef cf_data;
  13365. if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
  13366. {
  13367. static ImVector<char> clipboard_text;
  13368. int length = (int)CFDataGetLength(cf_data);
  13369. clipboard_text.resize(length + 1);
  13370. CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data);
  13371. clipboard_text[length] = 0;
  13372. CFRelease(cf_data);
  13373. return clipboard_text.Data;
  13374. }
  13375. }
  13376. }
  13377. return NULL;
  13378. }
  13379. #else
  13380. // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
  13381. static const char* GetClipboardTextFn_DefaultImpl(void*)
  13382. {
  13383. ImGuiContext& g = *GImGui;
  13384. return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
  13385. }
  13386. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  13387. {
  13388. ImGuiContext& g = *GImGui;
  13389. g.PrivateClipboard.clear();
  13390. const char* text_end = text + strlen(text);
  13391. g.PrivateClipboard.resize((int)(text_end - text) + 1);
  13392. memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
  13393. g.PrivateClipboard[(int)(text_end - text)] = 0;
  13394. }
  13395. #endif
  13396. //-----------------------------------------------------------------------------
  13397. // [SECTION] METRICS/DEBUG WINDOW
  13398. //-----------------------------------------------------------------------------
  13399. static void RenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
  13400. {
  13401. ImGuiContext& g = *GImGui;
  13402. ImGuiWindow* window = g.CurrentWindow;
  13403. ImVec2 scale = bb.GetSize() / viewport->Size;
  13404. ImVec2 off = bb.Min - viewport->Pos * scale;
  13405. float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
  13406. window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
  13407. for (int i = 0; i != g.Windows.Size; i++)
  13408. {
  13409. ImGuiWindow* thumb_window = g.Windows[i];
  13410. if (!thumb_window->WasActive || ((thumb_window->Flags & ImGuiWindowFlags_ChildWindow)))
  13411. continue;
  13412. if (thumb_window->SkipItems && (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME-DOCK: Skip hidden docked windows. Identify those betters.
  13413. continue;
  13414. if (thumb_window->Viewport != viewport)
  13415. continue;
  13416. ImRect thumb_r = thumb_window->Rect();
  13417. ImRect title_r = thumb_window->TitleBarRect();
  13418. ImRect thumb_r_scaled = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale));
  13419. ImRect title_r_scaled = 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
  13420. thumb_r_scaled.ClipWithFull(bb);
  13421. title_r_scaled.ClipWithFull(bb);
  13422. const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
  13423. window->DrawList->AddRectFilled(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_WindowBg, alpha_mul));
  13424. window->DrawList->AddRectFilled(title_r_scaled.Min, title_r_scaled.Max, ImGui::GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
  13425. window->DrawList->AddRect(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul));
  13426. if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(thumb_window))
  13427. window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r_scaled.Min, ImGui::GetColorU32(ImGuiCol_Text, alpha_mul), window_for_title->Name, ImGui::FindRenderedTextEnd(window_for_title->Name));
  13428. }
  13429. draw_list->AddRect(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul));
  13430. }
  13431. void ImGui::ShowViewportThumbnails()
  13432. {
  13433. ImGuiContext& g = *GImGui;
  13434. ImGuiWindow* window = g.CurrentWindow;
  13435. // 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.
  13436. float SCALE = 1.0f / 8.0f;
  13437. ImRect bb_full;
  13438. //for (int n = 0; n < g.PlatformIO.Monitors.Size; n++)
  13439. // bb_full.Add(GetPlatformMonitorMainRect(g.PlatformIO.Monitors[n]));
  13440. for (int n = 0; n < g.Viewports.Size; n++)
  13441. bb_full.Add(g.Viewports[n]->GetMainRect());
  13442. ImVec2 p = window->DC.CursorPos;
  13443. ImVec2 off = p - bb_full.Min * SCALE;
  13444. //for (int n = 0; n < g.PlatformIO.Monitors.Size; n++)
  13445. // window->DrawList->AddRect(off + g.PlatformIO.Monitors[n].MainPos * SCALE, off + (g.PlatformIO.Monitors[n].MainPos + g.PlatformIO.Monitors[n].MainSize) * SCALE, ImGui::GetColorU32(ImGuiCol_Border));
  13446. for (int n = 0; n < g.Viewports.Size; n++)
  13447. {
  13448. ImGuiViewportP* viewport = g.Viewports[n];
  13449. ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
  13450. RenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
  13451. }
  13452. ImGui::Dummy(bb_full.GetSize() * SCALE);
  13453. }
  13454. #ifndef IMGUI_DISABLE_METRICS_WINDOW
  13455. // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
  13456. static void MetricsHelpMarker(const char* desc)
  13457. {
  13458. ImGui::TextDisabled("(?)");
  13459. if (ImGui::IsItemHovered())
  13460. {
  13461. ImGui::BeginTooltip();
  13462. ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
  13463. ImGui::TextUnformatted(desc);
  13464. ImGui::PopTextWrapPos();
  13465. ImGui::EndTooltip();
  13466. }
  13467. }
  13468. void ImGui::ShowMetricsWindow(bool* p_open)
  13469. {
  13470. if (!ImGui::Begin("Dear ImGui Metrics", p_open))
  13471. {
  13472. ImGui::End();
  13473. return;
  13474. }
  13475. // Debugging enums
  13476. enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
  13477. const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" };
  13478. enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersDesired, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type
  13479. const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersDesired", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" };
  13480. // State
  13481. static bool show_windows_rects = false;
  13482. static int show_windows_rect_type = WRT_WorkRect;
  13483. static bool show_windows_begin_order = false;
  13484. static bool show_tables_rects = false;
  13485. static int show_tables_rect_type = TRT_WorkRect;
  13486. static bool show_drawcmd_details = true;
  13487. static bool show_docking_nodes = false;
  13488. // Basic info
  13489. ImGuiContext& g = *GImGui;
  13490. ImGuiIO& io = ImGui::GetIO();
  13491. ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
  13492. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  13493. ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
  13494. ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
  13495. ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
  13496. ImGui::Separator();
  13497. // Helper functions to display common structures:
  13498. // - NodeDrawList()
  13499. // - NodeColumns()
  13500. // - NodeWindow()
  13501. // - NodeWindows()
  13502. // - NodeViewport()
  13503. // - NodeDockNode()
  13504. // - NodeTabBar()
  13505. // - NodeStorage()
  13506. struct Funcs
  13507. {
  13508. static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
  13509. {
  13510. if (rect_type == WRT_OuterRect) { return window->Rect(); }
  13511. else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
  13512. else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
  13513. else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
  13514. else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
  13515. else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
  13516. else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
  13517. IM_ASSERT(0);
  13518. return ImRect();
  13519. }
  13520. static void NodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, ImDrawList* draw_list, const char* label)
  13521. {
  13522. bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
  13523. if (draw_list == ImGui::GetWindowDrawList())
  13524. {
  13525. ImGui::SameLine();
  13526. ImGui::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)
  13527. if (node_open) ImGui::TreePop();
  13528. return;
  13529. }
  13530. ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
  13531. if (window && fg_draw_list && ImGui::IsItemHovered())
  13532. fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  13533. if (!node_open)
  13534. return;
  13535. if (window && !window->WasActive)
  13536. ImGui::TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
  13537. unsigned int elem_offset = 0;
  13538. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
  13539. {
  13540. if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
  13541. continue;
  13542. if (pcmd->UserCallback)
  13543. {
  13544. ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  13545. continue;
  13546. }
  13547. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  13548. char buf[300];
  13549. ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd: %4d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
  13550. pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId,
  13551. pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  13552. bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
  13553. if (show_drawcmd_details && fg_draw_list && ImGui::IsItemHovered())
  13554. {
  13555. ImRect clip_rect = pcmd->ClipRect;
  13556. ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
  13557. for (unsigned int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
  13558. vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
  13559. fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255,0,255,255));
  13560. fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(255,255,0,255));
  13561. }
  13562. if (!pcmd_node_open)
  13563. continue;
  13564. // Calculate approximate coverage area (touched pixel count)
  13565. // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
  13566. float total_area = 0.0f;
  13567. for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
  13568. {
  13569. ImVec2 triangle[3];
  13570. for (int n = 0; n < 3; n++)
  13571. triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
  13572. total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
  13573. }
  13574. // Display vertex information summary. Hover to get all triangles drawn in wire-frame
  13575. ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
  13576. ImGui::Selectable(buf);
  13577. if (fg_draw_list && ImGui::IsItemHovered() && show_drawcmd_details)
  13578. {
  13579. // Draw wire-frame version of everything
  13580. ImDrawListFlags backup_flags = fg_draw_list->Flags;
  13581. fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  13582. ImRect clip_rect = pcmd->ClipRect;
  13583. fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255));
  13584. for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
  13585. {
  13586. ImVec2 triangle[3];
  13587. for (int n = 0; n < 3; n++)
  13588. triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
  13589. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f);
  13590. }
  13591. fg_draw_list->Flags = backup_flags;
  13592. }
  13593. // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
  13594. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  13595. while (clipper.Step())
  13596. for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
  13597. {
  13598. char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
  13599. ImVec2 triangle[3];
  13600. for (int n = 0; n < 3; n++, idx_i++)
  13601. {
  13602. ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
  13603. triangle[n] = v.pos;
  13604. buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
  13605. (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  13606. }
  13607. ImGui::Selectable(buf, false);
  13608. if (fg_draw_list && ImGui::IsItemHovered())
  13609. {
  13610. ImDrawListFlags backup_flags = fg_draw_list->Flags;
  13611. fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
  13612. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255,255,0,255), true, 1.0f);
  13613. fg_draw_list->Flags = backup_flags;
  13614. }
  13615. }
  13616. ImGui::TreePop();
  13617. }
  13618. ImGui::TreePop();
  13619. }
  13620. static void NodeColumns(const ImGuiColumns* columns)
  13621. {
  13622. if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
  13623. return;
  13624. ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
  13625. for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
  13626. ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
  13627. ImGui::TreePop();
  13628. }
  13629. static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
  13630. {
  13631. if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
  13632. return;
  13633. for (int i = 0; i < windows.Size; i++)
  13634. {
  13635. ImGui::PushID(windows[i]);
  13636. Funcs::NodeWindow(windows[i], "Window");
  13637. ImGui::PopID();
  13638. }
  13639. ImGui::TreePop();
  13640. }
  13641. static void NodeWindow(ImGuiWindow* window, const char* label)
  13642. {
  13643. if (window == NULL)
  13644. {
  13645. ImGui::BulletText("%s: NULL", label);
  13646. return;
  13647. }
  13648. bool open = ImGui::TreeNode(label, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window);
  13649. if (ImGui::IsItemHovered() && window->WasActive)
  13650. ImGui::GetForegroundDrawList()->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  13651. if (!open)
  13652. return;
  13653. ImGuiWindowFlags flags = window->Flags;
  13654. NodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
  13655. ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y);
  13656. ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
  13657. (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
  13658. (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
  13659. (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
  13660. ImGui::BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
  13661. ImGui::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" : "");
  13662. ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
  13663. ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
  13664. ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
  13665. ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
  13666. if (!window->NavRectRel[0].IsInverted())
  13667. ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
  13668. else
  13669. ImGui::BulletText("NavRectRel[0]: <None>");
  13670. ImGui::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);
  13671. ImGui::BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
  13672. ImGui::BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
  13673. if (window->DockNode || window->DockNodeAsHost)
  13674. NodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
  13675. if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
  13676. if (window->RootWindowDockStop != window->RootWindow) NodeWindow(window->RootWindowDockStop, "RootWindowDockStop");
  13677. if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
  13678. if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
  13679. if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
  13680. {
  13681. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  13682. NodeColumns(&window->ColumnsStorage[n]);
  13683. ImGui::TreePop();
  13684. }
  13685. NodeStorage(&window->StateStorage, "Storage");
  13686. ImGui::TreePop();
  13687. }
  13688. static void NodeViewport(ImGuiViewportP* viewport)
  13689. {
  13690. ImGui::SetNextItemOpen(true, ImGuiCond_Once);
  13691. if (ImGui::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"))
  13692. {
  13693. ImGuiWindowFlags flags = viewport->Flags;
  13694. ImGui::BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
  13695. viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
  13696. viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
  13697. viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
  13698. if (viewport->Idx > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200,200); if (viewport->Window) viewport->Window->Pos = ImVec2(200,200); } }
  13699. ImGui::BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s", viewport->Flags,
  13700. (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
  13701. (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
  13702. (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
  13703. (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "");
  13704. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  13705. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  13706. Funcs::NodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  13707. ImGui::TreePop();
  13708. }
  13709. }
  13710. static void NodeDockNode(ImGuiDockNode* node, const char* label)
  13711. {
  13712. ImGuiContext& g = *GImGui;
  13713. bool open;
  13714. if (node->Windows.Size > 0)
  13715. open = ImGui::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");
  13716. else
  13717. open = ImGui::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");
  13718. if (open)
  13719. {
  13720. IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
  13721. IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
  13722. ImGui::BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
  13723. node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
  13724. NodeWindow(node->HostWindow, "HostWindow");
  13725. NodeWindow(node->VisibleWindow, "VisibleWindow");
  13726. ImGui::BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
  13727. ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : "");
  13728. if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags))
  13729. {
  13730. ImGui::CheckboxFlags("LocalFlags: NoDocking", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoDocking);
  13731. ImGui::CheckboxFlags("LocalFlags: NoSplit", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit);
  13732. ImGui::CheckboxFlags("LocalFlags: NoResize", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize);
  13733. ImGui::CheckboxFlags("LocalFlags: NoTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar);
  13734. ImGui::CheckboxFlags("LocalFlags: HiddenTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar);
  13735. ImGui::CheckboxFlags("LocalFlags: NoWindowMenuButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton);
  13736. ImGui::CheckboxFlags("LocalFlags: NoCloseButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoCloseButton);
  13737. ImGui::TreePop();
  13738. }
  13739. if (node->ParentNode)
  13740. NodeDockNode(node->ParentNode, "ParentNode");
  13741. if (node->ChildNodes[0])
  13742. NodeDockNode(node->ChildNodes[0], "Child[0]");
  13743. if (node->ChildNodes[1])
  13744. NodeDockNode(node->ChildNodes[1], "Child[1]");
  13745. if (node->TabBar)
  13746. NodeTabBar(node->TabBar);
  13747. ImGui::TreePop();
  13748. }
  13749. }
  13750. static void NodeTabBar(ImGuiTabBar* tab_bar)
  13751. {
  13752. // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
  13753. char buf[256];
  13754. char* p = buf;
  13755. const char* buf_end = buf + IM_ARRAYSIZE(buf);
  13756. p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
  13757. if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
  13758. {
  13759. p += ImFormatString(p, buf_end - p, " { ");
  13760. for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
  13761. p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", tab_bar->Tabs[tab_n].Window->Name);
  13762. p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
  13763. }
  13764. if (ImGui::TreeNode(tab_bar, "%s", buf))
  13765. {
  13766. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
  13767. {
  13768. const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
  13769. ImGui::PushID(tab);
  13770. if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
  13771. if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
  13772. ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "");
  13773. ImGui::PopID();
  13774. }
  13775. ImGui::TreePop();
  13776. }
  13777. }
  13778. static void NodeStorage(ImGuiStorage* storage, const char* label)
  13779. {
  13780. if (!ImGui::TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
  13781. return;
  13782. for (int n = 0; n < storage->Data.Size; n++)
  13783. {
  13784. const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
  13785. ImGui::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.
  13786. }
  13787. ImGui::TreePop();
  13788. }
  13789. };
  13790. Funcs::NodeWindows(g.Windows, "Windows");
  13791. //Funcs::NodeWindows(g.WindowsFocusOrder, "WindowsFocusOrder");
  13792. if (ImGui::TreeNode("Viewport", "Viewports (%d)", g.Viewports.Size))
  13793. {
  13794. ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
  13795. ImGui::ShowViewportThumbnails();
  13796. ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
  13797. bool open = ImGui::TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
  13798. ImGui::SameLine();
  13799. 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.");
  13800. if (open)
  13801. {
  13802. for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
  13803. {
  13804. const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
  13805. ImGui::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)",
  13806. i, mon.DpiScale * 100.0f,
  13807. mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
  13808. mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
  13809. }
  13810. ImGui::TreePop();
  13811. }
  13812. for (int i = 0; i < g.Viewports.Size; i++)
  13813. Funcs::NodeViewport(g.Viewports[i]);
  13814. ImGui::TreePop();
  13815. }
  13816. // Details for Popups
  13817. if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
  13818. {
  13819. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  13820. {
  13821. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  13822. ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
  13823. }
  13824. ImGui::TreePop();
  13825. }
  13826. // Details for TabBars
  13827. if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
  13828. {
  13829. for (int n = 0; n < g.TabBars.GetSize(); n++)
  13830. Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
  13831. ImGui::TreePop();
  13832. }
  13833. // Details for Tables
  13834. IM_UNUSED(trt_rects_names);
  13835. IM_UNUSED(show_tables_rects);
  13836. IM_UNUSED(show_tables_rect_type);
  13837. #ifdef IMGUI_HAS_TABLE
  13838. if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
  13839. {
  13840. for (int n = 0; n < g.Tables.GetSize(); n++)
  13841. Funcs::NodeTable(g.Tables.GetByIndex(n));
  13842. ImGui::TreePop();
  13843. }
  13844. #endif // #define IMGUI_HAS_TABLE
  13845. // Details for Docking
  13846. #ifdef IMGUI_HAS_DOCK
  13847. if (ImGui::TreeNode("Docking"))
  13848. {
  13849. ImGuiDockContext* dc = g.DockContext;
  13850. ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes);
  13851. if (ImGui::TreeNode("Dock nodes"))
  13852. {
  13853. if (ImGui::SmallButton("Clear settings")) { DockContextClearNodes(&g, 0, true); }
  13854. ImGui::SameLine();
  13855. if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
  13856. for (int n = 0; n < dc->Nodes.Data.Size; n++)
  13857. if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
  13858. if (node->IsRootNode())
  13859. Funcs::NodeDockNode(node, "Node");
  13860. ImGui::TreePop();
  13861. }
  13862. if (ImGui::TreeNode("Settings"))
  13863. {
  13864. if (ImGui::SmallButton("Refresh"))
  13865. SaveIniSettingsToMemory();
  13866. ImGui::SameLine();
  13867. if (ImGui::SmallButton("Save to disk"))
  13868. SaveIniSettingsToDisk(g.IO.IniFilename);
  13869. ImGui::Separator();
  13870. ImGui::Text("Docked Windows:");
  13871. for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
  13872. if (settings->DockId != 0)
  13873. ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
  13874. ImGui::Separator();
  13875. ImGui::Text("Dock Nodes:");
  13876. for (int n = 0; n < dc->SettingsNodes.Size; n++)
  13877. {
  13878. ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n];
  13879. const char* selected_tab_name = NULL;
  13880. if (settings->SelectedWindowId)
  13881. {
  13882. if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowId))
  13883. selected_tab_name = window->Name;
  13884. else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowId))
  13885. selected_tab_name = window_settings->GetName();
  13886. }
  13887. ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedWindowId, selected_tab_name ? selected_tab_name : settings->SelectedWindowId ? "N/A" : "");
  13888. }
  13889. ImGui::TreePop();
  13890. }
  13891. ImGui::TreePop();
  13892. }
  13893. #endif // #define IMGUI_HAS_DOCK
  13894. // Misc Details
  13895. if (ImGui::TreeNode("Internal state"))
  13896. {
  13897. const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
  13898. ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  13899. ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
  13900. ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
  13901. ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
  13902. ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
  13903. ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  13904. ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
  13905. ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  13906. ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
  13907. ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
  13908. ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
  13909. ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
  13910. ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
  13911. ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
  13912. ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
  13913. ImGui::Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
  13914. ImGui::TreePop();
  13915. }
  13916. // Tools
  13917. if (ImGui::TreeNode("Tools"))
  13918. {
  13919. // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
  13920. if (ImGui::Button("Item Picker.."))
  13921. ImGui::DebugStartItemPicker();
  13922. ImGui::SameLine();
  13923. 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.");
  13924. ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
  13925. ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
  13926. ImGui::SameLine();
  13927. ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
  13928. show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count, WRT_Count);
  13929. if (show_windows_rects && g.NavWindow)
  13930. {
  13931. ImGui::BulletText("'%s':", g.NavWindow->Name);
  13932. ImGui::Indent();
  13933. for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
  13934. {
  13935. ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
  13936. ImGui::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]);
  13937. }
  13938. ImGui::Unindent();
  13939. }
  13940. ImGui::Checkbox("Show details when hovering ImDrawCmd node", &show_drawcmd_details);
  13941. ImGui::TreePop();
  13942. }
  13943. // Overlay: Display windows Rectangles and Begin Order
  13944. if (show_windows_rects || show_windows_begin_order)
  13945. {
  13946. for (int n = 0; n < g.Windows.Size; n++)
  13947. {
  13948. ImGuiWindow* window = g.Windows[n];
  13949. if (!window->WasActive)
  13950. continue;
  13951. ImDrawList* draw_list = GetForegroundDrawList(window);
  13952. if (show_windows_rects)
  13953. {
  13954. ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type);
  13955. draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
  13956. }
  13957. if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
  13958. {
  13959. char buf[32];
  13960. ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
  13961. float font_size = ImGui::GetFontSize();
  13962. draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
  13963. draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
  13964. }
  13965. }
  13966. }
  13967. #ifdef IMGUI_HAS_TABLE
  13968. // Overlay: Display Tables Rectangles
  13969. if (show_tables_rects)
  13970. {
  13971. for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
  13972. {
  13973. ImGuiTable* table = g.Tables.GetByIndex(table_n);
  13974. }
  13975. }
  13976. #endif // #define IMGUI_HAS_TABLE
  13977. #ifdef IMGUI_HAS_DOCK
  13978. // Overlay: Display Docking info
  13979. if (show_docking_nodes && g.IO.KeyCtrl)
  13980. {
  13981. for (int n = 0; n < g.DockContext->Nodes.Data.Size; n++)
  13982. if (ImGuiDockNode* node = (ImGuiDockNode*)g.DockContext->Nodes.Data[n].val_p)
  13983. {
  13984. ImGuiDockNode* root_node = DockNodeGetRootNode(node);
  13985. if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos))
  13986. if (hovered_node != node)
  13987. continue;
  13988. char buf[64] = "";
  13989. char* p = buf;
  13990. ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport());
  13991. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
  13992. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
  13993. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
  13994. p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
  13995. int depth = DockNodeGetDepth(node);
  13996. 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));
  13997. ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
  13998. overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
  13999. overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
  14000. }
  14001. }
  14002. #endif // #define IMGUI_HAS_DOCK
  14003. ImGui::End();
  14004. }
  14005. #else
  14006. void ImGui::ShowMetricsWindow(bool*) { }
  14007. #endif
  14008. //-----------------------------------------------------------------------------
  14009. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  14010. // 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.
  14011. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  14012. #include "imgui_user.inl"
  14013. #endif
  14014. //-----------------------------------------------------------------------------
  14015. #endif // #ifndef IMGUI_DISABLE