imgui.cpp 644 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126
  1. // dear imgui, v1.60 WIP
  2. // (main code and documentation)
  3. // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
  4. // Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
  5. // Get latest version at https://github.com/ocornut/imgui
  6. // Releases change-log at https://github.com/ocornut/imgui/releases
  7. // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
  8. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  9. // This library is free but I need your support to sustain development and maintenance.
  10. // If you work for a company, please consider financial support, see Readme. For individuals: https://www.patreon.com/imgui
  11. /*
  12. Index
  13. - MISSION STATEMENT
  14. - END-USER GUIDE
  15. - PROGRAMMER GUIDE (read me!)
  16. - Read first
  17. - How to update to a newer version of Dear ImGui
  18. - Getting started with integrating Dear ImGui in your code/engine
  19. - Using gamepad/keyboard navigation controls [BETA]
  20. - API BREAKING CHANGES (read me when you update!)
  21. - ISSUES & TODO LIST
  22. - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  23. - How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
  24. - How can I display an image? What is ImTextureID, how does it works?
  25. - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels and the ID stack.
  26. - How can I load a different font than the default?
  27. - How can I easily use icons in my application?
  28. - How can I load multiple fonts?
  29. - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
  30. - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  31. - I integrated Dear ImGui in my engine and the text or lines are blurry..
  32. - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  33. - How can I help?
  34. - ISSUES & TODO-LIST
  35. - CODE
  36. MISSION STATEMENT
  37. =================
  38. - Easy to use to create code-driven and data-driven tools
  39. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
  40. - Easy to hack and improve
  41. - Minimize screen real-estate usage
  42. - Minimize setup and maintenance
  43. - Minimize state storage on user side
  44. - Portable, minimize dependencies, run on target (consoles, phones, etc.)
  45. - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window, opening a tree node
  46. for the first time, etc. but a typical frame won't allocate anything)
  47. Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
  48. - Doesn't look fancy, doesn't animate
  49. - Limited layout features, intricate layouts are typically crafted in code
  50. END-USER GUIDE
  51. ==============
  52. - Double-click on title bar to collapse window.
  53. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
  54. - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
  55. - Click and drag on any empty space to move window.
  56. - TAB/SHIFT+TAB to cycle through keyboard editable fields.
  57. - CTRL+Click on a slider or drag box to input value as text.
  58. - Use mouse wheel to scroll.
  59. - Text editor:
  60. - Hold SHIFT or use mouse to select text.
  61. - CTRL+Left/Right to word jump.
  62. - CTRL+Shift+Left/Right to select words.
  63. - CTRL+A our Double-Click to select all.
  64. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
  65. - CTRL+Z,CTRL+Y to undo/redo.
  66. - ESCAPE to revert text to its original value.
  67. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  68. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  69. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
  70. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at goo.gl/9LgVZW.
  71. PROGRAMMER GUIDE
  72. ================
  73. READ FIRST
  74. - Read the FAQ below this section!
  75. - Your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention
  76. on your side, no state duplication, less sync, less bugs.
  77. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
  78. - You can learn about immediate-mode gui principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861
  79. HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
  80. - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
  81. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  82. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API.
  83. If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it.
  84. Please report any issue to the GitHub page!
  85. - Try to keep your copy of dear imgui reasonably up to date.
  86. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
  87. - Add the Dear ImGui source files to your projects, using your preferred build system.
  88. It is recommended you build the .cpp files as part of your project and not as a library.
  89. - You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types.
  90. - See examples/ folder for standalone sample applications.
  91. - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
  92. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
  93. - Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize
  94. (application resolution). Later on you will fill your keyboard mapping, clipboard handlers, and other advanced features but for a basic
  95. integration you don't need to worry about it all.
  96. - Init: call io.Fonts->GetTexDataAsRGBA32(...), it will build the font atlas texture, then load the texture pixels into graphics memory.
  97. - Every frame:
  98. - In your main loop as early a possible, fill the IO fields marked 'Input' (e.g. mouse position, buttons, keyboard info, etc.)
  99. - Call ImGui::NewFrame() to begin the frame
  100. - You can use any ImGui function you want between NewFrame() and Render()
  101. - Call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your io.RenderDrawListFn handler.
  102. (Even if you don't render, call Render() and ignore the callback, or call EndFrame() instead. Otherwhise some features will break)
  103. - All rendering information are stored into command-lists until ImGui::Render() is called.
  104. - Dear ImGui never touches or knows about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide.
  105. - Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases
  106. of your own application.
  107. - Refer to the examples applications in the examples/ folder for instruction on how to setup your code.
  108. - A minimal application skeleton may be:
  109. // Application init
  110. ImGui::CreateContext();
  111. ImGuiIO& io = ImGui::GetIO();
  112. io.DisplaySize.x = 1920.0f;
  113. io.DisplaySize.y = 1280.0f;
  114. // TODO: Fill others settings of the io structure later.
  115. // Load texture atlas (there is a default font so you don't need to care about choosing a font yet)
  116. unsigned char* pixels;
  117. int width, height;
  118. io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
  119. // TODO: At this points you've got the texture data and you need to upload that your your graphic system:
  120. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA)
  121. // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'. This will be passed back to your via the renderer.
  122. io.Fonts->TexID = (void*)texture;
  123. // Application main loop
  124. while (true)
  125. {
  126. // Setup low-level inputs (e.g. on Win32, GetKeyboardState(), or write to those fields from your Windows message loop handlers, etc.)
  127. ImGuiIO& io = ImGui::GetIO();
  128. io.DeltaTime = 1.0f/60.0f;
  129. io.MousePos = mouse_pos;
  130. io.MouseDown[0] = mouse_button_0;
  131. io.MouseDown[1] = mouse_button_1;
  132. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  133. ImGui::NewFrame();
  134. // Most of your application code here
  135. MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  136. MyGameRender(); // may use any ImGui functions as well!
  137. // Render & swap video buffers
  138. ImGui::Render();
  139. MyImGuiRenderFunction(ImGui::GetDrawData());
  140. SwapBuffers();
  141. }
  142. // Shutdown
  143. ImGui::DestroyContext();
  144. - A minimal render function skeleton may be:
  145. void void MyRenderFunction(ImDrawData* draw_data)
  146. {
  147. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  148. // TODO: Setup viewport, orthographic projection matrix
  149. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  150. for (int n = 0; n < draw_data->CmdListsCount; n++)
  151. {
  152. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
  153. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
  154. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  155. {
  156. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  157. if (pcmd->UserCallback)
  158. {
  159. pcmd->UserCallback(cmd_list, pcmd);
  160. }
  161. else
  162. {
  163. // The texture for the draw call is specified by pcmd->TextureId.
  164. // The vast majority of draw calls with use the imgui texture atlas, which value you have set yourself during initialization.
  165. MyEngineBindTexture(pcmd->TextureId);
  166. // We are using scissoring to clip some objects. All low-level graphics API supports it.
  167. // If your engine doesn't support scissoring yet, you will get some small glitches (some elements outside their bounds) which you can fix later.
  168. MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  169. // Render 'pcmd->ElemCount/3' indexed triangles.
  170. // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits if your engine doesn't support 16-bits indices.
  171. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
  172. }
  173. idx_buffer += pcmd->ElemCount;
  174. }
  175. }
  176. }
  177. - The examples/ folders contains many functional implementation of the pseudo-code above.
  178. - When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated.
  179. They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide
  180. mouse inputs from the rest of your application. Read the FAQ below for more information about those flags.
  181. USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS [BETA]
  182. - The gamepad/keyboard navigation is in Beta. Ask questions and report issues at https://github.com/ocornut/imgui/issues/787
  183. - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
  184. - Keyboard:
  185. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeyDown[] + io.KeyMap[] arrays.
  186. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag will be set.
  187. For more advanced uses, you may want to read from:
  188. - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
  189. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
  190. - or query focus information with e.g. IsWindowFocused(), IsItemFocused() etc. functions.
  191. Please reach out if you think the game vs navigation input sharing could be improved.
  192. - Gamepad:
  193. - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame().
  194. - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
  195. 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
  196. - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
  197. 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.).
  198. - You can download PNG/PSD files depicting the gamepad controls for common controllers at: goo.gl/9LgVZW.
  199. - 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 to toggle the target.
  200. Please reach out if you think the game vs navigation input sharing could be improved.
  201. - Mouse:
  202. - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
  203. - 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.
  204. - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavMoveMouse flag.
  205. Enabling ImGuiConfigFlags_NavMoveMouse instructs dear imgui to move your mouse cursor along with navigation movements.
  206. When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantMoveMouse' to notify you that it wants the mouse cursor to be moved.
  207. 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.
  208. (If you set the NavMoveMouse flag but don't honor 'io.WantMoveMouse' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
  209. (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
  210. to set a boolean to ignore your other external mouse positions until the external source is moved again.)
  211. API BREAKING CHANGES
  212. ====================
  213. Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
  214. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
  215. Also read releases logs https://github.com/ocornut/imgui/releases for more details.
  216. - 2018/03/12 (1.60) - Removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
  217. - 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.
  218. - 2018/03/03 (1.60) - Renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
  219. - 2018/02/27 (1.XX) - removed io.DisplayVisibleMin, io.DisplayVisibleMax settings (it was used to clip within the DisplayMin..DisplayMax range, I don't know of anyone using it)
  220. - 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.
  221. - 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.
  222. - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
  223. - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
  224. - removed Shutdown() function, as DestroyContext() serve this purpose.
  225. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwhise CreateContext() will create its own font atlas instance.
  226. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
  227. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
  228. - 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.
  229. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
  230. - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
  231. - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
  232. - 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.
  233. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
  234. - 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
  235. - 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.
  236. - 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.
  237. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
  238. - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
  239. - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
  240. - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
  241. - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
  242. - 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.
  243. - 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.
  244. 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.
  245. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
  246. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
  247. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
  248. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
  249. - 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.
  250. - 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.
  251. - 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.
  252. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
  253. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
  254. - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
  255. - 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).
  256. - 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)".
  257. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
  258. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  259. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  260. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  261. - 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.
  262. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
  263. - 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.
  264. - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
  265. - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
  266. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  267. - 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.
  268. - 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.
  269. - 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))'
  270. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  271. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  272. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  273. - 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().
  274. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  275. - 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.
  276. - 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.
  277. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  278. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
  279. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
  280. 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.
  281. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
  282. {
  283. float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
  284. 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);
  285. }
  286. 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.
  287. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  288. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  289. - 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).
  290. - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
  291. - 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).
  292. - 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)
  293. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  294. - 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.
  295. - 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.
  296. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  297. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  298. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  299. 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.
  300. 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!
  301. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  302. - 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.
  303. - 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
  304. - 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.
  305. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  306. - 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.
  307. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  308. - 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.
  309. - the signature of the io.RenderDrawListsFn handler has changed!
  310. old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  311. new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  312. argument: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
  313. ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
  314. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
  315. - 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.
  316. - 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!
  317. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  318. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  319. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  320. - 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.
  321. - 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
  322. - 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!
  323. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  324. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  325. - 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.
  326. - 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.
  327. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  328. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  329. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  330. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  331. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  332. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  333. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  334. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  335. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  336. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  337. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  338. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  339. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  340. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  341. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  342. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  343. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  344. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  345. font init: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>
  346. became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier;
  347. you now more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
  348. it is now recommended that you sample the font texture with bilinear interpolation.
  349. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
  350. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  351. (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  352. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  353. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  354. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  355. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  356. - 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)
  357. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  358. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  359. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  360. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  361. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  362. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  363. ISSUES & TODO-LIST
  364. ==================
  365. See TODO.txt
  366. FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  367. ======================================
  368. Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
  369. A: You can read the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags from the ImGuiIO structure.
  370. - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
  371. - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
  372. - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
  373. The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
  374. It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
  375. Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
  376. perfectly fine, as the bool toggle fairly rarely.
  377. (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically
  378. have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
  379. were for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
  380. Q: How can I display an image? What is ImTextureID, how does it works?
  381. A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
  382. Dear ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
  383. It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
  384. At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
  385. Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
  386. (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
  387. To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
  388. Dear ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
  389. You may call ImGui::ShowMetricsWindow() to explore active draw lists and visualize/understand how the draw data is generated.
  390. It is your responsibility to get textures uploaded to your GPU.
  391. Q: Can I have multiple widgets with the same label? Can I have widget without a label?
  392. A: Yes. A primer on labels and the ID stack...
  393. - Elements that are typically not clickable, such as Text() items don't need an ID.
  394. - Interactive widgets require state to be carried over multiple frames (most typically Dear ImGui often needs to remember what is
  395. the "active" widget). to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
  396. Button("OK"); // Label = "OK", ID = hash of "OK"
  397. Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
  398. - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK"
  399. in two different windows or in two different locations of a tree.
  400. - If you have a same ID twice in the same location, you'll have a conflict:
  401. Button("OK");
  402. Button("OK"); // ID collision! Both buttons will be treated as the same.
  403. Fear not! this is easy to solve and there are many ways to solve it!
  404. - When passing a label you can optionally specify extra unique ID information within string itself.
  405. Use "##" to pass a complement to the ID that won't be visible to the end-user.
  406. This helps solving the simple collision cases when you know which items are going to be created.
  407. Button("Play"); // Label = "Play", ID = hash of "Play"
  408. Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
  409. Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
  410. - If you want to completely hide the label, but still need an ID:
  411. Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
  412. - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels.
  413. For example you may want to include varying information in a window title bar, but windows are uniquely identified by their ID..
  414. Use "###" to pass a label that isn't part of ID:
  415. Button("Hello###ID"; // Label = "Hello", ID = hash of "ID"
  416. Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above)
  417. sprintf(buf, "My game (%f FPS)###MyGame", fps);
  418. Begin(buf); // Variable label, ID = hash of "MyGame"
  419. - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
  420. This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
  421. You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of _everything_ in the ID stack!
  422. for (int i = 0; i < 100; i++)
  423. {
  424. PushID(i);
  425. Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
  426. PopID();
  427. }
  428. for (int i = 0; i < 100; i++)
  429. {
  430. MyObject* obj = Objects[i];
  431. PushID(obj);
  432. Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
  433. PopID();
  434. }
  435. for (int i = 0; i < 100; i++)
  436. {
  437. MyObject* obj = Objects[i];
  438. PushID(obj->Name);
  439. Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
  440. PopID();
  441. }
  442. - More example showing that you can stack multiple prefixes into the ID stack:
  443. Button("Click"); // Label = "Click", ID = hash of "Click"
  444. PushID("node");
  445. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  446. PushID(my_ptr);
  447. Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click"
  448. PopID();
  449. PopID();
  450. - Tree nodes implicitly creates a scope for you by calling PushID().
  451. Button("Click"); // Label = "Click", ID = hash of "Click"
  452. if (TreeNode("node"))
  453. {
  454. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  455. TreePop();
  456. }
  457. - When working with trees, ID are used to preserve the open/close state of each tree node.
  458. Depending on your use cases you may want to use strings, indices or pointers as ID.
  459. e.g. when displaying a single object that may change over time (dynamic 1-1 relationship), using a static string as ID will preserve your
  460. node open/closed state when the targeted object change.
  461. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently.
  462. experiment and see what makes more sense!
  463. Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
  464. A: Use the font atlas to load the TTF/OTF file you want:
  465. ImGuiIO& io = ImGui::GetIO();
  466. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  467. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  468. New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ in a string literal you need to write a double backslash "\\":
  469. io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG
  470. io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
  471. io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
  472. Q: How can I easily use icons in my application?
  473. A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your
  474. strings. Read 'How can I load multiple fonts?' and the file 'misc/fonts/README.txt' for instructions and useful header files.
  475. Q: How can I load multiple fonts?
  476. A: Use the font atlas to pack them into a single texture:
  477. (Read misc/fonts/README.txt and the code in ImFontAtlas for more details.)
  478. ImGuiIO& io = ImGui::GetIO();
  479. ImFont* font0 = io.Fonts->AddFontDefault();
  480. ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  481. ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
  482. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  483. // the first loaded font gets used by default
  484. // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
  485. // Options
  486. ImFontConfig config;
  487. config.OversampleH = 3;
  488. config.OversampleV = 1;
  489. config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up
  490. config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
  491. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
  492. // Combine multiple fonts into one (e.g. for icon fonts)
  493. ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
  494. ImFontConfig config;
  495. config.MergeMode = true;
  496. io.Fonts->AddFontDefault();
  497. io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
  498. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
  499. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  500. A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
  501. // Add default Japanese ranges
  502. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
  503. // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
  504. ImVector<ImWchar> ranges;
  505. ImFontAtlas::GlyphRangesBuilder builder;
  506. builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
  507. builder.AddChar(0x7262); // Add a specific character
  508. builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
  509. builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
  510. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
  511. All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax.
  512. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
  513. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
  514. Text input: it is up to your application to pass the right character code to io.AddInputCharacter(). The applications in examples/ are doing that.
  515. For languages using IME, on Windows you can copy the Hwnd of your application to io.ImeWindowHandle.
  516. The default implementation of io.ImeSetInputScreenPosFn() on Windows will set your IME position correctly.
  517. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  518. A: - You can create a dummy window. Call SetNextWindowBgAlpha(0.0f), call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flags.
  519. Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
  520. - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows.
  521. - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData.
  522. Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
  523. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
  524. Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
  525. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  526. A: You are probably mishandling the clipping rectangles in your render function.
  527. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
  528. Q: How can I help?
  529. A: - If you are experienced with Dear ImGui and C++, look at the github issues, or TODO.txt and see how you want/can help!
  530. - Convince your company to fund development time! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README.
  531. - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
  532. You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1269). Visuals are ideal as they inspire other programmers.
  533. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
  534. - 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).
  535. - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
  536. this is also useful to set yourself in the context of another window (to get/set other settings)
  537. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
  538. - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
  539. of a deep nested inner loop in your code.
  540. - tip: you can call Render() multiple times (e.g for VR renders).
  541. - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
  542. */
  543. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  544. #define _CRT_SECURE_NO_WARNINGS
  545. #endif
  546. #include "imgui.h"
  547. #define IMGUI_DEFINE_MATH_OPERATORS
  548. #include "imgui_internal.h"
  549. #include <ctype.h> // toupper, isprint
  550. #include <stdlib.h> // NULL, malloc, free, qsort, atoi
  551. #include <stdio.h> // vsnprintf, sscanf, printf
  552. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  553. #include <stddef.h> // intptr_t
  554. #else
  555. #include <stdint.h> // intptr_t
  556. #endif
  557. #define IMGUI_DEBUG_NAV_SCORING 0
  558. #define IMGUI_DEBUG_NAV_RECTS 0
  559. // Visual Studio warnings
  560. #ifdef _MSC_VER
  561. #pragma warning (disable: 4127) // condition expression is constant
  562. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  563. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  564. #endif
  565. // Clang warnings with -Weverything
  566. #ifdef __clang__
  567. #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!
  568. #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
  569. #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.
  570. #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.
  571. #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.
  572. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
  573. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
  574. #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.
  575. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' //
  576. #elif defined(__GNUC__)
  577. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  578. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  579. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  580. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  581. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  582. #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
  583. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  584. #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
  585. #endif
  586. // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
  587. #ifdef _MSC_VER
  588. #define IMGUI_CDECL __cdecl
  589. #else
  590. #define IMGUI_CDECL
  591. #endif
  592. //-------------------------------------------------------------------------
  593. // Forward Declarations
  594. //-------------------------------------------------------------------------
  595. static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
  596. static ImFont* GetDefaultFont();
  597. static void SetCurrentWindow(ImGuiWindow* window);
  598. static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x);
  599. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
  600. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
  601. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
  602. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
  603. static ImGuiWindow* FindHoveredWindow();
  604. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
  605. static void CheckStacksSize(ImGuiWindow* window, bool write);
  606. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
  607. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
  608. static void AddWindowToDrawData(ImVector<ImDrawList*>* out_list, ImGuiWindow* window);
  609. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
  610. static ImGuiWindowSettings* AddWindowSettings(const char* name);
  611. static void LoadIniSettingsFromDisk(const char* ini_filename);
  612. static void LoadIniSettingsFromMemory(const char* buf);
  613. static void SaveIniSettingsToDisk(const char* ini_filename);
  614. static void SaveIniSettingsToMemory(ImVector<char>& out_buf);
  615. static void MarkIniSettingsDirty(ImGuiWindow* window);
  616. static void ClosePopupToLevel(int remaining);
  617. static ImGuiWindow* GetFrontMostModalRootWindow();
  618. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data);
  619. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
  620. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
  621. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
  622. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
  623. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
  624. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
  625. namespace ImGui
  626. {
  627. static void NavUpdate();
  628. static void NavUpdateWindowing();
  629. static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id);
  630. static void UpdateMovingWindow();
  631. static void UpdateMovingWindowDropViewport(ImGuiWindow* window);
  632. static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
  633. static void FocusFrontMostActiveWindow(ImGuiWindow* ignore_window);
  634. // Viewport
  635. const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using a constant instead of e.g. ImHash("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
  636. static inline ImRect GetViewportRect(ImGuiWindow* window) { return window->Viewport->GetRect(); }
  637. static inline ImVec2 ConvertViewportPosToPlatformPos(const ImVec2& imgui_pos, ImGuiViewport* viewport) { return imgui_pos - viewport->Pos + viewport->PlatformPos; }
  638. static inline ImVec2 ConvertPlatformPosToViewportPos(const ImVec2& platform_pos, ImGuiViewport* viewport) { return platform_pos - viewport->PlatformPos + viewport->Pos; }
  639. static ImGuiViewportP* Viewport(ImGuiWindow* window, ImGuiID id, ImGuiViewportFlags flags, const ImVec2& platform_pos, const ImVec2& size);
  640. static void UpdateViewports();
  641. static void UpdateWindowViewport(ImGuiWindow* window, bool window_pos_set_by_api);
  642. static void SetCurrentViewport(ImGuiViewportP* viewport);
  643. static void SetWindowViewportTranslateToPreservePlatformPos(ImGuiWindow* window, ImGuiViewportP* old_viewport, ImGuiViewportP* new_viewport);
  644. static void ResizeViewportTranslateWindows(int viewport_idx_min, int viewport_idx_max, float pos_x_delta, int idx_delta, ImGuiViewport* viewport_to_erase);
  645. }
  646. //-----------------------------------------------------------------------------
  647. // Platform dependent default implementations
  648. //-----------------------------------------------------------------------------
  649. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  650. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  651. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
  652. //-----------------------------------------------------------------------------
  653. // Context
  654. //-----------------------------------------------------------------------------
  655. // Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL.
  656. // CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
  657. // If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file.
  658. // ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can:
  659. // - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  660. // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
  661. #ifndef GImGui
  662. ImGuiContext* GImGui = NULL;
  663. #endif
  664. // Memory Allocator functions. Use SetAllocatorFunctions() to change them.
  665. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
  666. // 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.
  667. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
  668. static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); }
  669. static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); }
  670. #else
  671. static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; }
  672. static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); }
  673. #endif
  674. static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
  675. static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
  676. static void* GImAllocatorUserData = NULL;
  677. static size_t GImAllocatorActiveAllocationsCount = 0;
  678. //-----------------------------------------------------------------------------
  679. // User facing structures
  680. //-----------------------------------------------------------------------------
  681. ImGuiStyle::ImGuiStyle()
  682. {
  683. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  684. WindowPadding = ImVec2(8,8); // Padding within a window
  685. WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
  686. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  687. WindowMinSize = ImVec2(32,32); // Minimum window size
  688. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  689. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  690. ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  691. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
  692. PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
  693. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  694. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  695. FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
  696. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  697. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  698. 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!
  699. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  700. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
  701. ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  702. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  703. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  704. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  705. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  706. DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
  707. DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
  708. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
  709. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
  710. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
  711. 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.
  712. ImGui::StyleColorsClassic(this);
  713. }
  714. // 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.
  715. // 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.
  716. void ImGuiStyle::ScaleAllSizes(float scale_factor)
  717. {
  718. WindowPadding = ImFloor(WindowPadding * scale_factor);
  719. WindowRounding = ImFloor(WindowRounding * scale_factor);
  720. WindowMinSize = ImFloor(WindowMinSize * scale_factor);
  721. ChildRounding = ImFloor(ChildRounding * scale_factor);
  722. PopupRounding = ImFloor(PopupRounding * scale_factor);
  723. FramePadding = ImFloor(FramePadding * scale_factor);
  724. FrameRounding = ImFloor(FrameRounding * scale_factor);
  725. ItemSpacing = ImFloor(ItemSpacing * scale_factor);
  726. ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
  727. TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
  728. IndentSpacing = ImFloor(IndentSpacing * scale_factor);
  729. ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
  730. ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
  731. ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
  732. GrabMinSize = ImFloor(GrabMinSize * scale_factor);
  733. GrabRounding = ImFloor(GrabRounding * scale_factor);
  734. DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
  735. DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
  736. MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
  737. }
  738. ImGuiIO::ImGuiIO()
  739. {
  740. // Most fields are initialized with zero
  741. memset(this, 0, sizeof(*this));
  742. // Settings
  743. DisplaySize = ImVec2(-1.0f, -1.0f);
  744. DeltaTime = 1.0f/60.0f;
  745. ConfigFlags = 0x00;
  746. IniSavingRate = 5.0f;
  747. IniFilename = "imgui.ini";
  748. LogFilename = "imgui_log.txt";
  749. MouseDoubleClickTime = 0.30f;
  750. MouseDoubleClickMaxDist = 6.0f;
  751. for (int i = 0; i < ImGuiKey_COUNT; i++)
  752. KeyMap[i] = -1;
  753. KeyRepeatDelay = 0.250f;
  754. KeyRepeatRate = 0.050f;
  755. UserData = NULL;
  756. Fonts = NULL;
  757. FontGlobalScale = 1.0f;
  758. FontDefault = NULL;
  759. FontAllowUserScaling = false;
  760. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  761. // Advanced/subtle behaviors
  762. #ifdef __APPLE__
  763. OptMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
  764. #else
  765. OptMacOSXBehaviors = false;
  766. #endif
  767. OptCursorBlink = true;
  768. // Settings (User Functions)
  769. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  770. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  771. ClipboardUserData = NULL;
  772. ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
  773. ImeWindowHandle = NULL;
  774. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  775. RenderDrawListsFn = NULL;
  776. #endif
  777. // Input (NB: we already have memset zero the entire structure)
  778. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  779. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  780. MouseDragThreshold = 6.0f;
  781. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  782. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  783. for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
  784. }
  785. // Pass in translated ASCII characters for text input.
  786. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  787. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  788. void ImGuiIO::AddInputCharacter(ImWchar c)
  789. {
  790. const int n = ImStrlenW(InputCharacters);
  791. if (n + 1 < IM_ARRAYSIZE(InputCharacters))
  792. {
  793. InputCharacters[n] = c;
  794. InputCharacters[n+1] = '\0';
  795. }
  796. }
  797. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  798. {
  799. // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
  800. const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
  801. ImWchar wchars[wchars_buf_len];
  802. ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
  803. for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
  804. AddInputCharacter(wchars[i]);
  805. }
  806. //-----------------------------------------------------------------------------
  807. // HELPERS
  808. //-----------------------------------------------------------------------------
  809. #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
  810. #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
  811. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  812. {
  813. ImVec2 ap = p - a;
  814. ImVec2 ab_dir = b - a;
  815. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  816. if (dot < 0.0f)
  817. return a;
  818. float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
  819. if (dot > ab_len_sqr)
  820. return b;
  821. return a + ab_dir * dot / ab_len_sqr;
  822. }
  823. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  824. {
  825. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  826. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  827. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  828. return ((b1 == b2) && (b2 == b3));
  829. }
  830. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  831. {
  832. ImVec2 v0 = b - a;
  833. ImVec2 v1 = c - a;
  834. ImVec2 v2 = p - a;
  835. const float denom = v0.x * v1.y - v1.x * v0.y;
  836. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  837. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  838. out_u = 1.0f - out_v - out_w;
  839. }
  840. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  841. {
  842. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  843. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  844. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  845. float dist2_ab = ImLengthSqr(p - proj_ab);
  846. float dist2_bc = ImLengthSqr(p - proj_bc);
  847. float dist2_ca = ImLengthSqr(p - proj_ca);
  848. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  849. if (m == dist2_ab)
  850. return proj_ab;
  851. if (m == dist2_bc)
  852. return proj_bc;
  853. return proj_ca;
  854. }
  855. int ImStricmp(const char* str1, const char* str2)
  856. {
  857. int d;
  858. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  859. return d;
  860. }
  861. int ImStrnicmp(const char* str1, const char* str2, size_t count)
  862. {
  863. int d = 0;
  864. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  865. return d;
  866. }
  867. void ImStrncpy(char* dst, const char* src, size_t count)
  868. {
  869. if (count < 1) return;
  870. strncpy(dst, src, count);
  871. dst[count-1] = 0;
  872. }
  873. char* ImStrdup(const char *str)
  874. {
  875. size_t len = strlen(str) + 1;
  876. void* buf = ImGui::MemAlloc(len);
  877. return (char*)memcpy(buf, (const void*)str, len);
  878. }
  879. char* ImStrchrRange(const char* str, const char* str_end, char c)
  880. {
  881. for ( ; str < str_end; str++)
  882. if (*str == c)
  883. return (char*)str;
  884. return NULL;
  885. }
  886. int ImStrlenW(const ImWchar* str)
  887. {
  888. int n = 0;
  889. while (*str++) n++;
  890. return n;
  891. }
  892. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  893. {
  894. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  895. buf_mid_line--;
  896. return buf_mid_line;
  897. }
  898. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  899. {
  900. if (!needle_end)
  901. needle_end = needle + strlen(needle);
  902. const char un0 = (char)toupper(*needle);
  903. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  904. {
  905. if (toupper(*haystack) == un0)
  906. {
  907. const char* b = needle + 1;
  908. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  909. if (toupper(*a) != toupper(*b))
  910. break;
  911. if (b == needle_end)
  912. return haystack;
  913. }
  914. haystack++;
  915. }
  916. return NULL;
  917. }
  918. static const char* ImAtoi(const char* src, int* output)
  919. {
  920. int negative = 0;
  921. if (*src == '-') { negative = 1; src++; }
  922. if (*src == '+') { src++; }
  923. int v = 0;
  924. while (*src >= '0' && *src <= '9')
  925. v = (v * 10) + (*src++ - '0');
  926. *output = negative ? -v : v;
  927. return src;
  928. }
  929. // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  930. // 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.
  931. // B) When buf==NULL vsnprintf() will return the output size.
  932. #ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
  933. int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
  934. {
  935. va_list args;
  936. va_start(args, fmt);
  937. int w = vsnprintf(buf, buf_size, fmt, args);
  938. va_end(args);
  939. if (buf == NULL)
  940. return w;
  941. if (w == -1 || w >= (int)buf_size)
  942. w = (int)buf_size - 1;
  943. buf[w] = 0;
  944. return w;
  945. }
  946. int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
  947. {
  948. int w = vsnprintf(buf, buf_size, fmt, args);
  949. if (buf == NULL)
  950. return w;
  951. if (w == -1 || w >= (int)buf_size)
  952. w = (int)buf_size - 1;
  953. buf[w] = 0;
  954. return w;
  955. }
  956. #endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
  957. // Pass data_size==0 for zero-terminated strings
  958. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  959. ImU32 ImHash(const void* data, int data_size, ImU32 seed)
  960. {
  961. static ImU32 crc32_lut[256] = { 0 };
  962. if (!crc32_lut[1])
  963. {
  964. const ImU32 polynomial = 0xEDB88320;
  965. for (ImU32 i = 0; i < 256; i++)
  966. {
  967. ImU32 crc = i;
  968. for (ImU32 j = 0; j < 8; j++)
  969. crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
  970. crc32_lut[i] = crc;
  971. }
  972. }
  973. seed = ~seed;
  974. ImU32 crc = seed;
  975. const unsigned char* current = (const unsigned char*)data;
  976. if (data_size > 0)
  977. {
  978. // Known size
  979. while (data_size--)
  980. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
  981. }
  982. else
  983. {
  984. // Zero-terminated string
  985. while (unsigned char c = *current++)
  986. {
  987. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  988. // Because this syntax is rarely used we are optimizing for the common case.
  989. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  990. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
  991. if (c == '#' && current[0] == '#' && current[1] == '#')
  992. crc = seed;
  993. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  994. }
  995. }
  996. return ~crc;
  997. }
  998. //-----------------------------------------------------------------------------
  999. // ImText* helpers
  1000. //-----------------------------------------------------------------------------
  1001. // Convert UTF-8 to 32-bits character, process single character input.
  1002. // Based on stb_from_utf8() from github.com/nothings/stb/
  1003. // We handle UTF-8 decoding error by skipping forward.
  1004. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1005. {
  1006. unsigned int c = (unsigned int)-1;
  1007. const unsigned char* str = (const unsigned char*)in_text;
  1008. if (!(*str & 0x80))
  1009. {
  1010. c = (unsigned int)(*str++);
  1011. *out_char = c;
  1012. return 1;
  1013. }
  1014. if ((*str & 0xe0) == 0xc0)
  1015. {
  1016. *out_char = 0xFFFD; // will be invalid but not end of string
  1017. if (in_text_end && in_text_end - (const char*)str < 2) return 1;
  1018. if (*str < 0xc2) return 2;
  1019. c = (unsigned int)((*str++ & 0x1f) << 6);
  1020. if ((*str & 0xc0) != 0x80) return 2;
  1021. c += (*str++ & 0x3f);
  1022. *out_char = c;
  1023. return 2;
  1024. }
  1025. if ((*str & 0xf0) == 0xe0)
  1026. {
  1027. *out_char = 0xFFFD; // will be invalid but not end of string
  1028. if (in_text_end && in_text_end - (const char*)str < 3) return 1;
  1029. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
  1030. if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
  1031. c = (unsigned int)((*str++ & 0x0f) << 12);
  1032. if ((*str & 0xc0) != 0x80) return 3;
  1033. c += (unsigned int)((*str++ & 0x3f) << 6);
  1034. if ((*str & 0xc0) != 0x80) return 3;
  1035. c += (*str++ & 0x3f);
  1036. *out_char = c;
  1037. return 3;
  1038. }
  1039. if ((*str & 0xf8) == 0xf0)
  1040. {
  1041. *out_char = 0xFFFD; // will be invalid but not end of string
  1042. if (in_text_end && in_text_end - (const char*)str < 4) return 1;
  1043. if (*str > 0xf4) return 4;
  1044. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
  1045. if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
  1046. c = (unsigned int)((*str++ & 0x07) << 18);
  1047. if ((*str & 0xc0) != 0x80) return 4;
  1048. c += (unsigned int)((*str++ & 0x3f) << 12);
  1049. if ((*str & 0xc0) != 0x80) return 4;
  1050. c += (unsigned int)((*str++ & 0x3f) << 6);
  1051. if ((*str & 0xc0) != 0x80) return 4;
  1052. c += (*str++ & 0x3f);
  1053. // utf-8 encodings of values used in surrogate pairs are invalid
  1054. if ((c & 0xFFFFF800) == 0xD800) return 4;
  1055. *out_char = c;
  1056. return 4;
  1057. }
  1058. *out_char = 0;
  1059. return 0;
  1060. }
  1061. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1062. {
  1063. ImWchar* buf_out = buf;
  1064. ImWchar* buf_end = buf + buf_size;
  1065. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1066. {
  1067. unsigned int c;
  1068. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1069. if (c == 0)
  1070. break;
  1071. if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
  1072. *buf_out++ = (ImWchar)c;
  1073. }
  1074. *buf_out = 0;
  1075. if (in_text_remaining)
  1076. *in_text_remaining = in_text;
  1077. return (int)(buf_out - buf);
  1078. }
  1079. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1080. {
  1081. int char_count = 0;
  1082. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1083. {
  1084. unsigned int c;
  1085. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1086. if (c == 0)
  1087. break;
  1088. if (c < 0x10000)
  1089. char_count++;
  1090. }
  1091. return char_count;
  1092. }
  1093. // Based on stb_to_utf8() from github.com/nothings/stb/
  1094. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  1095. {
  1096. if (c < 0x80)
  1097. {
  1098. buf[0] = (char)c;
  1099. return 1;
  1100. }
  1101. if (c < 0x800)
  1102. {
  1103. if (buf_size < 2) return 0;
  1104. buf[0] = (char)(0xc0 + (c >> 6));
  1105. buf[1] = (char)(0x80 + (c & 0x3f));
  1106. return 2;
  1107. }
  1108. if (c >= 0xdc00 && c < 0xe000)
  1109. {
  1110. return 0;
  1111. }
  1112. if (c >= 0xd800 && c < 0xdc00)
  1113. {
  1114. if (buf_size < 4) return 0;
  1115. buf[0] = (char)(0xf0 + (c >> 18));
  1116. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1117. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1118. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1119. return 4;
  1120. }
  1121. //else if (c < 0x10000)
  1122. {
  1123. if (buf_size < 3) return 0;
  1124. buf[0] = (char)(0xe0 + (c >> 12));
  1125. buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
  1126. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1127. return 3;
  1128. }
  1129. }
  1130. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1131. {
  1132. if (c < 0x80) return 1;
  1133. if (c < 0x800) return 2;
  1134. if (c >= 0xdc00 && c < 0xe000) return 0;
  1135. if (c >= 0xd800 && c < 0xdc00) return 4;
  1136. return 3;
  1137. }
  1138. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1139. {
  1140. char* buf_out = buf;
  1141. const char* buf_end = buf + buf_size;
  1142. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1143. {
  1144. unsigned int c = (unsigned int)(*in_text++);
  1145. if (c < 0x80)
  1146. *buf_out++ = (char)c;
  1147. else
  1148. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
  1149. }
  1150. *buf_out = 0;
  1151. return (int)(buf_out - buf);
  1152. }
  1153. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1154. {
  1155. int bytes_count = 0;
  1156. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1157. {
  1158. unsigned int c = (unsigned int)(*in_text++);
  1159. if (c < 0x80)
  1160. bytes_count++;
  1161. else
  1162. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1163. }
  1164. return bytes_count;
  1165. }
  1166. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1167. {
  1168. float s = 1.0f/255.0f;
  1169. return ImVec4(
  1170. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1171. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1172. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1173. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1174. }
  1175. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1176. {
  1177. ImU32 out;
  1178. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1179. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1180. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1181. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1182. return out;
  1183. }
  1184. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  1185. {
  1186. ImGuiStyle& style = GImGui->Style;
  1187. ImVec4 c = style.Colors[idx];
  1188. c.w *= style.Alpha * alpha_mul;
  1189. return ColorConvertFloat4ToU32(c);
  1190. }
  1191. ImU32 ImGui::GetColorU32(const ImVec4& col)
  1192. {
  1193. ImGuiStyle& style = GImGui->Style;
  1194. ImVec4 c = col;
  1195. c.w *= style.Alpha;
  1196. return ColorConvertFloat4ToU32(c);
  1197. }
  1198. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  1199. {
  1200. ImGuiStyle& style = GImGui->Style;
  1201. return style.Colors[idx];
  1202. }
  1203. ImU32 ImGui::GetColorU32(ImU32 col)
  1204. {
  1205. float style_alpha = GImGui->Style.Alpha;
  1206. if (style_alpha >= 1.0f)
  1207. return col;
  1208. int a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  1209. a = (int)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  1210. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  1211. }
  1212. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1213. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1214. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1215. {
  1216. float K = 0.f;
  1217. if (g < b)
  1218. {
  1219. ImSwap(g, b);
  1220. K = -1.f;
  1221. }
  1222. if (r < g)
  1223. {
  1224. ImSwap(r, g);
  1225. K = -2.f / 6.f - K;
  1226. }
  1227. const float chroma = r - (g < b ? g : b);
  1228. out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f));
  1229. out_s = chroma / (r + 1e-20f);
  1230. out_v = r;
  1231. }
  1232. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1233. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1234. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1235. {
  1236. if (s == 0.0f)
  1237. {
  1238. // gray
  1239. out_r = out_g = out_b = v;
  1240. return;
  1241. }
  1242. h = fmodf(h, 1.0f) / (60.0f/360.0f);
  1243. int i = (int)h;
  1244. float f = h - (float)i;
  1245. float p = v * (1.0f - s);
  1246. float q = v * (1.0f - s * f);
  1247. float t = v * (1.0f - s * (1.0f - f));
  1248. switch (i)
  1249. {
  1250. case 0: out_r = v; out_g = t; out_b = p; break;
  1251. case 1: out_r = q; out_g = v; out_b = p; break;
  1252. case 2: out_r = p; out_g = v; out_b = t; break;
  1253. case 3: out_r = p; out_g = q; out_b = v; break;
  1254. case 4: out_r = t; out_g = p; out_b = v; break;
  1255. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1256. }
  1257. }
  1258. FILE* ImFileOpen(const char* filename, const char* mode)
  1259. {
  1260. #if defined(_WIN32) && !defined(__CYGWIN__)
  1261. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
  1262. const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
  1263. const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
  1264. ImVector<ImWchar> buf;
  1265. buf.resize(filename_wsize + mode_wsize);
  1266. ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
  1267. ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
  1268. return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
  1269. #else
  1270. return fopen(filename, mode);
  1271. #endif
  1272. }
  1273. // Load file content into memory
  1274. // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
  1275. void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
  1276. {
  1277. IM_ASSERT(filename && file_open_mode);
  1278. if (out_file_size)
  1279. *out_file_size = 0;
  1280. FILE* f;
  1281. if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
  1282. return NULL;
  1283. long file_size_signed;
  1284. if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
  1285. {
  1286. fclose(f);
  1287. return NULL;
  1288. }
  1289. int file_size = (int)file_size_signed;
  1290. void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
  1291. if (file_data == NULL)
  1292. {
  1293. fclose(f);
  1294. return NULL;
  1295. }
  1296. if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size)
  1297. {
  1298. fclose(f);
  1299. ImGui::MemFree(file_data);
  1300. return NULL;
  1301. }
  1302. if (padding_bytes > 0)
  1303. memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
  1304. fclose(f);
  1305. if (out_file_size)
  1306. *out_file_size = file_size;
  1307. return file_data;
  1308. }
  1309. //-----------------------------------------------------------------------------
  1310. // ImGuiStorage
  1311. // Helper: Key->value storage
  1312. //-----------------------------------------------------------------------------
  1313. // std::lower_bound but without the bullshit
  1314. static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
  1315. {
  1316. ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
  1317. ImVector<ImGuiStorage::Pair>::iterator last = data.end();
  1318. size_t count = (size_t)(last - first);
  1319. while (count > 0)
  1320. {
  1321. size_t count2 = count >> 1;
  1322. ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
  1323. if (mid->key < key)
  1324. {
  1325. first = ++mid;
  1326. count -= count2 + 1;
  1327. }
  1328. else
  1329. {
  1330. count = count2;
  1331. }
  1332. }
  1333. return first;
  1334. }
  1335. // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
  1336. void ImGuiStorage::BuildSortByKey()
  1337. {
  1338. struct StaticFunc
  1339. {
  1340. static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
  1341. {
  1342. // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
  1343. if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
  1344. if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
  1345. return 0;
  1346. }
  1347. };
  1348. if (Data.Size > 1)
  1349. qsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
  1350. }
  1351. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1352. {
  1353. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1354. if (it == Data.end() || it->key != key)
  1355. return default_val;
  1356. return it->val_i;
  1357. }
  1358. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1359. {
  1360. return GetInt(key, default_val ? 1 : 0) != 0;
  1361. }
  1362. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1363. {
  1364. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1365. if (it == Data.end() || it->key != key)
  1366. return default_val;
  1367. return it->val_f;
  1368. }
  1369. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1370. {
  1371. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1372. if (it == Data.end() || it->key != key)
  1373. return NULL;
  1374. return it->val_p;
  1375. }
  1376. // 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.
  1377. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1378. {
  1379. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1380. if (it == Data.end() || it->key != key)
  1381. it = Data.insert(it, Pair(key, default_val));
  1382. return &it->val_i;
  1383. }
  1384. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1385. {
  1386. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1387. }
  1388. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1389. {
  1390. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1391. if (it == Data.end() || it->key != key)
  1392. it = Data.insert(it, Pair(key, default_val));
  1393. return &it->val_f;
  1394. }
  1395. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1396. {
  1397. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1398. if (it == Data.end() || it->key != key)
  1399. it = Data.insert(it, Pair(key, default_val));
  1400. return &it->val_p;
  1401. }
  1402. // 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)
  1403. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1404. {
  1405. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1406. if (it == Data.end() || it->key != key)
  1407. {
  1408. Data.insert(it, Pair(key, val));
  1409. return;
  1410. }
  1411. it->val_i = val;
  1412. }
  1413. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1414. {
  1415. SetInt(key, val ? 1 : 0);
  1416. }
  1417. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1418. {
  1419. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1420. if (it == Data.end() || it->key != key)
  1421. {
  1422. Data.insert(it, Pair(key, val));
  1423. return;
  1424. }
  1425. it->val_f = val;
  1426. }
  1427. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1428. {
  1429. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1430. if (it == Data.end() || it->key != key)
  1431. {
  1432. Data.insert(it, Pair(key, val));
  1433. return;
  1434. }
  1435. it->val_p = val;
  1436. }
  1437. void ImGuiStorage::SetAllInt(int v)
  1438. {
  1439. for (int i = 0; i < Data.Size; i++)
  1440. Data[i].val_i = v;
  1441. }
  1442. //-----------------------------------------------------------------------------
  1443. // ImGuiTextFilter
  1444. //-----------------------------------------------------------------------------
  1445. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1446. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1447. {
  1448. if (default_filter)
  1449. {
  1450. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1451. Build();
  1452. }
  1453. else
  1454. {
  1455. InputBuf[0] = 0;
  1456. CountGrep = 0;
  1457. }
  1458. }
  1459. bool ImGuiTextFilter::Draw(const char* label, float width)
  1460. {
  1461. if (width != 0.0f)
  1462. ImGui::PushItemWidth(width);
  1463. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1464. if (width != 0.0f)
  1465. ImGui::PopItemWidth();
  1466. if (value_changed)
  1467. Build();
  1468. return value_changed;
  1469. }
  1470. void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
  1471. {
  1472. out.resize(0);
  1473. const char* wb = b;
  1474. const char* we = wb;
  1475. while (we < e)
  1476. {
  1477. if (*we == separator)
  1478. {
  1479. out.push_back(TextRange(wb, we));
  1480. wb = we + 1;
  1481. }
  1482. we++;
  1483. }
  1484. if (wb != we)
  1485. out.push_back(TextRange(wb, we));
  1486. }
  1487. void ImGuiTextFilter::Build()
  1488. {
  1489. Filters.resize(0);
  1490. TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
  1491. input_range.split(',', Filters);
  1492. CountGrep = 0;
  1493. for (int i = 0; i != Filters.Size; i++)
  1494. {
  1495. Filters[i].trim_blanks();
  1496. if (Filters[i].empty())
  1497. continue;
  1498. if (Filters[i].front() != '-')
  1499. CountGrep += 1;
  1500. }
  1501. }
  1502. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1503. {
  1504. if (Filters.empty())
  1505. return true;
  1506. if (text == NULL)
  1507. text = "";
  1508. for (int i = 0; i != Filters.Size; i++)
  1509. {
  1510. const TextRange& f = Filters[i];
  1511. if (f.empty())
  1512. continue;
  1513. if (f.front() == '-')
  1514. {
  1515. // Subtract
  1516. if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
  1517. return false;
  1518. }
  1519. else
  1520. {
  1521. // Grep
  1522. if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
  1523. return true;
  1524. }
  1525. }
  1526. // Implicit * grep
  1527. if (CountGrep == 0)
  1528. return true;
  1529. return false;
  1530. }
  1531. //-----------------------------------------------------------------------------
  1532. // ImGuiTextBuffer
  1533. //-----------------------------------------------------------------------------
  1534. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1535. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1536. #ifndef va_copy
  1537. #define va_copy(dest, src) (dest = src)
  1538. #endif
  1539. // Helper: Text buffer for logging/accumulating text
  1540. void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
  1541. {
  1542. va_list args_copy;
  1543. va_copy(args_copy, args);
  1544. int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1545. if (len <= 0)
  1546. return;
  1547. const int write_off = Buf.Size;
  1548. const int needed_sz = write_off + len;
  1549. if (write_off + len >= Buf.Capacity)
  1550. {
  1551. int double_capacity = Buf.Capacity * 2;
  1552. Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
  1553. }
  1554. Buf.resize(needed_sz);
  1555. ImFormatStringV(&Buf[write_off - 1], len + 1, fmt, args_copy);
  1556. }
  1557. void ImGuiTextBuffer::appendf(const char* fmt, ...)
  1558. {
  1559. va_list args;
  1560. va_start(args, fmt);
  1561. appendfv(fmt, args);
  1562. va_end(args);
  1563. }
  1564. //-----------------------------------------------------------------------------
  1565. // ImGuiSimpleColumns (internal use only)
  1566. //-----------------------------------------------------------------------------
  1567. ImGuiMenuColumns::ImGuiMenuColumns()
  1568. {
  1569. Count = 0;
  1570. Spacing = Width = NextWidth = 0.0f;
  1571. memset(Pos, 0, sizeof(Pos));
  1572. memset(NextWidths, 0, sizeof(NextWidths));
  1573. }
  1574. void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
  1575. {
  1576. IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
  1577. Count = count;
  1578. Width = NextWidth = 0.0f;
  1579. Spacing = spacing;
  1580. if (clear) memset(NextWidths, 0, sizeof(NextWidths));
  1581. for (int i = 0; i < Count; i++)
  1582. {
  1583. if (i > 0 && NextWidths[i] > 0.0f)
  1584. Width += Spacing;
  1585. Pos[i] = (float)(int)Width;
  1586. Width += NextWidths[i];
  1587. NextWidths[i] = 0.0f;
  1588. }
  1589. }
  1590. float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
  1591. {
  1592. NextWidth = 0.0f;
  1593. NextWidths[0] = ImMax(NextWidths[0], w0);
  1594. NextWidths[1] = ImMax(NextWidths[1], w1);
  1595. NextWidths[2] = ImMax(NextWidths[2], w2);
  1596. for (int i = 0; i < 3; i++)
  1597. NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
  1598. return ImMax(Width, NextWidth);
  1599. }
  1600. float ImGuiMenuColumns::CalcExtraSpace(float avail_w)
  1601. {
  1602. return ImMax(0.0f, avail_w - Width);
  1603. }
  1604. //-----------------------------------------------------------------------------
  1605. // ImGuiListClipper
  1606. //-----------------------------------------------------------------------------
  1607. static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
  1608. {
  1609. // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor.
  1610. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
  1611. // The clipper should probably have a 4th step to display the last item in a regular manner.
  1612. ImGui::SetCursorPosY(pos_y);
  1613. ImGuiWindow* window = ImGui::GetCurrentWindow();
  1614. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage.
  1615. window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
  1616. if (window->DC.ColumnsSet)
  1617. window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  1618. }
  1619. // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
  1620. // Use case B: Begin() called from constructor with items_height>0
  1621. // 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.
  1622. void ImGuiListClipper::Begin(int count, float items_height)
  1623. {
  1624. StartPosY = ImGui::GetCursorPosY();
  1625. ItemsHeight = items_height;
  1626. ItemsCount = count;
  1627. StepNo = 0;
  1628. DisplayEnd = DisplayStart = -1;
  1629. if (ItemsHeight > 0.0f)
  1630. {
  1631. ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
  1632. if (DisplayStart > 0)
  1633. SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
  1634. StepNo = 2;
  1635. }
  1636. }
  1637. void ImGuiListClipper::End()
  1638. {
  1639. if (ItemsCount < 0)
  1640. return;
  1641. // 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.
  1642. if (ItemsCount < INT_MAX)
  1643. SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
  1644. ItemsCount = -1;
  1645. StepNo = 3;
  1646. }
  1647. bool ImGuiListClipper::Step()
  1648. {
  1649. if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
  1650. {
  1651. ItemsCount = -1;
  1652. return false;
  1653. }
  1654. 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.
  1655. {
  1656. DisplayStart = 0;
  1657. DisplayEnd = 1;
  1658. StartPosY = ImGui::GetCursorPosY();
  1659. StepNo = 1;
  1660. return true;
  1661. }
  1662. 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.
  1663. {
  1664. if (ItemsCount == 1) { ItemsCount = -1; return false; }
  1665. float items_height = ImGui::GetCursorPosY() - StartPosY;
  1666. IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
  1667. Begin(ItemsCount-1, items_height);
  1668. DisplayStart++;
  1669. DisplayEnd++;
  1670. StepNo = 3;
  1671. return true;
  1672. }
  1673. 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.
  1674. {
  1675. IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
  1676. StepNo = 3;
  1677. return true;
  1678. }
  1679. 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.
  1680. End();
  1681. return false;
  1682. }
  1683. //-----------------------------------------------------------------------------
  1684. // ImGuiWindow
  1685. //-----------------------------------------------------------------------------
  1686. ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
  1687. {
  1688. Name = ImStrdup(name);
  1689. ID = ImHash(name, 0);
  1690. IDStack.push_back(ID);
  1691. Flags = FlagsPreviousFrame = 0;
  1692. Viewport = NULL;
  1693. ViewportId = 0;
  1694. ViewportPlatformPos = ImVec2(FLT_MAX, FLT_MAX);
  1695. PosFloat = Pos = ImVec2(0.0f, 0.0f);
  1696. Size = SizeFull = ImVec2(0.0f, 0.0f);
  1697. SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  1698. WindowPadding = ImVec2(0.0f, 0.0f);
  1699. WindowRounding = 0.0f;
  1700. WindowBorderSize = 0.0f;
  1701. MoveId = GetID("#MOVE");
  1702. ChildId = 0;
  1703. Scroll = ImVec2(0.0f, 0.0f);
  1704. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  1705. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  1706. ScrollbarX = ScrollbarY = false;
  1707. ScrollbarSizes = ImVec2(0.0f, 0.0f);
  1708. Active = WasActive = false;
  1709. WriteAccessed = false;
  1710. Collapsed = false;
  1711. CollapseToggleWanted = false;
  1712. SkipItems = false;
  1713. Appearing = false;
  1714. CloseButton = false;
  1715. BeginOrderWithinParent = -1;
  1716. BeginOrderWithinContext = -1;
  1717. BeginCount = 0;
  1718. PopupId = 0;
  1719. AutoFitFramesX = AutoFitFramesY = -1;
  1720. AutoFitOnlyGrows = false;
  1721. AutoFitChildAxises = 0x00;
  1722. AutoPosLastDirection = ImGuiDir_None;
  1723. HiddenFrames = 0;
  1724. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  1725. SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
  1726. LastFrameActive = -1;
  1727. ItemWidthDefault = 0.0f;
  1728. FontWindowScale = FontDpiScale = 1.0f;
  1729. DrawList = IM_NEW(ImDrawList)(&context->DrawListSharedData);
  1730. DrawList->_OwnerName = Name;
  1731. ParentWindow = NULL;
  1732. RootWindow = NULL;
  1733. RootWindowForTitleBarHighlight = NULL;
  1734. RootWindowForTabbing = NULL;
  1735. RootWindowForNav = NULL;
  1736. NavLastIds[0] = NavLastIds[1] = 0;
  1737. NavRectRel[0] = NavRectRel[1] = ImRect();
  1738. NavLastChildNavWindow = NULL;
  1739. FocusIdxAllCounter = FocusIdxTabCounter = -1;
  1740. FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
  1741. FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
  1742. }
  1743. ImGuiWindow::~ImGuiWindow()
  1744. {
  1745. IM_DELETE(DrawList);
  1746. IM_DELETE(Name);
  1747. for (int i = 0; i != ColumnsStorage.Size; i++)
  1748. ColumnsStorage[i].~ImGuiColumnsSet();
  1749. }
  1750. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  1751. {
  1752. ImGuiID seed = IDStack.back();
  1753. ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1754. ImGui::KeepAliveID(id);
  1755. return id;
  1756. }
  1757. ImGuiID ImGuiWindow::GetID(const void* ptr)
  1758. {
  1759. ImGuiID seed = IDStack.back();
  1760. ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
  1761. ImGui::KeepAliveID(id);
  1762. return id;
  1763. }
  1764. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  1765. {
  1766. ImGuiID seed = IDStack.back();
  1767. return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1768. }
  1769. // This is only used in rare/specific situations to manufacture an ID out of nowhere.
  1770. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
  1771. {
  1772. ImGuiID seed = IDStack.back();
  1773. 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) };
  1774. ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed);
  1775. ImGui::KeepAliveID(id);
  1776. return id;
  1777. }
  1778. //-----------------------------------------------------------------------------
  1779. // Internal API exposed in imgui_internal.h
  1780. //-----------------------------------------------------------------------------
  1781. static void SetCurrentWindow(ImGuiWindow* window)
  1782. {
  1783. ImGuiContext& g = *GImGui;
  1784. g.CurrentWindow = window;
  1785. if (window)
  1786. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  1787. }
  1788. static void SetNavID(ImGuiID id, int nav_layer)
  1789. {
  1790. ImGuiContext& g = *GImGui;
  1791. IM_ASSERT(g.NavWindow);
  1792. IM_ASSERT(nav_layer == 0 || nav_layer == 1);
  1793. g.NavId = id;
  1794. g.NavWindow->NavLastIds[nav_layer] = id;
  1795. }
  1796. static void SetNavIDAndMoveMouse(ImGuiID id, int nav_layer, const ImRect& rect_rel)
  1797. {
  1798. ImGuiContext& g = *GImGui;
  1799. SetNavID(id, nav_layer);
  1800. g.NavWindow->NavRectRel[nav_layer] = rect_rel;
  1801. g.NavMousePosDirty = true;
  1802. g.NavDisableHighlight = false;
  1803. g.NavDisableMouseHover = true;
  1804. }
  1805. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  1806. {
  1807. ImGuiContext& g = *GImGui;
  1808. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  1809. if (g.ActiveIdIsJustActivated)
  1810. g.ActiveIdTimer = 0.0f;
  1811. g.ActiveId = id;
  1812. g.ActiveIdAllowNavDirFlags = 0;
  1813. g.ActiveIdAllowOverlap = false;
  1814. g.ActiveIdWindow = window;
  1815. if (id)
  1816. {
  1817. g.ActiveIdIsAlive = true;
  1818. g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
  1819. }
  1820. }
  1821. ImGuiID ImGui::GetActiveID()
  1822. {
  1823. ImGuiContext& g = *GImGui;
  1824. return g.ActiveId;
  1825. }
  1826. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
  1827. {
  1828. ImGuiContext& g = *GImGui;
  1829. IM_ASSERT(id != 0);
  1830. // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
  1831. const int nav_layer = window->DC.NavLayerCurrent;
  1832. if (g.NavWindow != window)
  1833. g.NavInitRequest = false;
  1834. g.NavId = id;
  1835. g.NavWindow = window;
  1836. g.NavLayer = nav_layer;
  1837. window->NavLastIds[nav_layer] = id;
  1838. if (window->DC.LastItemId == id)
  1839. window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
  1840. if (g.ActiveIdSource == ImGuiInputSource_Nav)
  1841. g.NavDisableMouseHover = true;
  1842. else
  1843. g.NavDisableHighlight = true;
  1844. }
  1845. void ImGui::ClearActiveID()
  1846. {
  1847. SetActiveID(0, NULL);
  1848. }
  1849. void ImGui::SetHoveredID(ImGuiID id)
  1850. {
  1851. ImGuiContext& g = *GImGui;
  1852. g.HoveredId = id;
  1853. g.HoveredIdAllowOverlap = false;
  1854. g.HoveredIdTimer = (id != 0 && g.HoveredIdPreviousFrame == id) ? (g.HoveredIdTimer + g.IO.DeltaTime) : 0.0f;
  1855. }
  1856. ImGuiID ImGui::GetHoveredID()
  1857. {
  1858. ImGuiContext& g = *GImGui;
  1859. return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
  1860. }
  1861. void ImGui::KeepAliveID(ImGuiID id)
  1862. {
  1863. ImGuiContext& g = *GImGui;
  1864. if (g.ActiveId == id)
  1865. g.ActiveIdIsAlive = true;
  1866. }
  1867. static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
  1868. {
  1869. // An active popup disable hovering on other windows (apart from its own children)
  1870. // FIXME-OPT: This could be cached/stored within the window.
  1871. ImGuiContext& g = *GImGui;
  1872. if (g.NavWindow)
  1873. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
  1874. if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
  1875. {
  1876. // For the purpose of those flags we differentiate "standard popup" from "modal popup"
  1877. // NB: The order of those two tests is important because Modal windows are also Popups.
  1878. if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
  1879. return false;
  1880. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  1881. return false;
  1882. }
  1883. // Filter by viewport
  1884. if (window->Viewport != g.MouseViewport)
  1885. return false;
  1886. return true;
  1887. }
  1888. // Advance cursor given item size for layout.
  1889. void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
  1890. {
  1891. ImGuiContext& g = *GImGui;
  1892. ImGuiWindow* window = g.CurrentWindow;
  1893. if (window->SkipItems)
  1894. return;
  1895. // Always align ourselves on pixel boundaries
  1896. const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
  1897. const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
  1898. //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]
  1899. window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
  1900. window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y));
  1901. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  1902. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
  1903. //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
  1904. window->DC.PrevLineHeight = line_height;
  1905. window->DC.PrevLineTextBaseOffset = text_base_offset;
  1906. window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
  1907. // Horizontal layout mode
  1908. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  1909. SameLine();
  1910. }
  1911. void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
  1912. {
  1913. ItemSize(bb.GetSize(), text_offset_y);
  1914. }
  1915. static ImGuiDir NavScoreItemGetQuadrant(float dx, float dy)
  1916. {
  1917. if (fabsf(dx) > fabsf(dy))
  1918. return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
  1919. return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
  1920. }
  1921. static float NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
  1922. {
  1923. if (a1 < b0)
  1924. return a1 - b0;
  1925. if (b1 < a0)
  1926. return a0 - b1;
  1927. return 0.0f;
  1928. }
  1929. // Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
  1930. static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
  1931. {
  1932. ImGuiContext& g = *GImGui;
  1933. ImGuiWindow* window = g.CurrentWindow;
  1934. if (g.NavLayer != window->DC.NavLayerCurrent)
  1935. return false;
  1936. 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)
  1937. g.NavScoringCount++;
  1938. // We perform scoring on items bounding box clipped by their parent window on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
  1939. if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
  1940. {
  1941. cand.Min.y = ImClamp(cand.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y);
  1942. cand.Max.y = ImClamp(cand.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y);
  1943. }
  1944. else
  1945. {
  1946. cand.Min.x = ImClamp(cand.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
  1947. cand.Max.x = ImClamp(cand.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
  1948. }
  1949. // Compute distance between boxes
  1950. // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
  1951. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
  1952. 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
  1953. if (dby != 0.0f && dbx != 0.0f)
  1954. dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
  1955. float dist_box = fabsf(dbx) + fabsf(dby);
  1956. // 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)
  1957. float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
  1958. float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
  1959. float dist_center = fabsf(dcx) + fabsf(dcy); // L1 metric (need this for our connectedness guarantee)
  1960. // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
  1961. ImGuiDir quadrant;
  1962. float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
  1963. if (dbx != 0.0f || dby != 0.0f)
  1964. {
  1965. // For non-overlapping boxes, use distance between boxes
  1966. dax = dbx;
  1967. day = dby;
  1968. dist_axial = dist_box;
  1969. quadrant = NavScoreItemGetQuadrant(dbx, dby);
  1970. }
  1971. else if (dcx != 0.0f || dcy != 0.0f)
  1972. {
  1973. // For overlapping boxes with different centers, use distance between centers
  1974. dax = dcx;
  1975. day = dcy;
  1976. dist_axial = dist_center;
  1977. quadrant = NavScoreItemGetQuadrant(dcx, dcy);
  1978. }
  1979. else
  1980. {
  1981. // 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)
  1982. quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
  1983. }
  1984. #if IMGUI_DEBUG_NAV_SCORING
  1985. char buf[128];
  1986. if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max))
  1987. {
  1988. 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]);
  1989. g.OverlayDrawList.AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
  1990. g.OverlayDrawList.AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
  1991. g.OverlayDrawList.AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
  1992. g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
  1993. }
  1994. else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
  1995. {
  1996. if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
  1997. if (quadrant == g.NavMoveDir)
  1998. {
  1999. ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
  2000. g.OverlayDrawList.AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
  2001. g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
  2002. }
  2003. }
  2004. #endif
  2005. // Is it in the quadrant we're interesting in moving to?
  2006. bool new_best = false;
  2007. if (quadrant == g.NavMoveDir)
  2008. {
  2009. // Does it beat the current best candidate?
  2010. if (dist_box < result->DistBox)
  2011. {
  2012. result->DistBox = dist_box;
  2013. result->DistCenter = dist_center;
  2014. return true;
  2015. }
  2016. if (dist_box == result->DistBox)
  2017. {
  2018. // Try using distance between center points to break ties
  2019. if (dist_center < result->DistCenter)
  2020. {
  2021. result->DistCenter = dist_center;
  2022. new_best = true;
  2023. }
  2024. else if (dist_center == result->DistCenter)
  2025. {
  2026. // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
  2027. // (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),
  2028. // 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.
  2029. if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
  2030. new_best = true;
  2031. }
  2032. }
  2033. }
  2034. // 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
  2035. // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
  2036. // 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.
  2037. // 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.
  2038. // Disabling it may however lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
  2039. if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
  2040. if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
  2041. 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))
  2042. {
  2043. result->DistAxial = dist_axial;
  2044. new_best = true;
  2045. }
  2046. return new_best;
  2047. }
  2048. static void NavSaveLastChildNavWindow(ImGuiWindow* child_window)
  2049. {
  2050. ImGuiWindow* parent_window = child_window;
  2051. while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  2052. parent_window = parent_window->ParentWindow;
  2053. if (parent_window && parent_window != child_window)
  2054. parent_window->NavLastChildNavWindow = child_window;
  2055. }
  2056. // Call when we are expected to land on Layer 0 after FocusWindow()
  2057. static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window)
  2058. {
  2059. return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
  2060. }
  2061. static void NavRestoreLayer(int layer)
  2062. {
  2063. ImGuiContext& g = *GImGui;
  2064. g.NavLayer = layer;
  2065. if (layer == 0)
  2066. g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);
  2067. if (layer == 0 && g.NavWindow->NavLastIds[0] != 0)
  2068. SetNavIDAndMoveMouse(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]);
  2069. else
  2070. ImGui::NavInitWindow(g.NavWindow, true);
  2071. }
  2072. static inline void NavUpdateAnyRequestFlag()
  2073. {
  2074. ImGuiContext& g = *GImGui;
  2075. g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || IMGUI_DEBUG_NAV_SCORING;
  2076. }
  2077. static bool NavMoveRequestButNoResultYet()
  2078. {
  2079. ImGuiContext& g = *GImGui;
  2080. return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
  2081. }
  2082. void ImGui::NavMoveRequestCancel()
  2083. {
  2084. ImGuiContext& g = *GImGui;
  2085. g.NavMoveRequest = false;
  2086. NavUpdateAnyRequestFlag();
  2087. }
  2088. // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
  2089. static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
  2090. {
  2091. ImGuiContext& g = *GImGui;
  2092. //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.
  2093. // return;
  2094. const ImGuiItemFlags item_flags = window->DC.ItemFlags;
  2095. const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
  2096. if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
  2097. {
  2098. // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
  2099. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
  2100. {
  2101. g.NavInitResultId = id;
  2102. g.NavInitResultRectRel = nav_bb_rel;
  2103. }
  2104. if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
  2105. {
  2106. g.NavInitRequest = false; // Found a match, clear request
  2107. NavUpdateAnyRequestFlag();
  2108. }
  2109. }
  2110. // Scoring for navigation
  2111. if (g.NavId != id && !(item_flags & ImGuiItemFlags_NoNav))
  2112. {
  2113. ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  2114. #if IMGUI_DEBUG_NAV_SCORING
  2115. // [DEBUG] Score all items in NavWindow at all times
  2116. if (!g.NavMoveRequest)
  2117. g.NavMoveDir = g.NavMoveDirLast;
  2118. bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
  2119. #else
  2120. bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
  2121. #endif
  2122. if (new_best)
  2123. {
  2124. result->ID = id;
  2125. result->ParentID = window->IDStack.back();
  2126. result->Window = window;
  2127. result->RectRel = nav_bb_rel;
  2128. }
  2129. }
  2130. // Update window-relative bounding box of navigated item
  2131. if (g.NavId == id)
  2132. {
  2133. g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
  2134. g.NavLayer = window->DC.NavLayerCurrent;
  2135. g.NavIdIsAlive = true;
  2136. g.NavIdTabCounter = window->FocusIdxTabCounter;
  2137. window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
  2138. }
  2139. }
  2140. // Declare item bounding box for clipping and interaction.
  2141. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  2142. // declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
  2143. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
  2144. {
  2145. ImGuiContext& g = *GImGui;
  2146. ImGuiWindow* window = g.CurrentWindow;
  2147. if (id != 0)
  2148. {
  2149. // Navigation processing runs prior to clipping early-out
  2150. // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
  2151. // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
  2152. // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
  2153. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
  2154. window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
  2155. if (g.NavId == id || g.NavAnyRequest)
  2156. if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
  2157. if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
  2158. NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
  2159. }
  2160. window->DC.LastItemId = id;
  2161. window->DC.LastItemRect = bb;
  2162. window->DC.LastItemStatusFlags = 0;
  2163. // Clipping test
  2164. const bool is_clipped = IsClippedEx(bb, id, false);
  2165. if (is_clipped)
  2166. return false;
  2167. //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
  2168. // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
  2169. if (IsMouseHoveringRect(bb.Min, bb.Max))
  2170. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
  2171. return true;
  2172. }
  2173. // This is roughly matching the behavior of internal-facing ItemHoverable()
  2174. // - 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()
  2175. // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
  2176. bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
  2177. {
  2178. ImGuiContext& g = *GImGui;
  2179. ImGuiWindow* window = g.CurrentWindow;
  2180. if (g.NavDisableMouseHover && !g.NavDisableHighlight)
  2181. return IsItemFocused();
  2182. // Test for bounding box overlap, as updated as ItemAdd()
  2183. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  2184. return false;
  2185. IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
  2186. // Test if we are hovering the right window (our window could be behind another window)
  2187. // [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.
  2188. // 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.
  2189. //if (g.HoveredWindow != window)
  2190. // return false;
  2191. if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
  2192. return false;
  2193. // Test if another item is active (e.g. being dragged)
  2194. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  2195. if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
  2196. return false;
  2197. // Test if interactions on this window are blocked by an active popup or modal
  2198. if (!IsWindowContentHoverable(window, flags))
  2199. return false;
  2200. // Test if the item is disabled
  2201. if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
  2202. return false;
  2203. // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case.
  2204. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
  2205. return false;
  2206. return true;
  2207. }
  2208. // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
  2209. bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
  2210. {
  2211. ImGuiContext& g = *GImGui;
  2212. if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
  2213. return false;
  2214. ImGuiWindow* window = g.CurrentWindow;
  2215. if (g.HoveredWindow != window)
  2216. return false;
  2217. if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
  2218. return false;
  2219. if (!IsMouseHoveringRect(bb.Min, bb.Max))
  2220. return false;
  2221. if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_Default))
  2222. return false;
  2223. if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
  2224. return false;
  2225. SetHoveredID(id);
  2226. return true;
  2227. }
  2228. bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
  2229. {
  2230. ImGuiContext& g = *GImGui;
  2231. ImGuiWindow* window = g.CurrentWindow;
  2232. if (!bb.Overlaps(window->ClipRect))
  2233. if (id == 0 || id != g.ActiveId)
  2234. if (clip_even_when_logged || !g.LogEnabled)
  2235. return true;
  2236. return false;
  2237. }
  2238. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
  2239. {
  2240. ImGuiContext& g = *GImGui;
  2241. const bool allow_keyboard_focus = (window->DC.ItemFlags & (ImGuiItemFlags_AllowKeyboardFocus | ImGuiItemFlags_Disabled)) == ImGuiItemFlags_AllowKeyboardFocus;
  2242. window->FocusIdxAllCounter++;
  2243. if (allow_keyboard_focus)
  2244. window->FocusIdxTabCounter++;
  2245. // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
  2246. // Note that we can always TAB out of a widget that doesn't allow tabbing in.
  2247. if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
  2248. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
  2249. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
  2250. return true;
  2251. if (allow_keyboard_focus && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
  2252. {
  2253. g.NavJustTabbedId = id;
  2254. return true;
  2255. }
  2256. return false;
  2257. }
  2258. void ImGui::FocusableItemUnregister(ImGuiWindow* window)
  2259. {
  2260. window->FocusIdxAllCounter--;
  2261. window->FocusIdxTabCounter--;
  2262. }
  2263. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
  2264. {
  2265. ImGuiContext& g = *GImGui;
  2266. ImVec2 content_max;
  2267. if (size.x < 0.0f || size.y < 0.0f)
  2268. content_max = g.CurrentWindow->Pos + GetContentRegionMax();
  2269. if (size.x <= 0.0f)
  2270. size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
  2271. if (size.y <= 0.0f)
  2272. size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
  2273. return size;
  2274. }
  2275. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  2276. {
  2277. if (wrap_pos_x < 0.0f)
  2278. return 0.0f;
  2279. ImGuiWindow* window = GetCurrentWindowRead();
  2280. if (wrap_pos_x == 0.0f)
  2281. wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
  2282. else if (wrap_pos_x > 0.0f)
  2283. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  2284. return ImMax(wrap_pos_x - pos.x, 1.0f);
  2285. }
  2286. //-----------------------------------------------------------------------------
  2287. void* ImGui::MemAlloc(size_t sz)
  2288. {
  2289. GImAllocatorActiveAllocationsCount++;
  2290. return GImAllocatorAllocFunc(sz, GImAllocatorUserData);
  2291. }
  2292. void ImGui::MemFree(void* ptr)
  2293. {
  2294. if (ptr) GImAllocatorActiveAllocationsCount--;
  2295. return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
  2296. }
  2297. const char* ImGui::GetClipboardText()
  2298. {
  2299. return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
  2300. }
  2301. void ImGui::SetClipboardText(const char* text)
  2302. {
  2303. if (GImGui->IO.SetClipboardTextFn)
  2304. GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
  2305. }
  2306. const char* ImGui::GetVersion()
  2307. {
  2308. return IMGUI_VERSION;
  2309. }
  2310. // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
  2311. // 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
  2312. ImGuiContext* ImGui::GetCurrentContext()
  2313. {
  2314. return GImGui;
  2315. }
  2316. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  2317. {
  2318. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  2319. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  2320. #else
  2321. GImGui = ctx;
  2322. #endif
  2323. }
  2324. void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data)
  2325. {
  2326. GImAllocatorAllocFunc = alloc_func;
  2327. GImAllocatorFreeFunc = free_func;
  2328. GImAllocatorUserData = user_data;
  2329. }
  2330. ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
  2331. {
  2332. ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
  2333. if (GImGui == NULL)
  2334. SetCurrentContext(ctx);
  2335. Initialize(ctx);
  2336. return ctx;
  2337. }
  2338. void ImGui::DestroyContext(ImGuiContext* ctx)
  2339. {
  2340. if (ctx == NULL)
  2341. ctx = GImGui;
  2342. Shutdown(ctx);
  2343. if (GImGui == ctx)
  2344. SetCurrentContext(NULL);
  2345. IM_DELETE(ctx);
  2346. }
  2347. ImGuiIO& ImGui::GetIO()
  2348. {
  2349. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2350. return GImGui->IO;
  2351. }
  2352. ImGuiPlatformIO& ImGui::GetPlatformIO()
  2353. {
  2354. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2355. return GImGui->PlatformIO;
  2356. }
  2357. ImGuiStyle& ImGui::GetStyle()
  2358. {
  2359. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  2360. return GImGui->Style;
  2361. }
  2362. // Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
  2363. ImDrawData* ImGui::GetDrawData()
  2364. {
  2365. ImGuiContext& g = *GImGui;
  2366. return g.Viewports[0]->DrawDataP.Valid ? &g.Viewports[0]->DrawDataP : NULL;
  2367. }
  2368. float ImGui::GetTime()
  2369. {
  2370. return GImGui->Time;
  2371. }
  2372. int ImGui::GetFrameCount()
  2373. {
  2374. return GImGui->FrameCount;
  2375. }
  2376. ImDrawList* ImGui::GetOverlayDrawList()
  2377. {
  2378. return &GImGui->OverlayDrawList;
  2379. }
  2380. ImDrawListSharedData* ImGui::GetDrawListSharedData()
  2381. {
  2382. return &GImGui->DrawListSharedData;
  2383. }
  2384. // This needs to be called before we submit any widget (aka in or before Begin)
  2385. void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
  2386. {
  2387. ImGuiContext& g = *GImGui;
  2388. IM_ASSERT(window == g.NavWindow);
  2389. bool init_for_nav = false;
  2390. if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
  2391. if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
  2392. init_for_nav = true;
  2393. if (init_for_nav)
  2394. {
  2395. SetNavID(0, g.NavLayer);
  2396. g.NavInitRequest = true;
  2397. g.NavInitRequestFromMove = false;
  2398. g.NavInitResultId = 0;
  2399. g.NavInitResultRectRel = ImRect();
  2400. NavUpdateAnyRequestFlag();
  2401. }
  2402. else
  2403. {
  2404. g.NavId = window->NavLastIds[0];
  2405. }
  2406. }
  2407. static ImVec2 NavCalcPreferredMousePos()
  2408. {
  2409. ImGuiContext& g = *GImGui;
  2410. ImGuiWindow* window = g.NavWindow;
  2411. if (!window)
  2412. return g.IO.MousePos;
  2413. const ImRect& rect_rel = window->NavRectRel[g.NavLayer];
  2414. 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()));
  2415. ImRect visible_rect = ImGui::GetViewportRect(window);
  2416. 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.
  2417. }
  2418. static int FindWindowIndex(ImGuiWindow* window) // FIXME-OPT O(N)
  2419. {
  2420. ImGuiContext& g = *GImGui;
  2421. for (int i = g.Windows.Size-1; i >= 0; i--)
  2422. if (g.Windows[i] == window)
  2423. return i;
  2424. return -1;
  2425. }
  2426. static ImGuiWindow* FindWindowNavigable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
  2427. {
  2428. ImGuiContext& g = *GImGui;
  2429. for (int i = i_start; i >= 0 && i < g.Windows.Size && i != i_stop; i += dir)
  2430. if (ImGui::IsWindowNavFocusable(g.Windows[i]))
  2431. return g.Windows[i];
  2432. return NULL;
  2433. }
  2434. float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
  2435. {
  2436. ImGuiContext& g = *GImGui;
  2437. if (mode == ImGuiInputReadMode_Down)
  2438. return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
  2439. const float t = g.IO.NavInputsDownDuration[n];
  2440. if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
  2441. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
  2442. if (t < 0.0f)
  2443. return 0.0f;
  2444. if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
  2445. return (t == 0.0f) ? 1.0f : 0.0f;
  2446. if (mode == ImGuiInputReadMode_Repeat)
  2447. return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
  2448. if (mode == ImGuiInputReadMode_RepeatSlow)
  2449. return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
  2450. if (mode == ImGuiInputReadMode_RepeatFast)
  2451. return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
  2452. return 0.0f;
  2453. }
  2454. // Equivalent of IsKeyDown() for NavInputs[]
  2455. static bool IsNavInputDown(ImGuiNavInput n)
  2456. {
  2457. return GImGui->IO.NavInputs[n] > 0.0f;
  2458. }
  2459. // Equivalent of IsKeyPressed() for NavInputs[]
  2460. static bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode)
  2461. {
  2462. return ImGui::GetNavInputAmount(n, mode) > 0.0f;
  2463. }
  2464. static bool IsNavInputPressedAnyOfTwo(ImGuiNavInput n1, ImGuiNavInput n2, ImGuiInputReadMode mode)
  2465. {
  2466. return (ImGui::GetNavInputAmount(n1, mode) + ImGui::GetNavInputAmount(n2, mode)) > 0.0f;
  2467. }
  2468. ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
  2469. {
  2470. ImVec2 delta(0.0f, 0.0f);
  2471. if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
  2472. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
  2473. if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
  2474. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
  2475. if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
  2476. delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
  2477. if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
  2478. delta *= slow_factor;
  2479. if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
  2480. delta *= fast_factor;
  2481. return delta;
  2482. }
  2483. static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
  2484. {
  2485. ImGuiContext& g = *GImGui;
  2486. IM_ASSERT(g.NavWindowingTarget);
  2487. if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
  2488. return;
  2489. const int i_current = FindWindowIndex(g.NavWindowingTarget);
  2490. ImGuiWindow* window_target = FindWindowNavigable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
  2491. if (!window_target)
  2492. window_target = FindWindowNavigable((focus_change_dir < 0) ? (g.Windows.Size - 1) : 0, i_current, focus_change_dir);
  2493. g.NavWindowingTarget = window_target;
  2494. g.NavWindowingToggleLayer = false;
  2495. }
  2496. // Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer)
  2497. static void ImGui::NavUpdateWindowing()
  2498. {
  2499. ImGuiContext& g = *GImGui;
  2500. ImGuiWindow* apply_focus_window = NULL;
  2501. bool apply_toggle_layer = false;
  2502. bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
  2503. bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
  2504. if (start_windowing_with_gamepad || start_windowing_with_keyboard)
  2505. if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavigable(g.Windows.Size - 1, -INT_MAX, -1))
  2506. {
  2507. g.NavWindowingTarget = window->RootWindowForTabbing;
  2508. g.NavWindowingHighlightTimer = g.NavWindowingHighlightAlpha = 0.0f;
  2509. g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
  2510. g.NavWindowingInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
  2511. }
  2512. // Gamepad update
  2513. g.NavWindowingHighlightTimer += g.IO.DeltaTime;
  2514. if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_NavGamepad)
  2515. {
  2516. // 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
  2517. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.20f) / 0.05f));
  2518. // Select window to focus
  2519. const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
  2520. if (focus_change_dir != 0)
  2521. {
  2522. NavUpdateWindowingHighlightWindow(focus_change_dir);
  2523. g.NavWindowingHighlightAlpha = 1.0f;
  2524. }
  2525. // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most)
  2526. if (!IsNavInputDown(ImGuiNavInput_Menu))
  2527. {
  2528. g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
  2529. if (g.NavWindowingToggleLayer && g.NavWindow)
  2530. apply_toggle_layer = true;
  2531. else if (!g.NavWindowingToggleLayer)
  2532. apply_focus_window = g.NavWindowingTarget;
  2533. g.NavWindowingTarget = NULL;
  2534. }
  2535. }
  2536. // Keyboard: Focus
  2537. if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_NavKeyboard)
  2538. {
  2539. // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
  2540. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.15f) / 0.04f)); // 1.0f
  2541. if (IsKeyPressedMap(ImGuiKey_Tab, true))
  2542. NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
  2543. if (!g.IO.KeyCtrl)
  2544. apply_focus_window = g.NavWindowingTarget;
  2545. }
  2546. // Keyboard: Press and Release ALT to toggle menu layer
  2547. // 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
  2548. if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
  2549. if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
  2550. apply_toggle_layer = true;
  2551. // Move window
  2552. if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
  2553. {
  2554. ImVec2 move_delta;
  2555. if (g.NavWindowingInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
  2556. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  2557. if (g.NavWindowingInputSource == ImGuiInputSource_NavGamepad)
  2558. move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
  2559. if (move_delta.x != 0.0f || move_delta.y != 0.0f)
  2560. {
  2561. const float NAV_MOVE_SPEED = 800.0f;
  2562. const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
  2563. g.NavWindowingTarget->PosFloat += move_delta * move_speed;
  2564. g.NavDisableMouseHover = true;
  2565. MarkIniSettingsDirty(g.NavWindowingTarget);
  2566. }
  2567. }
  2568. // Apply final focus
  2569. if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindowForTabbing))
  2570. {
  2571. g.NavDisableHighlight = false;
  2572. g.NavDisableMouseHover = true;
  2573. apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
  2574. ClosePopupsOverWindow(apply_focus_window);
  2575. FocusWindow(apply_focus_window);
  2576. if (apply_focus_window->NavLastIds[0] == 0)
  2577. NavInitWindow(apply_focus_window, false);
  2578. // If the window only has a menu layer, select it directly
  2579. if (apply_focus_window->DC.NavLayerActiveMask == (1 << 1))
  2580. g.NavLayer = 1;
  2581. }
  2582. if (apply_focus_window)
  2583. g.NavWindowingTarget = NULL;
  2584. // Apply menu/layer toggle
  2585. if (apply_toggle_layer && g.NavWindow)
  2586. {
  2587. ImGuiWindow* new_nav_window = g.NavWindow;
  2588. while ((new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
  2589. new_nav_window = new_nav_window->ParentWindow;
  2590. if (new_nav_window != g.NavWindow)
  2591. {
  2592. ImGuiWindow* old_nav_window = g.NavWindow;
  2593. FocusWindow(new_nav_window);
  2594. new_nav_window->NavLastChildNavWindow = old_nav_window;
  2595. }
  2596. g.NavDisableHighlight = false;
  2597. g.NavDisableMouseHover = true;
  2598. NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << 1)) ? (g.NavLayer ^ 1) : 0);
  2599. }
  2600. }
  2601. // NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated.
  2602. static void NavScrollToBringItemIntoView(ImGuiWindow* window, ImRect& item_rect_rel)
  2603. {
  2604. // Scroll to keep newly navigated item fully into view
  2605. ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1));
  2606. //g.OverlayDrawList.AddRect(window->Pos + window_rect_rel.Min, window->Pos + window_rect_rel.Max, IM_COL32_WHITE); // [DEBUG]
  2607. if (window_rect_rel.Contains(item_rect_rel))
  2608. return;
  2609. ImGuiContext& g = *GImGui;
  2610. if (window->ScrollbarX && item_rect_rel.Min.x < window_rect_rel.Min.x)
  2611. {
  2612. window->ScrollTarget.x = item_rect_rel.Min.x + window->Scroll.x - g.Style.ItemSpacing.x;
  2613. window->ScrollTargetCenterRatio.x = 0.0f;
  2614. }
  2615. else if (window->ScrollbarX && item_rect_rel.Max.x >= window_rect_rel.Max.x)
  2616. {
  2617. window->ScrollTarget.x = item_rect_rel.Max.x + window->Scroll.x + g.Style.ItemSpacing.x;
  2618. window->ScrollTargetCenterRatio.x = 1.0f;
  2619. }
  2620. if (item_rect_rel.Min.y < window_rect_rel.Min.y)
  2621. {
  2622. window->ScrollTarget.y = item_rect_rel.Min.y + window->Scroll.y - g.Style.ItemSpacing.y;
  2623. window->ScrollTargetCenterRatio.y = 0.0f;
  2624. }
  2625. else if (item_rect_rel.Max.y >= window_rect_rel.Max.y)
  2626. {
  2627. window->ScrollTarget.y = item_rect_rel.Max.y + window->Scroll.y + g.Style.ItemSpacing.y;
  2628. window->ScrollTargetCenterRatio.y = 1.0f;
  2629. }
  2630. // Estimate upcoming scroll so we can offset our relative mouse position so mouse position can be applied immediately (under this block)
  2631. ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  2632. item_rect_rel.Translate(window->Scroll - next_scroll);
  2633. }
  2634. static void ImGui::NavUpdate()
  2635. {
  2636. ImGuiContext& g = *GImGui;
  2637. g.IO.WantMoveMouse = false;
  2638. #if 0
  2639. if (g.NavScoringCount > 0) printf("[%05d] 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);
  2640. #endif
  2641. // Update Keyboard->Nav inputs mapping
  2642. memset(g.IO.NavInputs + ImGuiNavInput_InternalStart_, 0, (ImGuiNavInput_COUNT - ImGuiNavInput_InternalStart_) * sizeof(g.IO.NavInputs[0]));
  2643. if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
  2644. {
  2645. #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (g.IO.KeyMap[_KEY] != -1 && IsKeyDown(g.IO.KeyMap[_KEY])) g.IO.NavInputs[_NAV_INPUT] = 1.0f;
  2646. NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
  2647. NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
  2648. NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
  2649. NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
  2650. NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
  2651. NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
  2652. NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
  2653. if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
  2654. if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
  2655. if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
  2656. #undef NAV_MAP_KEY
  2657. }
  2658. memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
  2659. for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
  2660. 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;
  2661. // Process navigation init request (select first/default focus)
  2662. if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
  2663. {
  2664. // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
  2665. IM_ASSERT(g.NavWindow);
  2666. if (g.NavInitRequestFromMove)
  2667. SetNavIDAndMoveMouse(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
  2668. else
  2669. SetNavID(g.NavInitResultId, g.NavLayer);
  2670. g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
  2671. }
  2672. g.NavInitRequest = false;
  2673. g.NavInitRequestFromMove = false;
  2674. g.NavInitResultId = 0;
  2675. g.NavJustMovedToId = 0;
  2676. // Process navigation move request
  2677. if (g.NavMoveRequest && (g.NavMoveResultLocal.ID != 0 || g.NavMoveResultOther.ID != 0))
  2678. {
  2679. // Select which result to use
  2680. ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
  2681. if (g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) // Maybe entering a flattened child? In this case solve the tie using the regular scoring rules
  2682. if ((g.NavMoveResultOther.DistBox < g.NavMoveResultLocal.DistBox) || (g.NavMoveResultOther.DistBox == g.NavMoveResultLocal.DistBox && g.NavMoveResultOther.DistCenter < g.NavMoveResultLocal.DistCenter))
  2683. result = &g.NavMoveResultOther;
  2684. IM_ASSERT(g.NavWindow && result->Window);
  2685. // Scroll to keep newly navigated item fully into view
  2686. if (g.NavLayer == 0)
  2687. NavScrollToBringItemIntoView(result->Window, result->RectRel);
  2688. // Apply result from previous frame navigation directional move request
  2689. ClearActiveID();
  2690. g.NavWindow = result->Window;
  2691. SetNavIDAndMoveMouse(result->ID, g.NavLayer, result->RectRel);
  2692. g.NavJustMovedToId = result->ID;
  2693. g.NavMoveFromClampedRefRect = false;
  2694. }
  2695. // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
  2696. if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
  2697. {
  2698. IM_ASSERT(g.NavMoveRequest);
  2699. if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
  2700. g.NavDisableHighlight = false;
  2701. g.NavMoveRequestForward = ImGuiNavForward_None;
  2702. }
  2703. // Apply application mouse position movement, after we had a chance to process move request result.
  2704. if (g.NavMousePosDirty && g.NavIdIsAlive)
  2705. {
  2706. // Set mouse position given our knowledge of the nav widget position from last frame
  2707. if (g.IO.ConfigFlags & ImGuiConfigFlags_NavMoveMouse)
  2708. {
  2709. g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredMousePos();
  2710. g.IO.WantMoveMouse = true;
  2711. }
  2712. g.NavMousePosDirty = false;
  2713. }
  2714. g.NavIdIsAlive = false;
  2715. g.NavJustTabbedId = 0;
  2716. IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
  2717. // 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
  2718. if (g.NavWindow)
  2719. NavSaveLastChildNavWindow(g.NavWindow);
  2720. if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
  2721. g.NavWindow->NavLastChildNavWindow = NULL;
  2722. NavUpdateWindowing();
  2723. // Set output flags for user application
  2724. g.IO.NavActive = (g.IO.ConfigFlags & (ImGuiConfigFlags_NavEnableGamepad | ImGuiConfigFlags_NavEnableKeyboard)) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
  2725. g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL) || g.NavInitRequest;
  2726. // Process NavCancel input (to close a popup, get back to parent, clear focus)
  2727. if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
  2728. {
  2729. if (g.ActiveId != 0)
  2730. {
  2731. ClearActiveID();
  2732. }
  2733. else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
  2734. {
  2735. // Exit child window
  2736. ImGuiWindow* child_window = g.NavWindow;
  2737. ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
  2738. IM_ASSERT(child_window->ChildId != 0);
  2739. FocusWindow(parent_window);
  2740. SetNavID(child_window->ChildId, 0);
  2741. g.NavIdIsAlive = false;
  2742. if (g.NavDisableMouseHover)
  2743. g.NavMousePosDirty = true;
  2744. }
  2745. else if (g.OpenPopupStack.Size > 0)
  2746. {
  2747. // Close open popup/menu
  2748. if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
  2749. ClosePopupToLevel(g.OpenPopupStack.Size - 1);
  2750. }
  2751. else if (g.NavLayer != 0)
  2752. {
  2753. // Leave the "menu" layer
  2754. NavRestoreLayer(0);
  2755. }
  2756. else
  2757. {
  2758. // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
  2759. if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
  2760. g.NavWindow->NavLastIds[0] = 0;
  2761. g.NavId = 0;
  2762. }
  2763. }
  2764. // Process manual activation request
  2765. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
  2766. if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  2767. {
  2768. bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
  2769. bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
  2770. if (g.ActiveId == 0 && activate_pressed)
  2771. g.NavActivateId = g.NavId;
  2772. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
  2773. g.NavActivateDownId = g.NavId;
  2774. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
  2775. g.NavActivatePressedId = g.NavId;
  2776. if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
  2777. g.NavInputId = g.NavId;
  2778. }
  2779. if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  2780. g.NavDisableHighlight = true;
  2781. if (g.NavActivateId != 0)
  2782. IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
  2783. g.NavMoveRequest = false;
  2784. // Process programmatic activation request
  2785. if (g.NavNextActivateId != 0)
  2786. g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
  2787. g.NavNextActivateId = 0;
  2788. // Initiate directional inputs request
  2789. const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
  2790. if (g.NavMoveRequestForward == ImGuiNavForward_None)
  2791. {
  2792. g.NavMoveDir = ImGuiDir_None;
  2793. if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
  2794. {
  2795. if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
  2796. if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
  2797. if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
  2798. if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
  2799. }
  2800. }
  2801. else
  2802. {
  2803. // 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)
  2804. IM_ASSERT(g.NavMoveDir != ImGuiDir_None);
  2805. IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
  2806. g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
  2807. }
  2808. if (g.NavMoveDir != ImGuiDir_None)
  2809. {
  2810. g.NavMoveRequest = true;
  2811. g.NavMoveDirLast = g.NavMoveDir;
  2812. }
  2813. // 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
  2814. if (g.NavMoveRequest && g.NavId == 0)
  2815. {
  2816. g.NavInitRequest = g.NavInitRequestFromMove = true;
  2817. g.NavInitResultId = 0;
  2818. g.NavDisableHighlight = false;
  2819. }
  2820. NavUpdateAnyRequestFlag();
  2821. // Scrolling
  2822. if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
  2823. {
  2824. // *Fallback* manual-scroll with NavUp/NavDown when window has no navigable item
  2825. ImGuiWindow* window = g.NavWindow;
  2826. const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
  2827. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
  2828. {
  2829. if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
  2830. SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
  2831. if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
  2832. SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
  2833. }
  2834. // *Normal* Manual scroll with NavScrollXXX keys
  2835. // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
  2836. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
  2837. if (scroll_dir.x != 0.0f && window->ScrollbarX)
  2838. {
  2839. SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
  2840. g.NavMoveFromClampedRefRect = true;
  2841. }
  2842. if (scroll_dir.y != 0.0f)
  2843. {
  2844. SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
  2845. g.NavMoveFromClampedRefRect = true;
  2846. }
  2847. }
  2848. // Reset search results
  2849. g.NavMoveResultLocal.Clear();
  2850. g.NavMoveResultOther.Clear();
  2851. // 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
  2852. if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
  2853. {
  2854. ImGuiWindow* window = g.NavWindow;
  2855. ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
  2856. if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
  2857. {
  2858. float pad = window->CalcFontSize() * 0.5f;
  2859. 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
  2860. window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
  2861. g.NavId = 0;
  2862. }
  2863. g.NavMoveFromClampedRefRect = false;
  2864. }
  2865. // 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)
  2866. ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
  2867. g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : ImRect(0,0,0,0);
  2868. g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
  2869. g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
  2870. IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous fabsf() calls in NavScoreItem().
  2871. //g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
  2872. g.NavScoringCount = 0;
  2873. #if IMGUI_DEBUG_NAV_RECTS
  2874. if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) g.OverlayDrawList.AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
  2875. if (g.NavWindow) { ImU32 col = (g.NavWindow->HiddenFrames <= 0) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredMousePos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); g.OverlayDrawList.AddCircleFilled(p, 3.0f, col); g.OverlayDrawList.AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
  2876. #endif
  2877. }
  2878. static void ImGui::UpdateMovingWindowDropViewport(ImGuiWindow* window)
  2879. {
  2880. // On release we either drop window over an existing viewport or create a new one
  2881. // (We convert position from one viewport space to another, which is unnecessary at the moment but allows us to have viewport overlapping in term of imgui position)
  2882. ImGuiContext& g = *GImGui;
  2883. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_EnableViewports))
  2884. return;
  2885. ImRect mouse_viewport_rect = g.MouseViewport->GetRect();
  2886. ImVec2 window_pos_in_mouse_viewport = ConvertPlatformPosToViewportPos(ConvertViewportPosToPlatformPos(window->Pos, window->Viewport), g.MouseViewport);
  2887. ImRect window_rect_in_mouse_viewport = ImRect(window_pos_in_mouse_viewport, window_pos_in_mouse_viewport + window->Size);
  2888. if ((g.MouseViewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && mouse_viewport_rect.Contains(window_rect_in_mouse_viewport))
  2889. {
  2890. // Drop on an existing viewport
  2891. ImGuiViewportP* old_viewport = window->Viewport;
  2892. SetWindowViewportTranslateToPreservePlatformPos(window, window->Viewport, g.MouseViewport);
  2893. // Our current scheme allow any window to land on a viewport, so when that viewport merges, move other windows as well
  2894. // FIXME-OPT
  2895. if (window->Flags & ImGuiWindowFlags_FullViewport)
  2896. for (int n = 0; n < g.Windows.Size; n++)
  2897. if (g.Windows[n]->Viewport == old_viewport)
  2898. SetWindowViewportTranslateToPreservePlatformPos(g.Windows[n], old_viewport, g.MouseViewport);
  2899. }
  2900. else
  2901. {
  2902. // Create new viewport
  2903. ImVec2 platform_pos = ConvertViewportPosToPlatformPos(window->Pos, window->Viewport);
  2904. ImGuiViewportP* viewport = Viewport(window, window->ID, 0, platform_pos, window->Size);
  2905. SetWindowViewportTranslateToPreservePlatformPos(window, window->Viewport, viewport);
  2906. }
  2907. }
  2908. static void ImGui::UpdateMovingWindow()
  2909. {
  2910. ImGuiContext& g = *GImGui;
  2911. if (g.MovingWindow && g.MovingWindow->MoveId == g.ActiveId && g.ActiveIdSource == ImGuiInputSource_Mouse)
  2912. {
  2913. // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
  2914. // We track it to preserve Focus and so that ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
  2915. KeepAliveID(g.ActiveId);
  2916. IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
  2917. ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
  2918. if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
  2919. {
  2920. ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
  2921. if (moving_window->PosFloat.x != pos.x || moving_window->PosFloat.y != pos.y)
  2922. {
  2923. MarkIniSettingsDirty(moving_window);
  2924. SetWindowPos(moving_window, pos, ImGuiCond_Always);
  2925. }
  2926. FocusWindow(g.MovingWindow);
  2927. }
  2928. else
  2929. {
  2930. UpdateMovingWindowDropViewport(moving_window);
  2931. // Clear the NoInput flag set by the Viewport system
  2932. moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
  2933. ClearActiveID();
  2934. g.MovingWindow = NULL;
  2935. }
  2936. }
  2937. else
  2938. {
  2939. // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
  2940. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
  2941. {
  2942. KeepAliveID(g.ActiveId);
  2943. if (!g.IO.MouseDown[0])
  2944. ClearActiveID();
  2945. }
  2946. if (g.MovingWindow != NULL)
  2947. g.MovingWindow->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
  2948. g.MovingWindow = NULL;
  2949. }
  2950. }
  2951. // If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
  2952. // This search won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
  2953. static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 mouse_platform_pos)
  2954. {
  2955. ImGuiContext& g = *GImGui;
  2956. ImGuiViewportP* best_candidate = NULL;
  2957. for (int n = 0; n < g.Viewports.Size; n++)
  2958. {
  2959. ImGuiViewportP* viewport = g.Viewports[n];
  2960. ImRect platform_rect = ImRect(viewport->PlatformPos, viewport->PlatformPos + viewport->Size);
  2961. if (!(viewport->Flags & ImGuiViewportFlags_NoInputs) && platform_rect.Contains(mouse_platform_pos))
  2962. if (best_candidate == NULL || best_candidate->LastFrameAsRefViewport < viewport->LastFrameAsRefViewport)
  2963. best_candidate = viewport;
  2964. }
  2965. return best_candidate;
  2966. }
  2967. static void ImGui::UpdateViewports()
  2968. {
  2969. ImGuiContext& g = *GImGui;
  2970. IM_ASSERT(g.PlatformData.Viewports.Size <= g.Viewports.Size);
  2971. // Mouse handling: latch the expected mouse OS position (if any) before processing viewport erasure
  2972. ImGuiViewportP* viewport_ref = g.IO.MousePosViewport ? FindViewportByID(g.IO.MousePosViewport) : g.Viewports[0];
  2973. const ImVec2 mouse_platform_pos = ConvertViewportPosToPlatformPos(g.IO.MousePos, viewport_ref);
  2974. g.CurrentViewport = NULL;
  2975. for (int n = 0; n < g.Viewports.Size; n++)
  2976. {
  2977. // Erase unused viewports
  2978. ImGuiViewportP* viewport = g.Viewports[n];
  2979. IM_ASSERT(viewport->Idx == n);
  2980. if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
  2981. {
  2982. // Translate windows like if we were resizing the viewport to be zero-width
  2983. ResizeViewportTranslateWindows(n + 1, g.Viewports.Size, viewport->Pos.x - viewport->GetNextX(), -1, viewport);
  2984. g.Viewports.erase(g.Viewports.Data + n);
  2985. // Destroy
  2986. if (viewport == viewport_ref) viewport_ref = NULL;
  2987. if (viewport == g.MouseViewport) g.MouseViewport = NULL;
  2988. if (viewport == g.MouseLastHoveredViewport) g.MouseLastHoveredViewport = NULL;
  2989. IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
  2990. IM_ASSERT(g.PlatformData.Viewports.contains(viewport) == false);
  2991. IM_DELETE(viewport);
  2992. n--;
  2993. continue;
  2994. }
  2995. // Translate resized viewports
  2996. if (n + 1 < g.Viewports.Size)
  2997. {
  2998. float dx = viewport->GetNextX() - g.Viewports[viewport->Idx + 1]->Pos.x;
  2999. if (dx != 0.0f)
  3000. ResizeViewportTranslateWindows(viewport->Idx + 1, g.Viewports.Size, dx, 0, NULL);
  3001. }
  3002. // Apply Position and Size (from Platform Window to ImGui) if requested
  3003. // We do it here early in the frame instead of UpdatePlatformWindows() to allow the platform back-end to set PlatformRequestResize early
  3004. // (e.g. in their own message handler before NewFrame) and not have a frame of lag.
  3005. if (viewport->PlatformRequestMove)
  3006. viewport->PlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
  3007. if (viewport->PlatformRequestResize)
  3008. viewport->Size = g.PlatformIO.Platform_GetWindowSize(viewport);
  3009. // Update DPI Scale
  3010. float new_dpi_scale;
  3011. if (g.PlatformIO.Platform_GetWindowDpiScale)
  3012. new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
  3013. else
  3014. new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
  3015. if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
  3016. {
  3017. float scale_factor = new_dpi_scale / viewport->DpiScale;
  3018. if (g.IO.ConfigFlags & ImGuiConfigFlags_EnableDpiScaleViewports)
  3019. ScaleWindowsInViewport(viewport, scale_factor);
  3020. //if (viewport == GetMainViewport())
  3021. // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
  3022. // FIXME-DPI: We need to preserve our pivots
  3023. //if (g.MovingWindow)
  3024. // g.ActiveIdClickOffset = g.ActiveIdClickOffset * scale_factor;
  3025. }
  3026. viewport->DpiScale = new_dpi_scale;
  3027. }
  3028. // Update main viewport with current size (and OS window position, if known)
  3029. ImGuiViewportP* main_viewport = g.Viewports[0];
  3030. IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
  3031. ImVec2 main_viewport_platform_pos = ImVec2(0.0f, 0.0f);
  3032. if ((g.IO.ConfigFlags & ImGuiConfigFlags_EnableViewports))
  3033. main_viewport_platform_pos = g.PlatformIO.Platform_GetWindowPos(main_viewport);
  3034. Viewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, ImGuiViewportFlags_CanHostOtherWindows, main_viewport_platform_pos, g.IO.DisplaySize);
  3035. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_EnableViewports))
  3036. {
  3037. g.MouseViewport = g.MouseLastViewport = main_viewport;
  3038. return;
  3039. }
  3040. // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
  3041. ImGuiViewportP* viewport_hovered = NULL;
  3042. if (g.IO.ConfigFlags & ImGuiConfigFlags_PlatformHasMouseHoveredViewport)
  3043. {
  3044. viewport_hovered = g.IO.MouseHoveredViewport ? FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
  3045. if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
  3046. {
  3047. // Back-end failed at honoring its contract
  3048. IM_ASSERT(0);
  3049. viewport_hovered = FindViewportHoveredFromPlatformWindowStack(mouse_platform_pos);
  3050. }
  3051. }
  3052. else
  3053. {
  3054. // If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
  3055. // This search won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
  3056. viewport_hovered = FindViewportHoveredFromPlatformWindowStack(mouse_platform_pos);
  3057. }
  3058. if (viewport_hovered != NULL)
  3059. g.MouseLastHoveredViewport = viewport_hovered;
  3060. // If reference viewport just has been deleted, use a position relative to the main viewport
  3061. if (viewport_ref == NULL)
  3062. {
  3063. viewport_ref = main_viewport;
  3064. g.IO.MousePos = ConvertPlatformPosToViewportPos(mouse_platform_pos, viewport_ref);
  3065. }
  3066. g.MouseLastViewport = g.MouseViewport;
  3067. g.MouseViewport = viewport_ref;
  3068. g.MouseViewport->LastFrameAsRefViewport = g.FrameCount;
  3069. // When dragging something, always refer to the last hovered viewport (so when we are between viewport, our dragged preview will tend to show in the last viewport)
  3070. const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive || (g.MovingWindow != NULL);
  3071. const bool is_mouse_all_released = !ImGui::IsAnyMouseDown();
  3072. if (is_mouse_dragging_with_an_expected_destination || is_mouse_all_released)
  3073. {
  3074. if (is_mouse_dragging_with_an_expected_destination)
  3075. viewport_hovered = g.MouseLastHoveredViewport;
  3076. if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
  3077. {
  3078. g.IO.MousePos = ConvertPlatformPosToViewportPos(ConvertViewportPosToPlatformPos(g.IO.MousePos, g.MouseViewport), viewport_hovered);
  3079. g.MouseViewport = viewport_hovered;
  3080. }
  3081. }
  3082. IM_ASSERT(g.MouseViewport != NULL);
  3083. }
  3084. ImGuiPlatformData* ImGui::GetPlatformData()
  3085. {
  3086. return &GImGui->PlatformData;
  3087. }
  3088. void ImGui::UpdatePlatformWindows()
  3089. {
  3090. ImGuiContext& g = *GImGui;
  3091. IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
  3092. IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
  3093. g.FrameCountPlatformEnded = g.FrameCount;
  3094. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_EnableViewports))
  3095. return;
  3096. // Create/resize/destroy platform windows and update the list that the user can process
  3097. for (int i = 1; i < g.Viewports.Size; i++)
  3098. {
  3099. ImGuiViewportP* viewport = g.Viewports[i];
  3100. if (viewport->LastFrameActive < g.FrameCount)
  3101. {
  3102. if (viewport->LastFrameActive < g.FrameCount - 1)
  3103. {
  3104. if (g.PlatformIO.Renderer_DestroyWindow)
  3105. g.PlatformIO.Renderer_DestroyWindow(viewport);
  3106. if (g.PlatformIO.Platform_DestroyWindow)
  3107. g.PlatformIO.Platform_DestroyWindow(viewport);
  3108. IM_ASSERT(viewport->RendererUserData == NULL);
  3109. IM_ASSERT(viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
  3110. }
  3111. continue;
  3112. }
  3113. bool is_new_window = (viewport->PlatformHandle == NULL && viewport->PlatformUserData == NULL && viewport->RendererUserData == NULL);
  3114. if (is_new_window && viewport->PlatformHandle == NULL && viewport->PlatformUserData == NULL)
  3115. g.PlatformIO.Platform_CreateWindow(viewport);
  3116. if (is_new_window && viewport->RendererUserData == NULL && g.PlatformIO.Renderer_CreateWindow != NULL)
  3117. {
  3118. g.PlatformIO.Renderer_CreateWindow(viewport);
  3119. viewport->RendererLastSize = viewport->Size;
  3120. }
  3121. // Apply Position and Size (from ImGui to Platform Window)
  3122. if (!viewport->PlatformRequestMove)
  3123. g.PlatformIO.Platform_SetWindowPos(viewport, viewport->PlatformPos);
  3124. if (!viewport->PlatformRequestResize)
  3125. g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
  3126. // Update Size for Renderer
  3127. if (g.PlatformIO.Renderer_SetWindowSize && (viewport->RendererLastSize.x != viewport->Size.x || viewport->RendererLastSize.y != viewport->Size.y))
  3128. g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
  3129. viewport->RendererLastSize = viewport->Size;
  3130. // Update title bar
  3131. const char* title_begin = viewport->Window->Name;
  3132. const char* title_end = ImGui::FindRenderedTextEnd(title_begin);
  3133. const ImGuiID title_hash = ImHash(title_begin, (int)(title_end - title_begin));
  3134. if (viewport->LastNameHash != title_hash)
  3135. {
  3136. viewport->LastNameHash = title_hash;
  3137. char* title_displayed = ImStrdup(viewport->Window->Name);
  3138. title_displayed[title_end - title_begin] = 0;
  3139. g.PlatformIO.Platform_SetWindowTitle(viewport, title_displayed);
  3140. ImGui::MemFree(title_displayed);
  3141. }
  3142. // Show window. On startup ensure platform window don't get focus.
  3143. if (is_new_window)
  3144. {
  3145. if (g.FrameCount < 2)
  3146. viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
  3147. g.PlatformIO.Platform_ShowWindow(viewport);
  3148. }
  3149. // Clear request flags
  3150. viewport->PlatformRequestClose = viewport->PlatformRequestMove = viewport->PlatformRequestResize = false;
  3151. }
  3152. }
  3153. // This is a default/basic function for performing the rendering/swap of multiple platform windows.
  3154. // Custom renderers may prefer to not call this function at all, and instead iterate the platform data and handle rendering/sync themselves.
  3155. // The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
  3156. //
  3157. // ImGuiPlatformData* data = ImGui::GetPlatformData();
  3158. // for (int i = 1; i < data->Viewports.Size; i++)
  3159. // MyRenderFunction(data->Viewports[i], my_args);
  3160. // for (int i = 1; i < data->Viewports.Size; i++)
  3161. // MySwapBufferFunction(data->Viewports[i], my_args);
  3162. //
  3163. // Note how we intentionally skip the main viewport (index 0) which is generally rendered as part of our main application.
  3164. void ImGui::RenderPlatformWindows(void* platform_render_arg, void* renderer_render_arg)
  3165. {
  3166. if (!(ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_EnableViewports))
  3167. return;
  3168. ImGuiPlatformData* data = ImGui::GetPlatformData();
  3169. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  3170. for (int i = 1; i < data->Viewports.Size; i++)
  3171. {
  3172. ImGuiViewport* viewport = data->Viewports[i];
  3173. if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
  3174. if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
  3175. }
  3176. for (int i = 1; i < data->Viewports.Size; i++)
  3177. {
  3178. ImGuiViewport* viewport = data->Viewports[i];
  3179. if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
  3180. if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
  3181. }
  3182. }
  3183. void ImGui::NewFrame()
  3184. {
  3185. IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
  3186. ImGuiContext& g = *GImGui;
  3187. // Check user data
  3188. // (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)
  3189. IM_ASSERT(g.Initialized);
  3190. IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
  3191. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
  3192. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  3193. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
  3194. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
  3195. 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)");
  3196. IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
  3197. for (int n = 0; n < ImGuiKey_COUNT; n++)
  3198. 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)");
  3199. // Perform simple check for 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)
  3200. if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
  3201. IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
  3202. // Perform simple checks for multi-viewport and platform windows support
  3203. if (g.IO.ConfigFlags & ImGuiConfigFlags_EnableViewports)
  3204. {
  3205. if ((g.IO.ConfigFlags & ImGuiConfigFlags_PlatformHasViewports) && (g.IO.ConfigFlags & ImGuiConfigFlags_RendererHasViewports))
  3206. {
  3207. IM_ASSERT(g.FrameCount == 0 || g.FrameCountPlatformEnded == g.FrameCount && "Forgot to call UpdatePlatformWindows() at the end of the previous frame?");
  3208. IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
  3209. IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
  3210. IM_ASSERT(g.Viewports[0]->PlatformUserData != NULL && "Platform init didn't setup main viewport.");
  3211. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  3212. IM_ASSERT(g.IO.RenderDrawListsFn == NULL); // Call ImGui::Render() then pass ImGui::GetDrawData() yourself to your render function!
  3213. #endif
  3214. }
  3215. else
  3216. {
  3217. // Disable feature, our back-ends do not support it
  3218. g.IO.ConfigFlags &= ~ImGuiConfigFlags_EnableViewports;
  3219. }
  3220. }
  3221. // Load settings on first frame
  3222. if (!g.SettingsLoaded)
  3223. {
  3224. IM_ASSERT(g.SettingsWindows.empty());
  3225. LoadIniSettingsFromDisk(g.IO.IniFilename);
  3226. g.SettingsLoaded = true;
  3227. }
  3228. g.Time += g.IO.DeltaTime;
  3229. g.FrameCount += 1;
  3230. g.TooltipOverrideCount = 0;
  3231. g.WindowsActiveCount = 0;
  3232. UpdateViewports();
  3233. // Setup font, draw list shared data
  3234. // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
  3235. SetCurrentFont(GetDefaultFont());
  3236. IM_ASSERT(g.Font->IsLoaded());
  3237. ImVec2 virtual_space_max(0,0);
  3238. for (int n = 0; n < g.Viewports.Size; n++)
  3239. virtual_space_max = ImMax(virtual_space_max, g.Viewports[n]->Pos + g.Viewports[n]->Size);
  3240. g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, virtual_space_max.x, virtual_space_max.y);
  3241. g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
  3242. g.OverlayDrawList.Clear();
  3243. g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
  3244. g.OverlayDrawList.PushClipRectFullScreen();
  3245. g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
  3246. // Mark rendering data as invalid to prevent user who may have a handle on it to use it
  3247. for (int n = 0; n < g.Viewports.Size; n++)
  3248. {
  3249. g.Viewports[n]->DrawData = NULL;
  3250. g.Viewports[n]->DrawDataP.Clear();
  3251. }
  3252. // Clear reference to active widget if the widget isn't alive anymore
  3253. if (!g.HoveredIdPreviousFrame)
  3254. g.HoveredIdTimer = 0.0f;
  3255. g.HoveredIdPreviousFrame = g.HoveredId;
  3256. g.HoveredId = 0;
  3257. g.HoveredIdAllowOverlap = false;
  3258. if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  3259. ClearActiveID();
  3260. if (g.ActiveId)
  3261. g.ActiveIdTimer += g.IO.DeltaTime;
  3262. g.ActiveIdPreviousFrame = g.ActiveId;
  3263. g.ActiveIdIsAlive = false;
  3264. g.ActiveIdIsJustActivated = false;
  3265. if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
  3266. g.ScalarAsInputTextId = 0;
  3267. // Elapse drag & drop payload
  3268. if (g.DragDropActive && g.DragDropPayload.DataFrameCount + 1 < g.FrameCount)
  3269. {
  3270. ClearDragDrop();
  3271. g.DragDropPayloadBufHeap.clear();
  3272. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  3273. }
  3274. g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
  3275. g.DragDropAcceptIdCurr = 0;
  3276. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  3277. // Update keyboard input state
  3278. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  3279. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  3280. 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;
  3281. // Update gamepad/keyboard directional navigation
  3282. NavUpdate();
  3283. // Update mouse input state
  3284. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX component, but in reality we test for -256000.0f) we cancel out movement in MouseDelta
  3285. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev) && g.MouseViewport == g.MouseLastViewport)
  3286. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  3287. else
  3288. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  3289. if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
  3290. g.NavDisableMouseHover = false;
  3291. g.IO.MousePosPrev = g.IO.MousePos;
  3292. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  3293. {
  3294. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  3295. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  3296. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  3297. 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;
  3298. g.IO.MouseDoubleClicked[i] = false;
  3299. if (g.IO.MouseClicked[i])
  3300. {
  3301. if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
  3302. {
  3303. if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  3304. g.IO.MouseDoubleClicked[i] = true;
  3305. g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
  3306. }
  3307. else
  3308. {
  3309. g.IO.MouseClickedTime[i] = g.Time;
  3310. }
  3311. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  3312. g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
  3313. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  3314. }
  3315. else if (g.IO.MouseDown[i])
  3316. {
  3317. ImVec2 mouse_delta = g.IO.MousePos - g.IO.MouseClickedPos[i];
  3318. g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, mouse_delta.x < 0.0f ? -mouse_delta.x : mouse_delta.x);
  3319. g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, mouse_delta.y < 0.0f ? -mouse_delta.y : mouse_delta.y);
  3320. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(mouse_delta));
  3321. }
  3322. if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
  3323. g.NavDisableMouseHover = false;
  3324. }
  3325. // Calculate frame-rate for the user, as a purely luxurious feature
  3326. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  3327. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  3328. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  3329. g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
  3330. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
  3331. UpdateMovingWindow();
  3332. // Delay saving settings so we don't spam disk too much
  3333. if (g.SettingsDirtyTimer > 0.0f)
  3334. {
  3335. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  3336. if (g.SettingsDirtyTimer <= 0.0f)
  3337. SaveIniSettingsToDisk(g.IO.IniFilename);
  3338. }
  3339. // Find the window we are hovering
  3340. // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
  3341. // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point.
  3342. // - 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.
  3343. g.HoveredWindow = (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs)) ? g.MovingWindow : FindHoveredWindow();
  3344. g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
  3345. IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
  3346. ImGuiWindow* modal_window = GetFrontMostModalRootWindow();
  3347. if (modal_window != NULL)
  3348. {
  3349. g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  3350. if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
  3351. g.HoveredRootWindow = g.HoveredWindow = NULL;
  3352. }
  3353. else
  3354. {
  3355. g.ModalWindowDarkeningRatio = 0.0f;
  3356. }
  3357. // Update the WantCaptureMouse/WantCaptureKeyboard flags, so user can capture/discard the inputs away from the rest of their application.
  3358. // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
  3359. int mouse_earliest_button_down = -1;
  3360. bool mouse_any_down = false;
  3361. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  3362. {
  3363. if (g.IO.MouseClicked[i])
  3364. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
  3365. mouse_any_down |= g.IO.MouseDown[i];
  3366. if (g.IO.MouseDown[i])
  3367. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
  3368. mouse_earliest_button_down = i;
  3369. }
  3370. bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
  3371. if (g.WantCaptureMouseNextFrame != -1)
  3372. g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
  3373. else
  3374. g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
  3375. if (g.WantCaptureKeyboardNextFrame != -1)
  3376. g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
  3377. else
  3378. g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
  3379. if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
  3380. g.IO.WantCaptureKeyboard = true;
  3381. g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : 0;
  3382. g.MouseCursor = ImGuiMouseCursor_Arrow;
  3383. g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
  3384. g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  3385. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  3386. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
  3387. bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
  3388. if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
  3389. g.HoveredWindow = g.HoveredRootWindow = NULL;
  3390. // Mouse wheel scrolling, scale
  3391. if (g.HoveredWindow && !g.HoveredWindow->Collapsed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f))
  3392. {
  3393. // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
  3394. ImGuiWindow* window = g.HoveredWindow;
  3395. ImGuiWindow* scroll_window = window;
  3396. while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs) && scroll_window->ParentWindow)
  3397. scroll_window = scroll_window->ParentWindow;
  3398. const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs);
  3399. if (g.IO.MouseWheel != 0.0f)
  3400. {
  3401. if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  3402. {
  3403. // Zoom / Scale window
  3404. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  3405. const float scale = new_font_scale / window->FontWindowScale;
  3406. window->FontWindowScale = new_font_scale;
  3407. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  3408. window->Pos += offset;
  3409. window->PosFloat += offset;
  3410. window->Size *= scale;
  3411. window->SizeFull *= scale;
  3412. }
  3413. else if (!g.IO.KeyCtrl && scroll_allowed)
  3414. {
  3415. // Mouse wheel vertical scrolling
  3416. float scroll_amount = 5 * scroll_window->CalcFontSize();
  3417. scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
  3418. SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
  3419. }
  3420. }
  3421. if (g.IO.MouseWheelH != 0.0f && scroll_allowed)
  3422. {
  3423. // Mouse wheel horizontal scrolling (for hardware that supports it)
  3424. float scroll_amount = scroll_window->CalcFontSize();
  3425. if (!g.IO.KeyCtrl && !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
  3426. SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
  3427. }
  3428. }
  3429. // Pressing TAB activate widget focus
  3430. if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false))
  3431. {
  3432. if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
  3433. g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
  3434. else
  3435. g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0;
  3436. }
  3437. g.NavIdTabCounter = INT_MAX;
  3438. // Mark all windows as not visible
  3439. for (int i = 0; i != g.Windows.Size; i++)
  3440. {
  3441. ImGuiWindow* window = g.Windows[i];
  3442. window->WasActive = window->Active;
  3443. window->BeginCount = 0;
  3444. window->Active = false;
  3445. window->WriteAccessed = false;
  3446. }
  3447. // Closing the focused window restore focus to the first active root window in descending z-order
  3448. if (g.NavWindow && !g.NavWindow->WasActive)
  3449. FocusFrontMostActiveWindow(NULL);
  3450. // No window should be open at the beginning of the frame.
  3451. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  3452. g.CurrentWindowStack.resize(0);
  3453. g.CurrentPopupStack.resize(0);
  3454. ClosePopupsOverWindow(g.NavWindow);
  3455. // Create implicit window - we will only render it if the user has added something to it.
  3456. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
  3457. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
  3458. Begin("Debug##Default");
  3459. }
  3460. static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  3461. {
  3462. ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
  3463. if (!settings)
  3464. settings = AddWindowSettings(name);
  3465. return (void*)settings;
  3466. }
  3467. static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  3468. {
  3469. ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
  3470. float x, y;
  3471. int i;
  3472. ImU32 u1;
  3473. if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) { settings->Pos = ImVec2(x, y); }
  3474. else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) { settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize); }
  3475. else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
  3476. else if (sscanf(line, "ViewportPlatformPos=%f,%f", &x, &y)==2) { settings->ViewportPlatformPos = ImVec2(x, y); }
  3477. else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
  3478. }
  3479. static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  3480. {
  3481. // Gather data from windows that were active during this session
  3482. ImGuiContext& g = *imgui_ctx;
  3483. for (int i = 0; i != g.Windows.Size; i++)
  3484. {
  3485. ImGuiWindow* window = g.Windows[i];
  3486. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  3487. continue;
  3488. ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID);
  3489. if (!settings)
  3490. settings = AddWindowSettings(window->Name);
  3491. settings->Pos = window->Pos;// - window->Viewport->Pos;
  3492. settings->Size = window->SizeFull;
  3493. settings->ViewportId = window->ViewportId;
  3494. settings->ViewportPlatformPos = window->ViewportPlatformPos;
  3495. settings->Collapsed = window->Collapsed;
  3496. }
  3497. // Write a buffer
  3498. // If a window wasn't opened in this session we preserve its settings
  3499. buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
  3500. for (int i = 0; i != g.SettingsWindows.Size; i++)
  3501. {
  3502. const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
  3503. if (settings->Pos.x == FLT_MAX)
  3504. continue;
  3505. const char* name = settings->Name;
  3506. if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  3507. name = p;
  3508. buf->appendf("[%s][%s]\n", handler->TypeName, name);
  3509. buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
  3510. buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
  3511. if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
  3512. {
  3513. buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
  3514. if (settings->ViewportPlatformPos.x != FLT_MAX && settings->ViewportPlatformPos.y != FLT_MAX)
  3515. buf->appendf("ViewportPlatformPos=%d,%d\n", (int)settings->ViewportPlatformPos.x, (int)settings->ViewportPlatformPos.y);
  3516. }
  3517. buf->appendf("Collapsed=%d\n", settings->Collapsed);
  3518. buf->appendf("\n");
  3519. }
  3520. }
  3521. void ImGui::Initialize(ImGuiContext* context)
  3522. {
  3523. ImGuiContext& g = *context;
  3524. IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
  3525. g.LogClipboard = IM_NEW(ImGuiTextBuffer)();
  3526. // Add .ini handle for ImGuiWindow type
  3527. ImGuiSettingsHandler ini_handler;
  3528. ini_handler.TypeName = "Window";
  3529. ini_handler.TypeHash = ImHash("Window", 0, 0);
  3530. ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
  3531. ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
  3532. ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
  3533. g.SettingsHandlers.push_front(ini_handler);
  3534. // Create default viewport
  3535. ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
  3536. viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
  3537. viewport->Idx = 0;
  3538. g.Viewports.push_back(viewport);
  3539. g.Initialized = true;
  3540. }
  3541. void ImGui::DestroyPlatformWindows()
  3542. {
  3543. ImGuiContext& g = *GImGui;
  3544. if (g.PlatformIO.Renderer_DestroyWindow)
  3545. for (int i = 0; i < g.Viewports.Size; i++)
  3546. g.PlatformIO.Renderer_DestroyWindow(g.Viewports[i]);
  3547. if (g.PlatformIO.Platform_DestroyWindow)
  3548. for (int i = 0; i < g.Viewports.Size; i++)
  3549. g.PlatformIO.Platform_DestroyWindow(g.Viewports[i]);
  3550. }
  3551. // This function is merely here to free heap allocations.
  3552. void ImGui::Shutdown(ImGuiContext* context)
  3553. {
  3554. ImGuiContext& g = *context;
  3555. // 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)
  3556. if (g.IO.Fonts && g.FontAtlasOwnedByContext)
  3557. IM_DELETE(g.IO.Fonts);
  3558. // Cleanup of other data are conditional on actually having initialize ImGui.
  3559. if (!g.Initialized)
  3560. return;
  3561. SaveIniSettingsToDisk(g.IO.IniFilename);
  3562. // Destroy platform windows
  3563. ImGuiContext* backup_context = ImGui::GetCurrentContext();
  3564. SetCurrentContext(context);
  3565. DestroyPlatformWindows();
  3566. SetCurrentContext(backup_context);
  3567. // Clear everything else
  3568. for (int i = 0; i < g.Windows.Size; i++)
  3569. IM_DELETE(g.Windows[i]);
  3570. g.Windows.clear();
  3571. g.WindowsSortBuffer.clear();
  3572. g.CurrentWindow = NULL;
  3573. g.CurrentWindowStack.clear();
  3574. g.WindowsById.Clear();
  3575. g.NavWindow = NULL;
  3576. g.HoveredWindow = NULL;
  3577. g.HoveredRootWindow = NULL;
  3578. g.ActiveIdWindow = NULL;
  3579. g.MovingWindow = NULL;
  3580. for (int i = 0; i < g.SettingsWindows.Size; i++)
  3581. IM_DELETE(g.SettingsWindows[i].Name);
  3582. g.ColorModifiers.clear();
  3583. g.StyleModifiers.clear();
  3584. g.FontStack.clear();
  3585. g.OpenPopupStack.clear();
  3586. g.CurrentPopupStack.clear();
  3587. g.CurrentViewport = g.MouseViewport = g.MouseLastViewport = g.MouseLastHoveredViewport = NULL;
  3588. for (int i = 0; i < g.Viewports.Size; i++)
  3589. IM_DELETE(g.Viewports[i]);
  3590. g.Viewports.clear();
  3591. g.OverlayDrawList.ClearFreeMemory();
  3592. g.PrivateClipboard.clear();
  3593. g.InputTextState.Text.clear();
  3594. g.InputTextState.InitialText.clear();
  3595. g.InputTextState.TempTextBuffer.clear();
  3596. g.SettingsWindows.clear();
  3597. g.SettingsHandlers.clear();
  3598. if (g.LogFile && g.LogFile != stdout)
  3599. {
  3600. fclose(g.LogFile);
  3601. g.LogFile = NULL;
  3602. }
  3603. if (g.LogClipboard)
  3604. IM_DELETE(g.LogClipboard);
  3605. g.Initialized = false;
  3606. }
  3607. ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
  3608. {
  3609. ImGuiContext& g = *GImGui;
  3610. for (int i = 0; i != g.SettingsWindows.Size; i++)
  3611. if (g.SettingsWindows[i].Id == id)
  3612. return &g.SettingsWindows[i];
  3613. return NULL;
  3614. }
  3615. static ImGuiWindowSettings* AddWindowSettings(const char* name)
  3616. {
  3617. ImGuiContext& g = *GImGui;
  3618. g.SettingsWindows.push_back(ImGuiWindowSettings());
  3619. ImGuiWindowSettings* settings = &g.SettingsWindows.back();
  3620. settings->Name = ImStrdup(name);
  3621. settings->Id = ImHash(name, 0);
  3622. return settings;
  3623. }
  3624. static void LoadIniSettingsFromDisk(const char* ini_filename)
  3625. {
  3626. if (!ini_filename)
  3627. return;
  3628. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", NULL, +1);
  3629. if (!file_data)
  3630. return;
  3631. LoadIniSettingsFromMemory(file_data);
  3632. ImGui::MemFree(file_data);
  3633. }
  3634. ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
  3635. {
  3636. ImGuiContext& g = *GImGui;
  3637. const ImGuiID type_hash = ImHash(type_name, 0, 0);
  3638. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  3639. if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
  3640. return &g.SettingsHandlers[handler_n];
  3641. return NULL;
  3642. }
  3643. // Zero-tolerance, no error reporting, cheap .ini parsing
  3644. static void LoadIniSettingsFromMemory(const char* buf_readonly)
  3645. {
  3646. // For convenience and to make the code simpler, we'll write zero terminators inside the buffer. So let's create a writable copy.
  3647. char* buf = ImStrdup(buf_readonly);
  3648. char* buf_end = buf + strlen(buf);
  3649. ImGuiContext& g = *GImGui;
  3650. void* entry_data = NULL;
  3651. ImGuiSettingsHandler* entry_handler = NULL;
  3652. char* line_end = NULL;
  3653. for (char* line = buf; line < buf_end; line = line_end + 1)
  3654. {
  3655. // Skip new lines markers, then find end of the line
  3656. while (*line == '\n' || *line == '\r')
  3657. line++;
  3658. line_end = line;
  3659. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  3660. line_end++;
  3661. line_end[0] = 0;
  3662. if (line[0] == '[' && line_end > line && line_end[-1] == ']')
  3663. {
  3664. // Close last entry
  3665. if (entry_data && entry_handler && entry_handler->ReadCloseFn)
  3666. entry_handler->ReadCloseFn(&g, entry_handler, entry_data);
  3667. // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
  3668. line_end[-1] = 0;
  3669. const char* name_end = line_end - 1;
  3670. const char* type_start = line + 1;
  3671. char* type_end = ImStrchrRange(type_start, name_end, ']');
  3672. const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
  3673. if (!type_end || !name_start)
  3674. {
  3675. name_start = type_start; // Import legacy entries that have no type
  3676. type_start = "Window";
  3677. }
  3678. else
  3679. {
  3680. *type_end = 0; // Overwrite first ']'
  3681. name_start++; // Skip second '['
  3682. }
  3683. entry_handler = ImGui::FindSettingsHandler(type_start);
  3684. entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
  3685. }
  3686. else if (entry_handler != NULL && entry_data != NULL)
  3687. {
  3688. // Let type handler parse the line
  3689. entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
  3690. }
  3691. }
  3692. // Close last entry
  3693. if (entry_data && entry_handler && entry_handler->ReadCloseFn)
  3694. entry_handler->ReadCloseFn(&g, entry_handler, entry_data);
  3695. ImGui::MemFree(buf);
  3696. g.SettingsLoaded = true;
  3697. }
  3698. static void SaveIniSettingsToDisk(const char* ini_filename)
  3699. {
  3700. ImGuiContext& g = *GImGui;
  3701. g.SettingsDirtyTimer = 0.0f;
  3702. if (!ini_filename)
  3703. return;
  3704. ImVector<char> buf;
  3705. SaveIniSettingsToMemory(buf);
  3706. FILE* f = ImFileOpen(ini_filename, "wt");
  3707. if (!f)
  3708. return;
  3709. fwrite(buf.Data, sizeof(char), (size_t)buf.Size, f);
  3710. fclose(f);
  3711. }
  3712. static void SaveIniSettingsToMemory(ImVector<char>& out_buf)
  3713. {
  3714. ImGuiContext& g = *GImGui;
  3715. g.SettingsDirtyTimer = 0.0f;
  3716. ImGuiTextBuffer buf;
  3717. for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
  3718. {
  3719. ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
  3720. handler->WriteAllFn(&g, handler, &buf);
  3721. }
  3722. buf.Buf.pop_back(); // Remove extra zero-terminator used by ImGuiTextBuffer
  3723. out_buf.swap(buf.Buf);
  3724. }
  3725. void ImGui::MarkIniSettingsDirty()
  3726. {
  3727. ImGuiContext& g = *GImGui;
  3728. if (g.SettingsDirtyTimer <= 0.0f)
  3729. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  3730. }
  3731. static void MarkIniSettingsDirty(ImGuiWindow* window)
  3732. {
  3733. ImGuiContext& g = *GImGui;
  3734. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  3735. if (g.SettingsDirtyTimer <= 0.0f)
  3736. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  3737. }
  3738. // FIXME: Add a more explicit sort order in the window structure.
  3739. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
  3740. {
  3741. const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
  3742. const ImGuiWindow* b = *(const ImGuiWindow**)rhs;
  3743. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  3744. return d;
  3745. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  3746. return d;
  3747. return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
  3748. }
  3749. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
  3750. {
  3751. out_sorted_windows->push_back(window);
  3752. if (window->Active)
  3753. {
  3754. int count = window->DC.ChildWindows.Size;
  3755. if (count > 1)
  3756. qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  3757. for (int i = 0; i < count; i++)
  3758. {
  3759. ImGuiWindow* child = window->DC.ChildWindows[i];
  3760. if (child->Active)
  3761. AddWindowToSortedBuffer(out_sorted_windows, child);
  3762. }
  3763. }
  3764. }
  3765. static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
  3766. {
  3767. if (draw_list->CmdBuffer.empty())
  3768. return;
  3769. // Remove trailing command if unused
  3770. ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
  3771. if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
  3772. {
  3773. draw_list->CmdBuffer.pop_back();
  3774. if (draw_list->CmdBuffer.empty())
  3775. return;
  3776. }
  3777. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
  3778. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  3779. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  3780. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  3781. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
  3782. // If this assert triggers because you are drawing lots of stuff manually:
  3783. // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
  3784. // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
  3785. // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
  3786. // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
  3787. // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
  3788. // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
  3789. if (sizeof(ImDrawIdx) == 2)
  3790. IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
  3791. out_list->push_back(draw_list);
  3792. }
  3793. static void AddWindowToDrawData(ImVector<ImDrawList*>* out_list, ImGuiWindow* window)
  3794. {
  3795. AddDrawListToDrawData(out_list, window->DrawList);
  3796. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  3797. {
  3798. ImGuiWindow* child = window->DC.ChildWindows[i];
  3799. if (child->Active && child->HiddenFrames <= 0) // clipped children may have been marked not active
  3800. AddWindowToDrawData(out_list, child);
  3801. }
  3802. }
  3803. static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window)
  3804. {
  3805. ImGuiContext& g = *GImGui;
  3806. g.IO.MetricsActiveWindows++;
  3807. if (window->Flags & ImGuiWindowFlags_Tooltip)
  3808. AddWindowToDrawData(&window->Viewport->DrawDataBuilder.Layers[1], window);
  3809. else
  3810. AddWindowToDrawData(&window->Viewport->DrawDataBuilder.Layers[0], window);
  3811. }
  3812. void ImDrawDataBuilder::FlattenIntoSingleLayer()
  3813. {
  3814. int n = Layers[0].Size;
  3815. int size = n;
  3816. for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
  3817. size += Layers[i].Size;
  3818. Layers[0].resize(size);
  3819. for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
  3820. {
  3821. ImVector<ImDrawList*>& layer = Layers[layer_n];
  3822. if (layer.empty())
  3823. continue;
  3824. memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  3825. n += layer.Size;
  3826. layer.resize(0);
  3827. }
  3828. }
  3829. static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
  3830. {
  3831. ImDrawData* draw_data = &viewport->DrawDataP;
  3832. viewport->DrawData = draw_data; // Make publicly accessible
  3833. draw_data->Valid = true;
  3834. draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
  3835. draw_data->CmdListsCount = draw_lists->Size;
  3836. draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
  3837. draw_data->DisplayPos = viewport->Pos;
  3838. draw_data->DisplaySize = viewport->Size;
  3839. for (int n = 0; n < draw_lists->Size; n++)
  3840. {
  3841. draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
  3842. draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
  3843. }
  3844. }
  3845. // 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.
  3846. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  3847. {
  3848. ImGuiWindow* window = GetCurrentWindow();
  3849. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  3850. window->ClipRect = window->DrawList->_ClipRectStack.back();
  3851. }
  3852. void ImGui::PopClipRect()
  3853. {
  3854. ImGuiWindow* window = GetCurrentWindow();
  3855. window->DrawList->PopClipRect();
  3856. window->ClipRect = window->DrawList->_ClipRectStack.back();
  3857. }
  3858. // 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.
  3859. void ImGui::EndFrame()
  3860. {
  3861. ImGuiContext& g = *GImGui;
  3862. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  3863. if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
  3864. return;
  3865. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  3866. if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
  3867. {
  3868. g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
  3869. g.OsImePosSet = g.OsImePosRequest;
  3870. }
  3871. // Hide implicit "Debug" window if it hasn't been used
  3872. IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
  3873. if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
  3874. g.CurrentWindow->Active = false;
  3875. End();
  3876. SetCurrentViewport(NULL);
  3877. if (g.ActiveId == 0 && g.HoveredId == 0)
  3878. {
  3879. if (!g.NavWindow || !g.NavWindow->Appearing) // Unless we just made a window/popup appear
  3880. {
  3881. // Click to focus window and start moving (after we're done with all our widgets)
  3882. if (g.IO.MouseClicked[0])
  3883. {
  3884. if (g.HoveredRootWindow != NULL)
  3885. {
  3886. // Set ActiveId even if the _NoMove flag is set, without it dragging away from a window with _NoMove would activate hover on other windows.
  3887. FocusWindow(g.HoveredWindow);
  3888. SetActiveID(g.HoveredWindow->MoveId, g.HoveredWindow);
  3889. g.NavDisableHighlight = true;
  3890. g.ActiveIdClickOffset = g.IO.MousePos - g.HoveredRootWindow->Pos;
  3891. if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove) && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoMove))
  3892. g.MovingWindow = g.HoveredWindow;
  3893. }
  3894. else if (g.NavWindow != NULL && GetFrontMostModalRootWindow() == NULL)
  3895. {
  3896. // Clicking on void disable focus
  3897. FocusWindow(NULL);
  3898. }
  3899. }
  3900. // With right mouse button we close popups without changing focus
  3901. // (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger)
  3902. if (g.IO.MouseClicked[1])
  3903. {
  3904. // Find the top-most window between HoveredWindow and the front most Modal Window.
  3905. // This is where we can trim the popup stack.
  3906. ImGuiWindow* modal = GetFrontMostModalRootWindow();
  3907. bool hovered_window_above_modal = false;
  3908. if (modal == NULL)
  3909. hovered_window_above_modal = true;
  3910. for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
  3911. {
  3912. ImGuiWindow* window = g.Windows[i];
  3913. if (window == modal)
  3914. break;
  3915. if (window == g.HoveredWindow)
  3916. hovered_window_above_modal = true;
  3917. }
  3918. ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal);
  3919. }
  3920. }
  3921. }
  3922. // Update user-side viewport list
  3923. g.PlatformData.MainViewport = g.Viewports[0];
  3924. g.PlatformData.Viewports.resize(0);
  3925. for (int i = 0; i < g.Viewports.Size; i++)
  3926. {
  3927. ImGuiViewportP* viewport = g.Viewports[i];
  3928. if (viewport->LastFrameActive < g.FrameCount)
  3929. continue;
  3930. if (i > 0)
  3931. IM_ASSERT(viewport->Window != NULL);
  3932. g.PlatformData.Viewports.push_back(viewport);
  3933. }
  3934. // Sort the window list so that all child windows are after their parent
  3935. // We cannot do that on FocusWindow() because childs may not exist yet
  3936. g.WindowsSortBuffer.resize(0);
  3937. g.WindowsSortBuffer.reserve(g.Windows.Size);
  3938. for (int i = 0; i != g.Windows.Size; i++)
  3939. {
  3940. ImGuiWindow* window = g.Windows[i];
  3941. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  3942. continue;
  3943. AddWindowToSortedBuffer(&g.WindowsSortBuffer, window);
  3944. }
  3945. IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
  3946. g.Windows.swap(g.WindowsSortBuffer);
  3947. // Clear Input data for next frame
  3948. g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
  3949. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  3950. memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
  3951. g.FrameCountEnded = g.FrameCount;
  3952. }
  3953. void ImGui::Render()
  3954. {
  3955. ImGuiContext& g = *GImGui;
  3956. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  3957. if (g.FrameCountEnded != g.FrameCount)
  3958. ImGui::EndFrame();
  3959. g.FrameCountRendered = g.FrameCount;
  3960. // Gather windows to render
  3961. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
  3962. for (int n = 0; n != g.Viewports.Size; n++)
  3963. g.Viewports[n]->DrawDataBuilder.Clear();
  3964. ImGuiWindow* window_to_render_front_most = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget : NULL;
  3965. for (int n = 0; n != g.Windows.Size; n++)
  3966. {
  3967. ImGuiWindow* window = g.Windows[n];
  3968. if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0 && window != window_to_render_front_most)
  3969. AddWindowToDrawDataSelectLayer(window);
  3970. }
  3971. if (window_to_render_front_most && window_to_render_front_most->Active && window_to_render_front_most->HiddenFrames <= 0) // NavWindowingTarget is always temporarily displayed as the front-most window
  3972. AddWindowToDrawDataSelectLayer(window_to_render_front_most);
  3973. // Draw software mouse cursor if requested
  3974. ImVec2 offset, size, uv[4];
  3975. if (g.IO.MouseDrawCursor && g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &offset, &size, &uv[0], &uv[2]))
  3976. {
  3977. const ImVec2 pos = g.IO.MousePos - offset;
  3978. const ImTextureID tex_id = g.IO.Fonts->TexID;
  3979. const float sc = g.Style.MouseCursorScale;
  3980. g.OverlayDrawList.PushClipRect(g.MouseViewport->Pos, g.MouseViewport->Pos + g.MouseViewport->Size);
  3981. g.OverlayDrawList.PushTextureID(tex_id);
  3982. g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(1,0)*sc, pos+ImVec2(1,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
  3983. g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(2,0)*sc, pos+ImVec2(2,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
  3984. g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[2], uv[3], IM_COL32(0,0,0,255)); // Black border
  3985. g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[0], uv[1], IM_COL32(255,255,255,255)); // White fill
  3986. g.OverlayDrawList.PopTextureID();
  3987. g.OverlayDrawList.PopClipRect();
  3988. }
  3989. // Setup ImDrawData structures for end-user
  3990. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
  3991. for (int n = 0; n < g.Viewports.Size; n++)
  3992. {
  3993. ImGuiViewportP* viewport = g.Viewports[n];
  3994. viewport->DrawDataBuilder.FlattenIntoSingleLayer();
  3995. AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], &g.OverlayDrawList);
  3996. SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
  3997. g.IO.MetricsRenderVertices += viewport->DrawData->TotalVtxCount;
  3998. g.IO.MetricsRenderIndices += viewport->DrawData->TotalIdxCount;
  3999. }
  4000. // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
  4001. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  4002. if (g.Viewports[0]->DrawData->CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
  4003. g.IO.RenderDrawListsFn(g.Viewports[0]->DrawData);
  4004. #endif
  4005. }
  4006. ImGuiViewport* ImGui::GetMainViewport()
  4007. {
  4008. ImGuiContext& g = *GImGui;
  4009. return g.Viewports[0];
  4010. }
  4011. ImGuiViewportP* ImGui::FindViewportByID(ImGuiID id)
  4012. {
  4013. ImGuiContext& g = *GImGui;
  4014. for (int n = 0; n < g.Viewports.Size; n++)
  4015. if (g.Viewports[n]->ID == id)
  4016. return g.Viewports[n];
  4017. return NULL;
  4018. }
  4019. ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
  4020. {
  4021. ImGuiContext& g = *GImGui;
  4022. for (int i = 0; i != g.Viewports.Size; i++)
  4023. if (g.Viewports[i]->PlatformHandle == platform_handle)
  4024. return g.Viewports[i];
  4025. return NULL;
  4026. }
  4027. static void TranslateWindowX(ImGuiWindow* window, float dx)
  4028. {
  4029. window->Pos.x += dx;
  4030. window->PosFloat.x += dx;
  4031. window->ClipRect.Translate(dx, 0.0f);
  4032. window->WindowRectClipped.Translate(dx, 0.0f);
  4033. window->InnerRect.Translate(dx, 0.0f);
  4034. window->DC.CursorPos.x += dx;
  4035. window->DC.CursorStartPos.x += dx;
  4036. window->DC.CursorMaxPos.x += dx;
  4037. window->DC.LastItemRect.Translate(dx, 0.0f);
  4038. window->DC.LastItemDisplayRect.Translate(dx, 0.0f);
  4039. }
  4040. static void ImGui::ResizeViewportTranslateWindows(int viewport_idx_min, int viewport_idx_max, float pos_x_delta, int idx_delta, ImGuiViewport* viewport_to_erase)
  4041. {
  4042. ImGuiContext& g = *GImGui;
  4043. IM_ASSERT(pos_x_delta != 0.0f || idx_delta != 0);
  4044. IM_ASSERT(g.CurrentViewport == NULL); // We only resize at the beginning of the frame
  4045. for (int n = 0; n < g.Windows.Size; n++)
  4046. {
  4047. ImGuiWindow* window = g.Windows[n];
  4048. if (window->Viewport == viewport_to_erase)
  4049. window->Viewport = NULL; // Set to NULL so window->ViewportId becomes the master data
  4050. if (window->Viewport == NULL)
  4051. continue;
  4052. if (window->Viewport->Idx < viewport_idx_min || window->Viewport->Idx > viewport_idx_max)
  4053. continue;
  4054. TranslateWindowX(window, pos_x_delta);
  4055. }
  4056. for (int n = viewport_idx_min; n < viewport_idx_max; n++)
  4057. {
  4058. g.Viewports[n]->Pos.x += pos_x_delta;
  4059. g.Viewports[n]->Idx += idx_delta;
  4060. }
  4061. }
  4062. void ImGui::SetCurrentViewport(ImGuiViewportP* viewport)
  4063. {
  4064. // Notify platform layer of viewport changes
  4065. // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
  4066. ImGuiContext& g = *GImGui;
  4067. if (viewport)
  4068. viewport->LastFrameActive = g.FrameCount;
  4069. if (g.CurrentViewport == viewport)
  4070. return;
  4071. g.CurrentViewport = viewport;
  4072. if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
  4073. g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
  4074. }
  4075. ImGuiViewportP* ImGui::Viewport(ImGuiWindow* window, ImGuiID id, ImGuiViewportFlags flags, const ImVec2& platform_pos, const ImVec2& size)
  4076. {
  4077. ImGuiContext& g = *GImGui;
  4078. IM_ASSERT(id != 0);
  4079. ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
  4080. if (viewport)
  4081. {
  4082. // We defer translating windows to the beginning of the frame.
  4083. // Our viewport system already works with fully overlapped viewports, it's only certain user interactions that don't and they can't be performed while resizing.
  4084. viewport->Size = size;
  4085. }
  4086. else
  4087. {
  4088. // New viewport
  4089. viewport = IM_NEW(ImGuiViewportP)();
  4090. viewport->ID = id;
  4091. viewport->Idx = g.Viewports.Size;
  4092. viewport->Pos = ImVec2(g.Viewports.back()->GetNextX(), 0.0f);
  4093. viewport->Size = size;
  4094. g.Viewports.push_back(viewport);
  4095. }
  4096. IM_ASSERT(viewport->Pos.y == 0.0f);
  4097. viewport->Window = window;
  4098. viewport->Flags = flags;
  4099. viewport->PlatformPos = platform_pos;
  4100. viewport->LastFrameActive = g.FrameCount;
  4101. // Request an initial DpiScale before the OS platform window creation
  4102. if (g.PlatformIO.Platform_GetWindowDpiScale)
  4103. viewport->DpiScale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
  4104. return viewport;
  4105. }
  4106. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  4107. {
  4108. const char* text_display_end = text;
  4109. if (!text_end)
  4110. text_end = (const char*)-1;
  4111. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  4112. text_display_end++;
  4113. return text_display_end;
  4114. }
  4115. // Pass text data straight to log (without being displayed)
  4116. void ImGui::LogText(const char* fmt, ...)
  4117. {
  4118. ImGuiContext& g = *GImGui;
  4119. if (!g.LogEnabled)
  4120. return;
  4121. va_list args;
  4122. va_start(args, fmt);
  4123. if (g.LogFile)
  4124. {
  4125. vfprintf(g.LogFile, fmt, args);
  4126. }
  4127. else
  4128. {
  4129. g.LogClipboard->appendfv(fmt, args);
  4130. }
  4131. va_end(args);
  4132. }
  4133. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  4134. // We split text into individual lines to add current tree level padding
  4135. static void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL)
  4136. {
  4137. ImGuiContext& g = *GImGui;
  4138. ImGuiWindow* window = g.CurrentWindow;
  4139. if (!text_end)
  4140. text_end = ImGui::FindRenderedTextEnd(text, text_end);
  4141. const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1);
  4142. if (ref_pos)
  4143. window->DC.LogLinePosY = ref_pos->y;
  4144. const char* text_remaining = text;
  4145. if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
  4146. g.LogStartDepth = window->DC.TreeDepth;
  4147. const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
  4148. for (;;)
  4149. {
  4150. // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
  4151. const char* line_end = text_remaining;
  4152. while (line_end < text_end)
  4153. if (*line_end == '\n')
  4154. break;
  4155. else
  4156. line_end++;
  4157. if (line_end >= text_end)
  4158. line_end = NULL;
  4159. const bool is_first_line = (text == text_remaining);
  4160. bool is_last_line = false;
  4161. if (line_end == NULL)
  4162. {
  4163. is_last_line = true;
  4164. line_end = text_end;
  4165. }
  4166. if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
  4167. {
  4168. const int char_count = (int)(line_end - text_remaining);
  4169. if (log_new_line || !is_first_line)
  4170. ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining);
  4171. else
  4172. ImGui::LogText(" %.*s", char_count, text_remaining);
  4173. }
  4174. if (is_last_line)
  4175. break;
  4176. text_remaining = line_end + 1;
  4177. }
  4178. }
  4179. // Internal ImGui functions to render text
  4180. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  4181. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  4182. {
  4183. ImGuiContext& g = *GImGui;
  4184. ImGuiWindow* window = g.CurrentWindow;
  4185. // Hide anything after a '##' string
  4186. const char* text_display_end;
  4187. if (hide_text_after_hash)
  4188. {
  4189. text_display_end = FindRenderedTextEnd(text, text_end);
  4190. }
  4191. else
  4192. {
  4193. if (!text_end)
  4194. text_end = text + strlen(text); // FIXME-OPT
  4195. text_display_end = text_end;
  4196. }
  4197. const int text_len = (int)(text_display_end - text);
  4198. if (text_len > 0)
  4199. {
  4200. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  4201. if (g.LogEnabled)
  4202. LogRenderedText(&pos, text, text_display_end);
  4203. }
  4204. }
  4205. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  4206. {
  4207. ImGuiContext& g = *GImGui;
  4208. ImGuiWindow* window = g.CurrentWindow;
  4209. if (!text_end)
  4210. text_end = text + strlen(text); // FIXME-OPT
  4211. const int text_len = (int)(text_end - text);
  4212. if (text_len > 0)
  4213. {
  4214. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  4215. if (g.LogEnabled)
  4216. LogRenderedText(&pos, text, text_end);
  4217. }
  4218. }
  4219. // Default clip_rect uses (pos_min,pos_max)
  4220. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  4221. 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)
  4222. {
  4223. // Hide anything after a '##' string
  4224. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  4225. const int text_len = (int)(text_display_end - text);
  4226. if (text_len == 0)
  4227. return;
  4228. ImGuiContext& g = *GImGui;
  4229. ImGuiWindow* window = g.CurrentWindow;
  4230. // Perform CPU side clipping for single clipped element to avoid using scissor state
  4231. ImVec2 pos = pos_min;
  4232. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  4233. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  4234. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  4235. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  4236. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  4237. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  4238. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  4239. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  4240. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  4241. // Render
  4242. if (need_clipping)
  4243. {
  4244. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  4245. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  4246. }
  4247. else
  4248. {
  4249. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  4250. }
  4251. if (g.LogEnabled)
  4252. LogRenderedText(&pos, text, text_display_end);
  4253. }
  4254. // Render a rectangle shaped with optional rounding and borders
  4255. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  4256. {
  4257. ImGuiContext& g = *GImGui;
  4258. ImGuiWindow* window = g.CurrentWindow;
  4259. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  4260. const float border_size = g.Style.FrameBorderSize;
  4261. if (border && border_size > 0.0f)
  4262. {
  4263. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  4264. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  4265. }
  4266. }
  4267. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  4268. {
  4269. ImGuiContext& g = *GImGui;
  4270. ImGuiWindow* window = g.CurrentWindow;
  4271. const float border_size = g.Style.FrameBorderSize;
  4272. if (border_size > 0.0f)
  4273. {
  4274. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
  4275. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
  4276. }
  4277. }
  4278. // Render a triangle to denote expanded/collapsed state
  4279. void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
  4280. {
  4281. ImGuiContext& g = *GImGui;
  4282. ImGuiWindow* window = g.CurrentWindow;
  4283. const float h = g.FontSize * 1.00f;
  4284. float r = h * 0.40f * scale;
  4285. ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
  4286. ImVec2 a, b, c;
  4287. switch (dir)
  4288. {
  4289. case ImGuiDir_Up:
  4290. case ImGuiDir_Down:
  4291. if (dir == ImGuiDir_Up) r = -r;
  4292. center.y -= r * 0.25f;
  4293. a = ImVec2(0,1) * r;
  4294. b = ImVec2(-0.866f,-0.5f) * r;
  4295. c = ImVec2(+0.866f,-0.5f) * r;
  4296. break;
  4297. case ImGuiDir_Left:
  4298. case ImGuiDir_Right:
  4299. if (dir == ImGuiDir_Left) r = -r;
  4300. center.x -= r * 0.25f;
  4301. a = ImVec2(1,0) * r;
  4302. b = ImVec2(-0.500f,+0.866f) * r;
  4303. c = ImVec2(-0.500f,-0.866f) * r;
  4304. break;
  4305. case ImGuiDir_None:
  4306. case ImGuiDir_COUNT:
  4307. IM_ASSERT(0);
  4308. break;
  4309. }
  4310. window->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
  4311. }
  4312. void ImGui::RenderBullet(ImVec2 pos)
  4313. {
  4314. ImGuiContext& g = *GImGui;
  4315. ImGuiWindow* window = g.CurrentWindow;
  4316. window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
  4317. }
  4318. void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
  4319. {
  4320. ImGuiContext& g = *GImGui;
  4321. ImGuiWindow* window = g.CurrentWindow;
  4322. float thickness = ImMax(sz / 5.0f, 1.0f);
  4323. sz -= thickness*0.5f;
  4324. pos += ImVec2(thickness*0.25f, thickness*0.25f);
  4325. float third = sz / 3.0f;
  4326. float bx = pos.x + third;
  4327. float by = pos.y + sz - third*0.5f;
  4328. window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
  4329. window->DrawList->PathLineTo(ImVec2(bx, by));
  4330. window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
  4331. window->DrawList->PathStroke(col, false, thickness);
  4332. }
  4333. void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
  4334. {
  4335. ImGuiContext& g = *GImGui;
  4336. if (id != g.NavId)
  4337. return;
  4338. if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
  4339. return;
  4340. ImGuiWindow* window = ImGui::GetCurrentWindow();
  4341. if (window->DC.NavHideHighlightOneFrame)
  4342. return;
  4343. float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
  4344. ImRect display_rect = bb;
  4345. display_rect.ClipWith(window->ClipRect);
  4346. if (flags & ImGuiNavHighlightFlags_TypeDefault)
  4347. {
  4348. const float THICKNESS = 2.0f;
  4349. const float DISTANCE = 3.0f + THICKNESS * 0.5f;
  4350. display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
  4351. bool fully_visible = window->ClipRect.Contains(display_rect);
  4352. if (!fully_visible)
  4353. window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
  4354. 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);
  4355. if (!fully_visible)
  4356. window->DrawList->PopClipRect();
  4357. }
  4358. if (flags & ImGuiNavHighlightFlags_TypeThin)
  4359. {
  4360. window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
  4361. }
  4362. }
  4363. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  4364. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
  4365. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  4366. {
  4367. ImGuiContext& g = *GImGui;
  4368. const char* text_display_end;
  4369. if (hide_text_after_double_hash)
  4370. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  4371. else
  4372. text_display_end = text_end;
  4373. ImFont* font = g.Font;
  4374. const float font_size = g.FontSize;
  4375. if (text == text_display_end)
  4376. return ImVec2(0.0f, font_size);
  4377. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  4378. // Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field)
  4379. const float font_scale = font_size / font->FontSize;
  4380. const float character_spacing_x = 1.0f * font_scale;
  4381. if (text_size.x > 0.0f)
  4382. text_size.x -= character_spacing_x;
  4383. text_size.x = (float)(int)(text_size.x + 0.95f);
  4384. return text_size;
  4385. }
  4386. // Helper to calculate coarse clipping of large list of evenly sized items.
  4387. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
  4388. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  4389. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  4390. {
  4391. ImGuiContext& g = *GImGui;
  4392. ImGuiWindow* window = g.CurrentWindow;
  4393. if (g.LogEnabled)
  4394. {
  4395. // If logging is active, do not perform any clipping
  4396. *out_items_display_start = 0;
  4397. *out_items_display_end = items_count;
  4398. return;
  4399. }
  4400. if (window->SkipItems)
  4401. {
  4402. *out_items_display_start = *out_items_display_end = 0;
  4403. return;
  4404. }
  4405. const ImVec2 pos = window->DC.CursorPos;
  4406. int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
  4407. int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
  4408. if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Up) // When performing a navigation request, ensure we have one item extra in the direction we are moving to
  4409. start--;
  4410. if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down)
  4411. end++;
  4412. start = ImClamp(start, 0, items_count);
  4413. end = ImClamp(end + 1, start, items_count);
  4414. *out_items_display_start = start;
  4415. *out_items_display_end = end;
  4416. }
  4417. // Find window given position, search front-to-back
  4418. // FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected.
  4419. static ImGuiWindow* FindHoveredWindow()
  4420. {
  4421. ImGuiContext& g = *GImGui;
  4422. for (int i = g.Windows.Size - 1; i >= 0; i--)
  4423. {
  4424. ImGuiWindow* window = g.Windows[i];
  4425. if (!window->Active)
  4426. continue;
  4427. if (window->Flags & ImGuiWindowFlags_NoInputs)
  4428. continue;
  4429. IM_ASSERT(window->Viewport);
  4430. if (window->Viewport != g.MouseViewport)
  4431. continue;
  4432. // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
  4433. ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
  4434. if (bb.Contains(g.IO.MousePos))
  4435. return window;
  4436. }
  4437. return NULL;
  4438. }
  4439. // Test if mouse cursor is hovering given rectangle
  4440. // NB- Rectangle is clipped by our current clip setting
  4441. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  4442. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  4443. {
  4444. ImGuiContext& g = *GImGui;
  4445. ImGuiWindow* window = g.CurrentWindow;
  4446. // Clip
  4447. ImRect rect_clipped(r_min, r_max);
  4448. if (clip)
  4449. rect_clipped.ClipWith(window->ClipRect);
  4450. // Expand for touch input
  4451. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  4452. if (!rect_for_touch.Contains(g.IO.MousePos))
  4453. return false;
  4454. if (!g.MouseViewport->GetRect().Overlaps(rect_clipped))
  4455. return false;
  4456. return true;
  4457. }
  4458. static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
  4459. {
  4460. const int key_index = GImGui->IO.KeyMap[key];
  4461. return (key_index >= 0) ? ImGui::IsKeyPressed(key_index, repeat) : false;
  4462. }
  4463. int ImGui::GetKeyIndex(ImGuiKey imgui_key)
  4464. {
  4465. IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
  4466. return GImGui->IO.KeyMap[imgui_key];
  4467. }
  4468. // Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your back-end/engine stored them into KeyDown[]!
  4469. bool ImGui::IsKeyDown(int user_key_index)
  4470. {
  4471. if (user_key_index < 0) return false;
  4472. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
  4473. return GImGui->IO.KeysDown[user_key_index];
  4474. }
  4475. int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
  4476. {
  4477. if (t == 0.0f)
  4478. return 1;
  4479. if (t <= repeat_delay || repeat_rate <= 0.0f)
  4480. return 0;
  4481. const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
  4482. return (count > 0) ? count : 0;
  4483. }
  4484. int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
  4485. {
  4486. ImGuiContext& g = *GImGui;
  4487. if (key_index < 0) return false;
  4488. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4489. const float t = g.IO.KeysDownDuration[key_index];
  4490. return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
  4491. }
  4492. bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
  4493. {
  4494. ImGuiContext& g = *GImGui;
  4495. if (user_key_index < 0) return false;
  4496. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4497. const float t = g.IO.KeysDownDuration[user_key_index];
  4498. if (t == 0.0f)
  4499. return true;
  4500. if (repeat && t > g.IO.KeyRepeatDelay)
  4501. return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  4502. return false;
  4503. }
  4504. bool ImGui::IsKeyReleased(int user_key_index)
  4505. {
  4506. ImGuiContext& g = *GImGui;
  4507. if (user_key_index < 0) return false;
  4508. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  4509. return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
  4510. }
  4511. bool ImGui::IsMouseDown(int button)
  4512. {
  4513. ImGuiContext& g = *GImGui;
  4514. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4515. return g.IO.MouseDown[button];
  4516. }
  4517. bool ImGui::IsAnyMouseDown()
  4518. {
  4519. ImGuiContext& g = *GImGui;
  4520. for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
  4521. if (g.IO.MouseDown[n])
  4522. return true;
  4523. return false;
  4524. }
  4525. bool ImGui::IsMouseClicked(int button, bool repeat)
  4526. {
  4527. ImGuiContext& g = *GImGui;
  4528. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4529. const float t = g.IO.MouseDownDuration[button];
  4530. if (t == 0.0f)
  4531. return true;
  4532. if (repeat && t > g.IO.KeyRepeatDelay)
  4533. {
  4534. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  4535. if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  4536. return true;
  4537. }
  4538. return false;
  4539. }
  4540. bool ImGui::IsMouseReleased(int button)
  4541. {
  4542. ImGuiContext& g = *GImGui;
  4543. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4544. return g.IO.MouseReleased[button];
  4545. }
  4546. bool ImGui::IsMouseDoubleClicked(int button)
  4547. {
  4548. ImGuiContext& g = *GImGui;
  4549. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4550. return g.IO.MouseDoubleClicked[button];
  4551. }
  4552. bool ImGui::IsMouseDragging(int button, float lock_threshold)
  4553. {
  4554. ImGuiContext& g = *GImGui;
  4555. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4556. if (!g.IO.MouseDown[button])
  4557. return false;
  4558. if (lock_threshold < 0.0f)
  4559. lock_threshold = g.IO.MouseDragThreshold;
  4560. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  4561. }
  4562. ImVec2 ImGui::GetMousePos()
  4563. {
  4564. return GImGui->IO.MousePos;
  4565. }
  4566. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  4567. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  4568. {
  4569. ImGuiContext& g = *GImGui;
  4570. if (g.CurrentPopupStack.Size > 0)
  4571. return g.OpenPopupStack[g.CurrentPopupStack.Size-1].OpenMousePos;
  4572. return g.IO.MousePos;
  4573. }
  4574. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position
  4575. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  4576. {
  4577. if (mouse_pos == NULL)
  4578. mouse_pos = &GImGui->IO.MousePos;
  4579. const float MOUSE_INVALID = -256000.0f;
  4580. return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
  4581. }
  4582. // NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
  4583. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
  4584. {
  4585. ImGuiContext& g = *GImGui;
  4586. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4587. if (lock_threshold < 0.0f)
  4588. lock_threshold = g.IO.MouseDragThreshold;
  4589. if (g.IO.MouseDown[button])
  4590. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  4591. return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
  4592. return ImVec2(0.0f, 0.0f);
  4593. }
  4594. void ImGui::ResetMouseDragDelta(int button)
  4595. {
  4596. ImGuiContext& g = *GImGui;
  4597. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  4598. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  4599. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  4600. }
  4601. ImGuiMouseCursor ImGui::GetMouseCursor()
  4602. {
  4603. return GImGui->MouseCursor;
  4604. }
  4605. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  4606. {
  4607. GImGui->MouseCursor = cursor_type;
  4608. }
  4609. void ImGui::CaptureKeyboardFromApp(bool capture)
  4610. {
  4611. GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
  4612. }
  4613. void ImGui::CaptureMouseFromApp(bool capture)
  4614. {
  4615. GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
  4616. }
  4617. bool ImGui::IsItemActive()
  4618. {
  4619. ImGuiContext& g = *GImGui;
  4620. if (g.ActiveId)
  4621. {
  4622. ImGuiWindow* window = g.CurrentWindow;
  4623. return g.ActiveId == window->DC.LastItemId;
  4624. }
  4625. return false;
  4626. }
  4627. bool ImGui::IsItemFocused()
  4628. {
  4629. ImGuiContext& g = *GImGui;
  4630. return g.NavId && !g.NavDisableHighlight && g.NavId == g.CurrentWindow->DC.LastItemId;
  4631. }
  4632. bool ImGui::IsItemClicked(int mouse_button)
  4633. {
  4634. return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_Default);
  4635. }
  4636. bool ImGui::IsAnyItemHovered()
  4637. {
  4638. ImGuiContext& g = *GImGui;
  4639. return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
  4640. }
  4641. bool ImGui::IsAnyItemActive()
  4642. {
  4643. ImGuiContext& g = *GImGui;
  4644. return g.ActiveId != 0;
  4645. }
  4646. bool ImGui::IsAnyItemFocused()
  4647. {
  4648. ImGuiContext& g = *GImGui;
  4649. return g.NavId != 0 && !g.NavDisableHighlight;
  4650. }
  4651. bool ImGui::IsItemVisible()
  4652. {
  4653. ImGuiWindow* window = GetCurrentWindowRead();
  4654. return window->ClipRect.Overlaps(window->DC.LastItemRect);
  4655. }
  4656. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  4657. void ImGui::SetItemAllowOverlap()
  4658. {
  4659. ImGuiContext& g = *GImGui;
  4660. if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
  4661. g.HoveredIdAllowOverlap = true;
  4662. if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
  4663. g.ActiveIdAllowOverlap = true;
  4664. }
  4665. ImVec2 ImGui::GetItemRectMin()
  4666. {
  4667. ImGuiWindow* window = GetCurrentWindowRead();
  4668. return window->DC.LastItemRect.Min;
  4669. }
  4670. ImVec2 ImGui::GetItemRectMax()
  4671. {
  4672. ImGuiWindow* window = GetCurrentWindowRead();
  4673. return window->DC.LastItemRect.Max;
  4674. }
  4675. ImVec2 ImGui::GetItemRectSize()
  4676. {
  4677. ImGuiWindow* window = GetCurrentWindowRead();
  4678. return window->DC.LastItemRect.GetSize();
  4679. }
  4680. // Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
  4681. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
  4682. {
  4683. ImGuiContext& g = *GImGui;
  4684. char window_name[16];
  4685. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
  4686. if (override_previous_tooltip)
  4687. if (ImGuiWindow* window = FindWindowByName(window_name))
  4688. if (window->Active)
  4689. {
  4690. // Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one.
  4691. window->HiddenFrames = 1;
  4692. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
  4693. }
  4694. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoNav;
  4695. Begin(window_name, NULL, flags | extra_flags);
  4696. }
  4697. void ImGui::SetTooltipV(const char* fmt, va_list args)
  4698. {
  4699. BeginTooltipEx(0, true);
  4700. TextV(fmt, args);
  4701. EndTooltip();
  4702. }
  4703. void ImGui::SetTooltip(const char* fmt, ...)
  4704. {
  4705. va_list args;
  4706. va_start(args, fmt);
  4707. SetTooltipV(fmt, args);
  4708. va_end(args);
  4709. }
  4710. void ImGui::BeginTooltip()
  4711. {
  4712. BeginTooltipEx(0, false);
  4713. }
  4714. void ImGui::EndTooltip()
  4715. {
  4716. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  4717. End();
  4718. }
  4719. // Mark popup as open (toggle toward open state).
  4720. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  4721. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  4722. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  4723. void ImGui::OpenPopupEx(ImGuiID id)
  4724. {
  4725. ImGuiContext& g = *GImGui;
  4726. ImGuiWindow* parent_window = g.CurrentWindow;
  4727. int current_stack_size = g.CurrentPopupStack.Size;
  4728. ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
  4729. popup_ref.PopupId = id;
  4730. popup_ref.Window = NULL;
  4731. popup_ref.ParentWindow = parent_window;
  4732. popup_ref.OpenFrameCount = g.FrameCount;
  4733. popup_ref.OpenParentId = parent_window->IDStack.back();
  4734. popup_ref.OpenMousePos = g.IO.MousePos;
  4735. popup_ref.OpenPopupPos = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos;
  4736. if (g.OpenPopupStack.Size < current_stack_size + 1)
  4737. {
  4738. g.OpenPopupStack.push_back(popup_ref);
  4739. }
  4740. else
  4741. {
  4742. // Close child popups if any
  4743. g.OpenPopupStack.resize(current_stack_size + 1);
  4744. // 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
  4745. // 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
  4746. // 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.
  4747. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
  4748. g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
  4749. else
  4750. g.OpenPopupStack[current_stack_size] = popup_ref;
  4751. // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
  4752. // This is equivalent to what ClosePopupToLevel() does.
  4753. //if (g.OpenPopupStack[current_stack_size].PopupId == id)
  4754. // FocusWindow(parent_window);
  4755. }
  4756. }
  4757. void ImGui::OpenPopup(const char* str_id)
  4758. {
  4759. ImGuiContext& g = *GImGui;
  4760. OpenPopupEx(g.CurrentWindow->GetID(str_id));
  4761. }
  4762. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
  4763. {
  4764. ImGuiContext& g = *GImGui;
  4765. if (g.OpenPopupStack.empty())
  4766. return;
  4767. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  4768. // Don't close our own child popup windows.
  4769. int n = 0;
  4770. if (ref_window)
  4771. {
  4772. for (n = 0; n < g.OpenPopupStack.Size; n++)
  4773. {
  4774. ImGuiPopupRef& popup = g.OpenPopupStack[n];
  4775. if (!popup.Window)
  4776. continue;
  4777. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  4778. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  4779. continue;
  4780. // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow)
  4781. bool has_focus = false;
  4782. for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
  4783. has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow);
  4784. if (!has_focus)
  4785. break;
  4786. }
  4787. }
  4788. if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the block below
  4789. ClosePopupToLevel(n);
  4790. }
  4791. static ImGuiWindow* GetFrontMostModalRootWindow()
  4792. {
  4793. ImGuiContext& g = *GImGui;
  4794. for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
  4795. if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
  4796. if (popup->Flags & ImGuiWindowFlags_Modal)
  4797. return popup;
  4798. return NULL;
  4799. }
  4800. static void ClosePopupToLevel(int remaining)
  4801. {
  4802. IM_ASSERT(remaining >= 0);
  4803. ImGuiContext& g = *GImGui;
  4804. ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow;
  4805. if (g.NavLayer == 0)
  4806. focus_window = NavRestoreLastChildNavWindow(focus_window);
  4807. ImGui::FocusWindow(focus_window);
  4808. focus_window->DC.NavHideHighlightOneFrame = true;
  4809. g.OpenPopupStack.resize(remaining);
  4810. }
  4811. void ImGui::ClosePopup(ImGuiID id)
  4812. {
  4813. if (!IsPopupOpen(id))
  4814. return;
  4815. ImGuiContext& g = *GImGui;
  4816. ClosePopupToLevel(g.OpenPopupStack.Size - 1);
  4817. }
  4818. // Close the popup we have begin-ed into.
  4819. void ImGui::CloseCurrentPopup()
  4820. {
  4821. ImGuiContext& g = *GImGui;
  4822. int popup_idx = g.CurrentPopupStack.Size - 1;
  4823. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  4824. return;
  4825. while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
  4826. popup_idx--;
  4827. ClosePopupToLevel(popup_idx);
  4828. }
  4829. bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
  4830. {
  4831. ImGuiContext& g = *GImGui;
  4832. if (!IsPopupOpen(id))
  4833. {
  4834. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  4835. return false;
  4836. }
  4837. char name[20];
  4838. if (extra_flags & ImGuiWindowFlags_ChildMenu)
  4839. ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
  4840. else
  4841. ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
  4842. bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
  4843. if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
  4844. EndPopup();
  4845. return is_open;
  4846. }
  4847. bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
  4848. {
  4849. ImGuiContext& g = *GImGui;
  4850. if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance
  4851. {
  4852. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  4853. return false;
  4854. }
  4855. return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  4856. }
  4857. bool ImGui::IsPopupOpen(ImGuiID id)
  4858. {
  4859. ImGuiContext& g = *GImGui;
  4860. return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
  4861. }
  4862. bool ImGui::IsPopupOpen(const char* str_id)
  4863. {
  4864. ImGuiContext& g = *GImGui;
  4865. return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
  4866. }
  4867. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
  4868. {
  4869. ImGuiContext& g = *GImGui;
  4870. ImGuiWindow* window = g.CurrentWindow;
  4871. const ImGuiID id = window->GetID(name);
  4872. if (!IsPopupOpen(id))
  4873. {
  4874. g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
  4875. return false;
  4876. }
  4877. // Center modal windows by default
  4878. // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
  4879. if (g.NextWindowData.PosCond == 0)
  4880. SetNextWindowPos(GetViewportRect(window).GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
  4881. bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings);
  4882. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  4883. {
  4884. EndPopup();
  4885. if (is_open)
  4886. ClosePopup(id);
  4887. return false;
  4888. }
  4889. return is_open;
  4890. }
  4891. static void NavProcessMoveRequestWrapAround(ImGuiWindow* window)
  4892. {
  4893. ImGuiContext& g = *GImGui;
  4894. if (g.NavWindow == window && NavMoveRequestButNoResultYet())
  4895. if ((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == 0)
  4896. {
  4897. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
  4898. ImGui::NavMoveRequestCancel();
  4899. g.NavWindow->NavRectRel[0].Min.y = g.NavWindow->NavRectRel[0].Max.y = ((g.NavMoveDir == ImGuiDir_Up) ? ImMax(window->SizeFull.y, window->SizeContents.y) : 0.0f) - window->Scroll.y;
  4900. }
  4901. }
  4902. void ImGui::EndPopup()
  4903. {
  4904. ImGuiContext& g = *GImGui; (void)g;
  4905. IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  4906. IM_ASSERT(g.CurrentPopupStack.Size > 0);
  4907. // Make all menus and popups wrap around for now, may need to expose that policy.
  4908. NavProcessMoveRequestWrapAround(g.CurrentWindow);
  4909. End();
  4910. }
  4911. bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
  4912. {
  4913. ImGuiWindow* window = GImGui->CurrentWindow;
  4914. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  4915. {
  4916. 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!
  4917. IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  4918. OpenPopupEx(id);
  4919. return true;
  4920. }
  4921. return false;
  4922. }
  4923. // This is a helper to handle the simplest case of associating one named popup to one given widget.
  4924. // You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
  4925. // You can pass a NULL str_id to use the identifier of the last item.
  4926. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
  4927. {
  4928. ImGuiWindow* window = GImGui->CurrentWindow;
  4929. 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!
  4930. IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
  4931. if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  4932. OpenPopupEx(id);
  4933. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  4934. }
  4935. bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
  4936. {
  4937. if (!str_id)
  4938. str_id = "window_context";
  4939. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  4940. if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  4941. if (also_over_items || !IsAnyItemHovered())
  4942. OpenPopupEx(id);
  4943. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  4944. }
  4945. bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
  4946. {
  4947. if (!str_id)
  4948. str_id = "void_context";
  4949. ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
  4950. if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
  4951. OpenPopupEx(id);
  4952. return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
  4953. }
  4954. static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4955. {
  4956. ImGuiContext& g = *GImGui;
  4957. ImGuiWindow* parent_window = ImGui::GetCurrentWindow();
  4958. ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
  4959. flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
  4960. const ImVec2 content_avail = ImGui::GetContentRegionAvail();
  4961. ImVec2 size = ImFloor(size_arg);
  4962. const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
  4963. if (size.x <= 0.0f)
  4964. size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
  4965. if (size.y <= 0.0f)
  4966. size.y = ImMax(content_avail.y + size.y, 4.0f);
  4967. const float backup_border_size = g.Style.ChildBorderSize;
  4968. if (!border)
  4969. g.Style.ChildBorderSize = 0.0f;
  4970. flags |= extra_flags;
  4971. char title[256];
  4972. if (name)
  4973. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
  4974. else
  4975. ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
  4976. ImGui::SetNextWindowSize(size);
  4977. bool ret = ImGui::Begin(title, NULL, flags);
  4978. ImGuiWindow* child_window = ImGui::GetCurrentWindow();
  4979. child_window->ChildId = id;
  4980. child_window->AutoFitChildAxises = auto_fit_axises;
  4981. g.Style.ChildBorderSize = backup_border_size;
  4982. // Process navigation-in immediately so NavInit can run on first frame
  4983. if (!(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll) && g.NavActivateId == id)
  4984. {
  4985. ImGui::FocusWindow(child_window);
  4986. ImGui::NavInitWindow(child_window, false);
  4987. ImGui::SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
  4988. g.ActiveIdSource = ImGuiInputSource_Nav;
  4989. }
  4990. return ret;
  4991. }
  4992. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4993. {
  4994. ImGuiWindow* window = GetCurrentWindow();
  4995. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  4996. }
  4997. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  4998. {
  4999. IM_ASSERT(id != 0);
  5000. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  5001. }
  5002. void ImGui::EndChild()
  5003. {
  5004. ImGuiContext& g = *GImGui;
  5005. ImGuiWindow* window = g.CurrentWindow;
  5006. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
  5007. if (window->BeginCount > 1)
  5008. {
  5009. End();
  5010. }
  5011. else
  5012. {
  5013. // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting.
  5014. ImVec2 sz = GetWindowSize();
  5015. if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  5016. sz.x = ImMax(4.0f, sz.x);
  5017. if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
  5018. sz.y = ImMax(4.0f, sz.y);
  5019. End();
  5020. ImGuiWindow* parent_window = g.CurrentWindow;
  5021. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  5022. ItemSize(sz);
  5023. if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
  5024. {
  5025. ItemAdd(bb, window->ChildId);
  5026. RenderNavHighlight(bb, window->ChildId);
  5027. // When browsing a window that has no activable items (scroll only) we keep a highlight on the child
  5028. if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
  5029. RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
  5030. }
  5031. else
  5032. {
  5033. // Not navigable into
  5034. ItemAdd(bb, 0);
  5035. }
  5036. }
  5037. }
  5038. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  5039. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  5040. {
  5041. ImGuiContext& g = *GImGui;
  5042. const ImGuiStyle& style = g.Style;
  5043. PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
  5044. PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
  5045. PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
  5046. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  5047. return BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  5048. }
  5049. void ImGui::EndChildFrame()
  5050. {
  5051. EndChild();
  5052. PopStyleVar(3);
  5053. PopStyleColor();
  5054. }
  5055. // Save and compare stack sizes on Begin()/End() to detect usage errors
  5056. static void CheckStacksSize(ImGuiWindow* window, bool write)
  5057. {
  5058. // 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)
  5059. ImGuiContext& g = *GImGui;
  5060. int* p_backup = &window->DC.StackSizesBackup[0];
  5061. { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
  5062. { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
  5063. { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
  5064. { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
  5065. { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
  5066. { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
  5067. IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
  5068. }
  5069. enum ImGuiPopupPositionPolicy
  5070. {
  5071. ImGuiPopupPositionPolicy_Default,
  5072. ImGuiPopupPositionPolicy_ComboBox
  5073. };
  5074. static ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window, const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default)
  5075. {
  5076. const ImGuiStyle& style = GImGui->Style;
  5077. // 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.)
  5078. // 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.
  5079. ImVec2 safe_padding = style.DisplaySafeAreaPadding;
  5080. ImRect r_outer(ImGui::GetViewportRect(window));
  5081. r_outer.Expand(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? -safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? -safe_padding.y : 0.0f));
  5082. ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
  5083. //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
  5084. //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
  5085. // Combo Box policy (we want a connecting edge)
  5086. if (policy == ImGuiPopupPositionPolicy_ComboBox)
  5087. {
  5088. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
  5089. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  5090. {
  5091. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  5092. if (n != -1 && dir == *last_dir) // Already tried this direction?
  5093. continue;
  5094. ImVec2 pos;
  5095. if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
  5096. if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
  5097. if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
  5098. if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
  5099. if (!r_outer.Contains(ImRect(pos, pos + size)))
  5100. continue;
  5101. *last_dir = dir;
  5102. return pos;
  5103. }
  5104. }
  5105. // Default popup policy
  5106. const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
  5107. for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
  5108. {
  5109. const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
  5110. if (n != -1 && dir == *last_dir) // Already tried this direction?
  5111. continue;
  5112. 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);
  5113. 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);
  5114. if (avail_w < size.x || avail_h < size.y)
  5115. continue;
  5116. ImVec2 pos;
  5117. pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
  5118. pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
  5119. *last_dir = dir;
  5120. return pos;
  5121. }
  5122. // Fallback, try to keep within display
  5123. *last_dir = ImGuiDir_None;
  5124. ImVec2 pos = ref_pos;
  5125. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  5126. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  5127. return pos;
  5128. }
  5129. static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
  5130. {
  5131. window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
  5132. window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
  5133. window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
  5134. }
  5135. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  5136. {
  5137. ImGuiContext& g = *GImGui;
  5138. ImGuiID id = ImHash(name, 0);
  5139. return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
  5140. }
  5141. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
  5142. {
  5143. ImGuiContext& g = *GImGui;
  5144. // Create window the first time
  5145. ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
  5146. window->Flags = flags;
  5147. g.WindowsById.SetVoidPtr(window->ID, window);
  5148. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  5149. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  5150. {
  5151. // Retrieve settings from .ini file
  5152. // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  5153. window->Pos = window->PosFloat = ImVec2(60, 60);
  5154. if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
  5155. {
  5156. SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
  5157. window->PosFloat = settings->Pos;
  5158. window->Pos = ImFloor(window->PosFloat);
  5159. window->Collapsed = settings->Collapsed;
  5160. if (settings->ViewportId)
  5161. window->ViewportId = settings->ViewportId;
  5162. if (settings->ViewportPlatformPos.x != FLT_MAX && settings->ViewportPlatformPos.y != FLT_MAX)
  5163. window->ViewportPlatformPos = settings->ViewportPlatformPos;
  5164. if (ImLengthSqr(settings->Size) > 0.00001f)
  5165. size = settings->Size;
  5166. }
  5167. }
  5168. window->Size = window->SizeFull = window->SizeFullAtLastBegin = size;
  5169. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  5170. {
  5171. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  5172. window->AutoFitOnlyGrows = false;
  5173. }
  5174. else
  5175. {
  5176. if (window->Size.x <= 0.0f)
  5177. window->AutoFitFramesX = 2;
  5178. if (window->Size.y <= 0.0f)
  5179. window->AutoFitFramesY = 2;
  5180. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  5181. }
  5182. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  5183. g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
  5184. else
  5185. g.Windows.push_back(window);
  5186. return window;
  5187. }
  5188. static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
  5189. {
  5190. ImGuiContext& g = *GImGui;
  5191. if (g.NextWindowData.SizeConstraintCond != 0)
  5192. {
  5193. // Using -1,-1 on either X/Y axis to preserve the current size.
  5194. ImRect cr = g.NextWindowData.SizeConstraintRect;
  5195. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  5196. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  5197. if (g.NextWindowData.SizeCallback)
  5198. {
  5199. ImGuiSizeCallbackData data;
  5200. data.UserData = g.NextWindowData.SizeCallbackUserData;
  5201. data.Pos = window->Pos;
  5202. data.CurrentSize = window->SizeFull;
  5203. data.DesiredSize = new_size;
  5204. g.NextWindowData.SizeCallback(&data);
  5205. new_size = data.DesiredSize;
  5206. }
  5207. }
  5208. // Minimum size
  5209. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  5210. {
  5211. new_size = ImMax(new_size, g.Style.WindowMinSize);
  5212. new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
  5213. }
  5214. return new_size;
  5215. }
  5216. static ImVec2 CalcSizeContents(ImGuiWindow* window)
  5217. {
  5218. ImVec2 sz;
  5219. sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
  5220. sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
  5221. return sz + window->WindowPadding;
  5222. }
  5223. static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
  5224. {
  5225. ImGuiContext& g = *GImGui;
  5226. ImGuiStyle& style = g.Style;
  5227. ImGuiWindowFlags flags = window->Flags;
  5228. ImVec2 size_auto_fit;
  5229. if ((flags & ImGuiWindowFlags_Tooltip) != 0)
  5230. {
  5231. // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
  5232. size_auto_fit = size_contents;
  5233. }
  5234. else
  5235. {
  5236. // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
  5237. ImVec2 viewport_size = (window->Flags & ImGuiWindowFlags_FullViewport) ? ImVec2(FLT_MAX, FLT_MAX) : window->Viewport->Size;
  5238. size_auto_fit = ImClamp(size_contents, style.WindowMinSize, ImMax(style.WindowMinSize, viewport_size - g.Style.DisplaySafeAreaPadding));
  5239. ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
  5240. if (size_auto_fit_after_constraint.x < size_contents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
  5241. size_auto_fit.y += style.ScrollbarSize;
  5242. if (size_auto_fit_after_constraint.y < size_contents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
  5243. size_auto_fit.x += style.ScrollbarSize;
  5244. }
  5245. return size_auto_fit;
  5246. }
  5247. static float GetScrollMaxX(ImGuiWindow* window)
  5248. {
  5249. return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
  5250. }
  5251. static float GetScrollMaxY(ImGuiWindow* window)
  5252. {
  5253. return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
  5254. }
  5255. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
  5256. {
  5257. ImVec2 scroll = window->Scroll;
  5258. float cr_x = window->ScrollTargetCenterRatio.x;
  5259. float cr_y = window->ScrollTargetCenterRatio.y;
  5260. if (window->ScrollTarget.x < FLT_MAX)
  5261. scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
  5262. if (window->ScrollTarget.y < FLT_MAX)
  5263. scroll.y = window->ScrollTarget.y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
  5264. scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
  5265. if (!window->Collapsed && !window->SkipItems)
  5266. {
  5267. scroll.x = ImMin(scroll.x, GetScrollMaxX(window));
  5268. scroll.y = ImMin(scroll.y, GetScrollMaxY(window));
  5269. }
  5270. return scroll;
  5271. }
  5272. static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
  5273. {
  5274. if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
  5275. return ImGuiCol_PopupBg;
  5276. if (flags & ImGuiWindowFlags_ChildWindow)
  5277. return ImGuiCol_ChildBg;
  5278. return ImGuiCol_WindowBg;
  5279. }
  5280. static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
  5281. {
  5282. ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
  5283. ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
  5284. ImVec2 size_expected = pos_max - pos_min;
  5285. ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
  5286. *out_pos = pos_min;
  5287. if (corner_norm.x == 0.0f)
  5288. out_pos->x -= (size_constrained.x - size_expected.x);
  5289. if (corner_norm.y == 0.0f)
  5290. out_pos->y -= (size_constrained.y - size_expected.y);
  5291. *out_size = size_constrained;
  5292. }
  5293. static void ImGui::SetWindowViewportTranslateToPreservePlatformPos(ImGuiWindow* window, ImGuiViewportP* prev_viewport, ImGuiViewportP* curr_viewport)
  5294. {
  5295. if (prev_viewport == curr_viewport)
  5296. return;
  5297. ImVec2 new_pos = ConvertPlatformPosToViewportPos(ConvertViewportPosToPlatformPos(window->PosFloat, prev_viewport), curr_viewport);
  5298. if ((window->FlagsPreviousFrame ^ window->Flags) & ImGuiWindowFlags_NoTitleBar)
  5299. {
  5300. // As a convenience, automatically adjust for client rect difference for the common use case of toggling the imgui title-bar when we move our tools to a separate OS window
  5301. float title_bar_height = GetFrameHeight();
  5302. if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
  5303. title_bar_height = -title_bar_height;
  5304. new_pos.y += title_bar_height;
  5305. window->SizeFull.y -= title_bar_height;
  5306. }
  5307. SetWindowPos(window, new_pos, ImGuiCond_Always);
  5308. window->Viewport = curr_viewport;
  5309. window->ViewportId = curr_viewport->ID;
  5310. }
  5311. // FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
  5312. static void ImGui::UpdateWindowViewport(ImGuiWindow* window, bool window_pos_set_by_api)
  5313. {
  5314. ImGuiContext& g = *GImGui;
  5315. ImGuiWindowFlags flags = window->Flags;
  5316. (void)window_pos_set_by_api;
  5317. // Restore main viewport if multi-viewport is not supported by the back-end
  5318. ImGuiViewportP* main_viewport = g.Viewports[0];
  5319. if (!(g.IO.ConfigFlags & ImGuiConfigFlags_EnableViewports))
  5320. {
  5321. window->Viewport = main_viewport;
  5322. window->ViewportId = main_viewport->ID;
  5323. return;
  5324. }
  5325. const bool window_is_mouse_tooltip = (flags & ImGuiWindowFlags_Tooltip) && g.NavDisableHighlight && !g.NavDisableMouseHover;
  5326. const bool window_follow_mouse_viewport = (window_is_mouse_tooltip || (g.MovingWindow && g.MovingWindow->RootWindow == window));
  5327. bool created_viewport = false;
  5328. if (g.NextWindowData.ViewportCond)
  5329. {
  5330. // Code explicitly request a viewport
  5331. window->Viewport = FindViewportByID(g.NextWindowData.ViewportId);
  5332. window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved.
  5333. }
  5334. else if (flags & ImGuiWindowFlags_ChildWindow)
  5335. {
  5336. IM_ASSERT(window->ParentWindow);
  5337. window->Viewport = window->ParentWindow->Viewport;
  5338. }
  5339. else if (window_follow_mouse_viewport && IsMousePosValid())
  5340. {
  5341. // Calculate mouse position in OS/platform coordinates
  5342. ImGuiViewportP* current_viewport = window->Viewport;
  5343. if (!window_is_mouse_tooltip && !current_viewport->GetRect().Contains(window->Rect()))
  5344. {
  5345. // Create an undecorated, temporary OS/platform window
  5346. ImVec2 platform_pos = ConvertViewportPosToPlatformPos(g.IO.MousePos - g.ActiveIdClickOffset, g.MouseViewport);
  5347. ImGuiViewportFlags viewport_flags = ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoInputs;
  5348. ImGuiViewportP* viewport = Viewport(window, window->ID, viewport_flags, platform_pos, window->Size);
  5349. window->Flags |= ImGuiWindowFlags_FullViewport;
  5350. window->Viewport = viewport;
  5351. created_viewport = true;
  5352. // Preserve relative mouse position so docking title bar test stays valid mid-frame (since it isn't latched)
  5353. g.IO.MousePos = g.IO.MousePosPrev = window->Viewport->Pos + g.ActiveIdClickOffset;
  5354. }
  5355. else
  5356. {
  5357. // When dragging a window back into another, only change viewport on mouse release (in UpdateMovingWindow()).
  5358. // This is so we don't require of the multi-viewport windowing back-end to preserve mouse buttons after a window closure, making it easier to implement them.
  5359. bool preserve_temporary_viewport = g.MovingWindow && g.MovingWindow->RootWindow == window && (window->Viewport->Flags & ImGuiWindowFlags_FullViewport);
  5360. if (!preserve_temporary_viewport)
  5361. window->Viewport = g.MouseViewport;
  5362. }
  5363. }
  5364. else if (g.NavWindow != NULL && g.NavWindow != window && (flags & ImGuiWindowFlags_Tooltip))
  5365. {
  5366. window->Viewport = g.NavWindow->Viewport;
  5367. }
  5368. // Appearing popups reset their viewport so they can inherit again
  5369. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames == 1);
  5370. if ((flags & ImGuiWindowFlags_Popup) && window_just_appearing_after_hidden_for_resize)
  5371. window->Viewport = NULL;
  5372. // By default inherit from parent window
  5373. if (window->Viewport == NULL && window->ParentWindow)
  5374. window->Viewport = window->ParentWindow->Viewport;
  5375. // Restore a viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPlatformPos'
  5376. if (window->Viewport == NULL && window->ViewportId != 0)
  5377. {
  5378. window->Viewport = FindViewportByID(window->ViewportId);
  5379. if (window->Viewport == NULL)
  5380. {
  5381. if (window->ViewportPlatformPos.x != FLT_MAX && window->ViewportPlatformPos.y != FLT_MAX)
  5382. {
  5383. ImGuiViewportP* viewport = Viewport(window, window->ID, ImGuiViewportFlags_NoDecoration, window->ViewportPlatformPos, window->Size);
  5384. window->Flags |= ImGuiWindowFlags_FullViewport;
  5385. window->Viewport = viewport;
  5386. created_viewport = true;
  5387. }
  5388. else
  5389. {
  5390. window->ViewportId = 0;
  5391. }
  5392. }
  5393. }
  5394. // Fallback to default viewport
  5395. if (window->Viewport == NULL)
  5396. window->Viewport = main_viewport;
  5397. // When we own the viewport update its size
  5398. if (window == window->Viewport->Window && !created_viewport)
  5399. {
  5400. window->Viewport->Flags |= ImGuiViewportFlags_NoDecoration;
  5401. if (!window->Viewport->PlatformRequestResize)
  5402. window->Viewport->Size = window->Size;
  5403. window->Viewport->PlatformPos = ConvertViewportPosToPlatformPos(window->Pos, window->Viewport);
  5404. window->Flags |= ImGuiWindowFlags_FullViewport;
  5405. }
  5406. // If the OS window has a title bar, hide our imgui title bar
  5407. if ((window->Flags & ImGuiWindowFlags_FullViewport) && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
  5408. window->Flags |= ImGuiWindowFlags_NoTitleBar;
  5409. if (window->Flags & ImGuiWindowFlags_FullViewport)
  5410. {
  5411. // We currently have window fully covering a viewport and we disable WindowBg alpha, so clearing is not necessary
  5412. window->Viewport->Flags |= ImGuiViewportFlags_NoRendererClear;
  5413. // Position
  5414. SetWindowPos(window, window->Viewport->Pos, ImGuiCond_Always);
  5415. if (window->Viewport->PlatformRequestResize)
  5416. SetWindowSize(window, window->Viewport->Size, ImGuiCond_Always);
  5417. }
  5418. window->ViewportId = window->Viewport->ID;
  5419. }
  5420. struct ImGuiResizeGripDef
  5421. {
  5422. ImVec2 CornerPos;
  5423. ImVec2 InnerDir;
  5424. int AngleMin12, AngleMax12;
  5425. };
  5426. const ImGuiResizeGripDef resize_grip_def[4] =
  5427. {
  5428. { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
  5429. { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
  5430. { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
  5431. { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
  5432. };
  5433. static ImRect GetBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
  5434. {
  5435. ImRect rect = window->Rect();
  5436. if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
  5437. if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y, rect.Max.x - perp_padding, rect.Min.y + thickness);
  5438. if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x, rect.Max.y - perp_padding);
  5439. if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y);
  5440. if (border_n == 3) return ImRect(rect.Min.x, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding);
  5441. IM_ASSERT(0);
  5442. return ImRect();
  5443. }
  5444. // Handle resize for: Resize Grips, Borders, Gamepad
  5445. static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
  5446. {
  5447. ImGuiContext& g = *GImGui;
  5448. ImGuiWindowFlags flags = window->Flags;
  5449. if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5450. return;
  5451. const int resize_border_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 4 : 0;
  5452. const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
  5453. const float grip_hover_size = (float)(int)(grip_draw_size * 0.75f);
  5454. ImVec2 pos_target(FLT_MAX, FLT_MAX);
  5455. ImVec2 size_target(FLT_MAX, FLT_MAX);
  5456. // Manual resize grips
  5457. PushID("#RESIZE");
  5458. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5459. {
  5460. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  5461. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
  5462. // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
  5463. ImRect resize_rect(corner, corner + grip.InnerDir * grip_hover_size);
  5464. resize_rect.FixInverted();
  5465. bool hovered, held;
  5466. ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
  5467. if (hovered || held)
  5468. g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  5469. if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
  5470. {
  5471. // Manual auto-fit when double-clicking
  5472. size_target = CalcSizeAfterConstraint(window, size_auto_fit);
  5473. ClearActiveID();
  5474. }
  5475. else if (held)
  5476. {
  5477. // Resize from any of the four corners
  5478. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  5479. ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize() * grip.CornerPos; // Corner of the window corresponding to our corner grip
  5480. CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target);
  5481. }
  5482. if (resize_grip_n == 0 || held || hovered)
  5483. resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  5484. }
  5485. for (int border_n = 0; border_n < resize_border_count; border_n++)
  5486. {
  5487. const float BORDER_SIZE = 5.0f; // FIXME: Only works _inside_ window because of HoveredWindow check.
  5488. const float BORDER_APPEAR_TIMER = 0.05f; // Reduce visual noise
  5489. bool hovered, held;
  5490. ImRect border_rect = GetBorderRect(window, border_n, grip_hover_size, BORDER_SIZE);
  5491. ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
  5492. if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held)
  5493. {
  5494. g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
  5495. if (held) *border_held = border_n;
  5496. }
  5497. if (held)
  5498. {
  5499. ImVec2 border_target = window->Pos;
  5500. ImVec2 border_posn;
  5501. if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y); }
  5502. if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + BORDER_SIZE); }
  5503. if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + BORDER_SIZE); }
  5504. if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x); }
  5505. CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
  5506. }
  5507. }
  5508. PopID();
  5509. // Navigation/gamepad resize
  5510. if (g.NavWindowingTarget == window)
  5511. {
  5512. ImVec2 nav_resize_delta;
  5513. if (g.NavWindowingInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
  5514. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
  5515. if (g.NavWindowingInputSource == ImGuiInputSource_NavGamepad)
  5516. nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
  5517. if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
  5518. {
  5519. const float NAV_RESIZE_SPEED = 600.0f;
  5520. nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
  5521. g.NavWindowingToggleLayer = false;
  5522. g.NavDisableMouseHover = true;
  5523. resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
  5524. // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
  5525. size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
  5526. }
  5527. }
  5528. // Apply back modified position/size to window
  5529. if (size_target.x != FLT_MAX)
  5530. {
  5531. window->SizeFull = size_target;
  5532. MarkIniSettingsDirty(window);
  5533. }
  5534. if (pos_target.x != FLT_MAX)
  5535. {
  5536. if (window->Flags & ImGuiWindowFlags_FullViewport)
  5537. window->Viewport->PlatformPos = ConvertViewportPosToPlatformPos(ImFloor(pos_target), window->Viewport);
  5538. else
  5539. window->Pos = window->PosFloat = ImFloor(pos_target);
  5540. MarkIniSettingsDirty(window);
  5541. }
  5542. window->Size = window->SizeFull;
  5543. }
  5544. // Push a new ImGui window to add widgets to.
  5545. // - 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.
  5546. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  5547. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  5548. // 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.
  5549. // - 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.
  5550. // - 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.
  5551. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  5552. {
  5553. ImGuiContext& g = *GImGui;
  5554. const ImGuiStyle& style = g.Style;
  5555. IM_ASSERT(name != NULL); // Window name required
  5556. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  5557. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  5558. // Find or create
  5559. ImGuiWindow* window = FindWindowByName(name);
  5560. if (!window)
  5561. {
  5562. ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
  5563. window = CreateNewWindow(name, size_on_first_use, flags);
  5564. }
  5565. // Automatically disable manual moving/resizing when NoInputs is set
  5566. if (flags & ImGuiWindowFlags_NoInputs)
  5567. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  5568. if (flags & ImGuiWindowFlags_NavFlattened)
  5569. IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
  5570. const int current_frame = g.FrameCount;
  5571. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  5572. if (first_begin_of_the_frame)
  5573. {
  5574. window->FlagsPreviousFrame = window->Flags;
  5575. window->Flags = (ImGuiWindowFlags)flags;
  5576. }
  5577. else
  5578. {
  5579. flags = window->Flags;
  5580. }
  5581. // Update the Appearing flag
  5582. bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  5583. const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames == 1);
  5584. if (flags & ImGuiWindowFlags_Popup)
  5585. {
  5586. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
  5587. window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
  5588. window_just_activated_by_user |= (window != popup_ref.Window);
  5589. }
  5590. window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
  5591. window->CloseButton = (p_open != NULL);
  5592. if (window->Appearing)
  5593. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
  5594. // 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
  5595. ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
  5596. ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
  5597. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  5598. // Add to stack
  5599. // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
  5600. g.CurrentWindowStack.push_back(window);
  5601. g.CurrentWindow = NULL;
  5602. CheckStacksSize(window, true);
  5603. if (flags & ImGuiWindowFlags_Popup)
  5604. {
  5605. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
  5606. popup_ref.Window = window;
  5607. g.CurrentPopupStack.push_back(popup_ref);
  5608. window->PopupId = popup_ref.PopupId;
  5609. }
  5610. if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
  5611. window->NavLastIds[0] = 0;
  5612. // Process SetNextWindow***() calls
  5613. bool window_pos_set_by_api = false;
  5614. bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
  5615. if (g.NextWindowData.PosCond)
  5616. {
  5617. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
  5618. if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
  5619. {
  5620. // May be processed on the next frame if this is our first frame and we are measuring size
  5621. // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
  5622. window->SetWindowPosVal = g.NextWindowData.PosVal;
  5623. window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
  5624. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5625. }
  5626. else
  5627. {
  5628. SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
  5629. }
  5630. }
  5631. if (g.NextWindowData.SizeCond)
  5632. {
  5633. window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
  5634. window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
  5635. SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
  5636. }
  5637. if (g.NextWindowData.ContentSizeCond)
  5638. {
  5639. // Adjust passed "client size" to become a "window size"
  5640. window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
  5641. if (window->SizeContentsExplicit.y != 0.0f)
  5642. window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
  5643. }
  5644. else if (first_begin_of_the_frame)
  5645. {
  5646. window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  5647. }
  5648. if (g.NextWindowData.CollapsedCond)
  5649. SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
  5650. if (g.NextWindowData.FocusCond)
  5651. FocusWindow(window);
  5652. if (window->Appearing)
  5653. SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
  5654. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  5655. if (first_begin_of_the_frame)
  5656. {
  5657. const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
  5658. // Initialize
  5659. window->ParentWindow = parent_window;
  5660. window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = window->RootWindowForNav = window;
  5661. if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !window_is_child_tooltip)
  5662. window->RootWindow = parent_window->RootWindow;
  5663. if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  5664. window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = parent_window->RootWindowForTitleBarHighlight; // Same value in master branch, will differ for docking
  5665. while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
  5666. window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
  5667. window->Active = true;
  5668. window->BeginOrderWithinParent = 0;
  5669. window->BeginOrderWithinContext = g.WindowsActiveCount++;
  5670. window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
  5671. window->LastFrameActive = current_frame;
  5672. window->IDStack.resize(1);
  5673. // VIEWPORT
  5674. // We need to do this before using any style/font sizes, as viewport with a different DPI will affect those sizes.
  5675. UpdateWindowViewport(window, window_pos_set_by_api);
  5676. SetCurrentViewport(window->Viewport);
  5677. window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_EnableDpiScaleFonts) ? window->Viewport->DpiScale : 1.0f;
  5678. SetCurrentWindow(window);
  5679. flags = window->Flags;
  5680. if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
  5681. {
  5682. window->Viewport->PlatformRequestClose = false;
  5683. *p_open = false;
  5684. }
  5685. // Lock window rounding, border size and padding for the frame (so that altering them doesn't cause inconsistencies)
  5686. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
  5687. if (window->Flags & ImGuiWindowFlags_FullViewport)
  5688. window->WindowRounding = 0.0f;
  5689. window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
  5690. window->WindowPadding = style.WindowPadding;
  5691. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
  5692. window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
  5693. // Collapse window by double-clicking on title bar
  5694. // 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
  5695. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  5696. {
  5697. ImRect title_bar_rect = window->TitleBarRect();
  5698. if (window->CollapseToggleWanted || (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]))
  5699. {
  5700. window->Collapsed = !window->Collapsed;
  5701. MarkIniSettingsDirty(window);
  5702. FocusWindow(window);
  5703. }
  5704. }
  5705. else
  5706. {
  5707. window->Collapsed = false;
  5708. }
  5709. window->CollapseToggleWanted = false;
  5710. // SIZE
  5711. // Update contents size from last frame for auto-fitting (unless explicitly specified)
  5712. window->SizeContents = CalcSizeContents(window);
  5713. // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
  5714. if (window->HiddenFrames > 0)
  5715. window->HiddenFrames--;
  5716. if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && window_just_activated_by_user)
  5717. {
  5718. window->HiddenFrames = 1;
  5719. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  5720. {
  5721. if (!window_size_x_set_by_api)
  5722. window->Size.x = window->SizeFull.x = 0.f;
  5723. if (!window_size_y_set_by_api)
  5724. window->Size.y = window->SizeFull.y = 0.f;
  5725. window->SizeContents = ImVec2(0.f, 0.f);
  5726. }
  5727. }
  5728. // Calculate auto-fit size, handle automatic resize
  5729. const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
  5730. ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
  5731. if (flags & ImGuiWindowFlags_AlwaysAutoResize && !window->Collapsed)
  5732. {
  5733. // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
  5734. if (!window_size_x_set_by_api)
  5735. window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
  5736. if (!window_size_y_set_by_api)
  5737. window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
  5738. }
  5739. else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
  5740. {
  5741. // Auto-fit only grows during the first few frames
  5742. // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  5743. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
  5744. window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  5745. if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
  5746. window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  5747. if (!window->Collapsed)
  5748. MarkIniSettingsDirty(window);
  5749. }
  5750. // Apply minimum/maximum window size constraints and final size
  5751. window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
  5752. window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
  5753. // SCROLLBAR STATUS
  5754. // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
  5755. if (!window->Collapsed)
  5756. {
  5757. // When reading the current size we need to read it after size constraints have been applied
  5758. float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
  5759. float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
  5760. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
  5761. window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
  5762. if (window->ScrollbarX && !window->ScrollbarY)
  5763. window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
  5764. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  5765. }
  5766. // POSITION
  5767. // Popup latch its initial position, will position itself when it appears next frame
  5768. if (window_just_activated_by_user)
  5769. {
  5770. window->AutoPosLastDirection = ImGuiDir_None;
  5771. if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
  5772. window->Pos = window->PosFloat = g.CurrentPopupStack.back().OpenPopupPos;
  5773. }
  5774. // Position child window
  5775. if (flags & ImGuiWindowFlags_ChildWindow)
  5776. {
  5777. window->BeginOrderWithinParent = parent_window->DC.ChildWindows.Size;
  5778. parent_window->DC.ChildWindows.push_back(window);
  5779. if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
  5780. window->Pos = window->PosFloat = parent_window->DC.CursorPos;
  5781. }
  5782. const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFrames == 0);
  5783. if (window_pos_with_pivot)
  5784. {
  5785. // Position given a pivot (e.g. for centering)
  5786. SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0);
  5787. }
  5788. else if (flags & ImGuiWindowFlags_ChildMenu)
  5789. {
  5790. // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds.
  5791. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  5792. IM_ASSERT(window_pos_set_by_api);
  5793. float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value).
  5794. ImGuiWindow* parent_menu = parent_window_in_stack;
  5795. ImRect rect_to_avoid;
  5796. if (parent_menu->DC.MenuBarAppending)
  5797. rect_to_avoid = ImRect(-FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight(), FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight() + parent_menu->MenuBarHeight());
  5798. else
  5799. rect_to_avoid = ImRect(parent_menu->Pos.x + horizontal_overlap, -FLT_MAX, parent_menu->Pos.x + parent_menu->Size.x - horizontal_overlap - parent_menu->ScrollbarSizes.x, FLT_MAX);
  5800. window->PosFloat = FindBestWindowPosForPopup(window, window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  5801. }
  5802. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
  5803. {
  5804. ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
  5805. window->PosFloat = FindBestWindowPosForPopup(window, window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  5806. }
  5807. // Position tooltip (always follows mouse)
  5808. if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
  5809. {
  5810. float sc = g.Style.MouseCursorScale;
  5811. ImVec2 ref_pos = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos;
  5812. ImRect rect_to_avoid;
  5813. if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavMoveMouse))
  5814. rect_to_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
  5815. else
  5816. rect_to_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.
  5817. window->PosFloat = FindBestWindowPosForPopup(window, ref_pos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  5818. if (window->AutoPosLastDirection == ImGuiDir_None)
  5819. window->PosFloat = ref_pos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  5820. }
  5821. // Clamp position so window stays visible within its viewport
  5822. ImRect viewport_rect(GetViewportRect(window));
  5823. if (!window_pos_set_by_api && !(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_FullViewport)) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  5824. {
  5825. // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
  5826. if (viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
  5827. {
  5828. ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  5829. window->PosFloat = ImMax(window->PosFloat + window->Size, viewport_rect.Min + padding) - window->Size;
  5830. window->PosFloat = ImMin(window->PosFloat, viewport_rect.Max - padding);
  5831. }
  5832. }
  5833. window->Pos = ImFloor(window->PosFloat);
  5834. // Default item width. Make it proportional to window size if window manually resizes
  5835. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  5836. window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
  5837. else
  5838. window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
  5839. // Prepare for focus requests
  5840. window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
  5841. window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
  5842. window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
  5843. window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
  5844. // Apply scrolling
  5845. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  5846. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  5847. // Apply focus, new windows appears in front
  5848. bool want_focus = false;
  5849. if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  5850. if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
  5851. want_focus = true;
  5852. // Handle manual resize: Resize Grips, Borders, Gamepad
  5853. int border_held = -1;
  5854. ImU32 resize_grip_col[4] = { 0 };
  5855. const int resize_grip_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 2 : 1; // 4
  5856. const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
  5857. if (!window->Collapsed)
  5858. UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
  5859. // When a window is marked as owning its viewport, we immediately update the viewport after a resize
  5860. window->ViewportPlatformPos = window->Viewport->PlatformPos;
  5861. if (flags & ImGuiWindowFlags_FullViewport)
  5862. if (window->Size.x != window->Viewport->Size.x || window->Size.y != window->Viewport->Size.y)
  5863. {
  5864. window->Viewport->Size = window->SizeFull;
  5865. viewport_rect = GetViewportRect(window);
  5866. }
  5867. // DRAWING
  5868. // Setup draw list and outer clipping rectangle
  5869. window->DrawList->Clear();
  5870. window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
  5871. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  5872. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
  5873. PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
  5874. else
  5875. PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
  5876. // Draw modal window background (darkens what is behind them, all viewports)
  5877. if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow() && window->HiddenFrames <= 0)
  5878. {
  5879. window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
  5880. for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
  5881. if (g.Viewports[viewport_n] != window->Viewport)
  5882. g.OverlayDrawList.AddRectFilled(g.Viewports[viewport_n]->Pos, g.Viewports[viewport_n]->Pos + g.Viewports[viewport_n]->Size, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
  5883. }
  5884. // Draw navigation selection/windowing rectangle background
  5885. if (g.NavWindowingTarget == window)
  5886. {
  5887. ImRect bb = window->Rect();
  5888. bb.Expand(g.FontSize);
  5889. if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
  5890. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
  5891. }
  5892. // Draw window + handle manual resize
  5893. const float window_rounding = window->WindowRounding;
  5894. const float window_border_size = window->WindowBorderSize;
  5895. const bool title_bar_is_highlight = want_focus || (g.NavWindow && window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
  5896. const ImRect title_bar_rect = window->TitleBarRect();
  5897. if (window->Collapsed)
  5898. {
  5899. // Title bar only
  5900. float backup_border_size = style.FrameBorderSize;
  5901. g.Style.FrameBorderSize = window->WindowBorderSize;
  5902. ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
  5903. RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
  5904. g.Style.FrameBorderSize = backup_border_size;
  5905. }
  5906. else
  5907. {
  5908. // Window background
  5909. ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
  5910. if (g.NextWindowData.BgAlphaCond != 0)
  5911. bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
  5912. if (window->Flags & ImGuiWindowFlags_FullViewport)
  5913. bg_col = (bg_col | IM_COL32_A_MASK);
  5914. window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
  5915. // Title bar
  5916. ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
  5917. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  5918. window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
  5919. // Menu bar
  5920. if (flags & ImGuiWindowFlags_MenuBar)
  5921. {
  5922. ImRect menu_bar_rect = window->MenuBarRect();
  5923. 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.
  5924. window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
  5925. if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
  5926. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  5927. }
  5928. // Scrollbars
  5929. if (window->ScrollbarX)
  5930. Scrollbar(ImGuiLayoutType_Horizontal);
  5931. if (window->ScrollbarY)
  5932. Scrollbar(ImGuiLayoutType_Vertical);
  5933. // Render resize grips (after their input handling so we don't have a frame of latency)
  5934. if (!(flags & ImGuiWindowFlags_NoResize))
  5935. {
  5936. for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
  5937. {
  5938. const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
  5939. const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
  5940. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size)));
  5941. window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size)));
  5942. 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);
  5943. window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
  5944. }
  5945. }
  5946. // Borders
  5947. if (window_border_size > 0.0f)
  5948. window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size);
  5949. if (border_held != -1)
  5950. {
  5951. ImRect border = GetBorderRect(window, border_held, grip_draw_size, 0.0f);
  5952. window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size));
  5953. }
  5954. if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar))
  5955. window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize,-1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
  5956. }
  5957. // Draw navigation selection/windowing rectangle border
  5958. if (g.NavWindowingTarget == window)
  5959. {
  5960. float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
  5961. ImRect bb = window->Rect();
  5962. bb.Expand(g.FontSize);
  5963. if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
  5964. {
  5965. bb.Expand(-g.FontSize - 1.0f);
  5966. rounding = window->WindowRounding;
  5967. }
  5968. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
  5969. }
  5970. // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
  5971. window->SizeFullAtLastBegin = window->SizeFull;
  5972. // Update ContentsRegionMax. All the variable it depends on are set above in this function.
  5973. window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
  5974. window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
  5975. window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
  5976. window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
  5977. // Setup drawing context
  5978. // (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.)
  5979. window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
  5980. window->DC.GroupOffsetX = 0.0f;
  5981. window->DC.ColumnsOffsetX = 0.0f;
  5982. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
  5983. window->DC.CursorPos = window->DC.CursorStartPos;
  5984. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  5985. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  5986. window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
  5987. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  5988. window->DC.NavHideHighlightOneFrame = false;
  5989. window->DC.NavHasScroll = (GetScrollMaxY() > 0.0f);
  5990. window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
  5991. window->DC.NavLayerActiveMaskNext = 0x00;
  5992. window->DC.MenuBarAppending = false;
  5993. window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
  5994. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  5995. window->DC.ChildWindows.resize(0);
  5996. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  5997. window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
  5998. window->DC.ItemFlags = ImGuiItemFlags_Default_;
  5999. window->DC.ItemWidth = window->ItemWidthDefault;
  6000. window->DC.TextWrapPos = -1.0f; // disabled
  6001. window->DC.ItemFlagsStack.resize(0);
  6002. window->DC.ItemWidthStack.resize(0);
  6003. window->DC.TextWrapPosStack.resize(0);
  6004. window->DC.ColumnsSet = NULL;
  6005. window->DC.TreeDepth = 0;
  6006. window->DC.TreeDepthMayJumpToParentOnPop = 0x00;
  6007. window->DC.StateStorage = &window->StateStorage;
  6008. window->DC.GroupStack.resize(0);
  6009. window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
  6010. if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
  6011. {
  6012. window->DC.ItemFlags = parent_window->DC.ItemFlags;
  6013. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  6014. }
  6015. if (window->AutoFitFramesX > 0)
  6016. window->AutoFitFramesX--;
  6017. if (window->AutoFitFramesY > 0)
  6018. window->AutoFitFramesY--;
  6019. // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  6020. if (want_focus)
  6021. {
  6022. FocusWindow(window);
  6023. NavInitWindow(window, false);
  6024. }
  6025. // Title bar
  6026. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  6027. {
  6028. // Close & collapse button are on layer 1 (same as menus) and don't default focus
  6029. const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
  6030. window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
  6031. window->DC.NavLayerCurrent++;
  6032. window->DC.NavLayerCurrentMask <<= 1;
  6033. // Collapse button
  6034. if (!(flags & ImGuiWindowFlags_NoCollapse))
  6035. {
  6036. ImGuiID id = window->GetID("#COLLAPSE");
  6037. ImRect bb(window->Pos + style.FramePadding + ImVec2(1,1), window->Pos + style.FramePadding + ImVec2(g.FontSize,g.FontSize) - ImVec2(1,1));
  6038. ItemAdd(bb, id);
  6039. if (ButtonBehavior(bb, id, NULL, NULL))
  6040. window->CollapseToggleWanted = true; // Defer collapsing to next frame as we are too far in the Begin() function
  6041. RenderNavHighlight(bb, id);
  6042. RenderArrow(window->Pos + style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
  6043. }
  6044. // Close button
  6045. if (p_open != NULL)
  6046. {
  6047. const float pad = style.FramePadding.y;
  6048. const float rad = g.FontSize * 0.5f;
  6049. if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad + 1))
  6050. *p_open = false;
  6051. }
  6052. window->DC.NavLayerCurrent--;
  6053. window->DC.NavLayerCurrentMask >>= 1;
  6054. window->DC.ItemFlags = item_flags_backup;
  6055. // Title text (FIXME: refactor text alignment facilities along with RenderText helpers)
  6056. ImVec2 text_size = CalcTextSize(name, NULL, true);
  6057. ImRect text_r = title_bar_rect;
  6058. float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  6059. float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  6060. if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
  6061. text_r.Min.x += pad_left;
  6062. text_r.Max.x -= pad_right;
  6063. ImRect clip_rect = text_r;
  6064. clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
  6065. RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
  6066. }
  6067. // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
  6068. window->WindowRectClipped = window->Rect();
  6069. window->WindowRectClipped.ClipWith(window->ClipRect);
  6070. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  6071. // 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.
  6072. // Maybe we can support CTRL+C on every element?
  6073. /*
  6074. if (g.ActiveId == move_id)
  6075. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  6076. ImGui::LogToClipboard();
  6077. */
  6078. // Inner rectangle
  6079. // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
  6080. // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
  6081. window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
  6082. window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
  6083. window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize;
  6084. window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
  6085. //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
  6086. // Inner clipping rectangle
  6087. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  6088. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
  6089. window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y);
  6090. window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
  6091. window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y);
  6092. // After Begin() we fill the last item / hovered data using the title bar data. Make that a standard behavior (to allow usage of context menus on title bar only, etc.).
  6093. window->DC.LastItemId = window->MoveId;
  6094. window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
  6095. window->DC.LastItemRect = title_bar_rect;
  6096. }
  6097. else
  6098. {
  6099. SetCurrentViewport(window->Viewport);
  6100. SetCurrentWindow(window);
  6101. }
  6102. PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
  6103. // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
  6104. if (first_begin_of_the_frame)
  6105. window->WriteAccessed = false;
  6106. window->BeginCount++;
  6107. g.NextWindowData.Clear();
  6108. // Child window can be out of sight and have "negative" clip windows.
  6109. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
  6110. if (flags & ImGuiWindowFlags_ChildWindow)
  6111. {
  6112. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  6113. window->Collapsed = parent_window && parent_window->Collapsed;
  6114. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  6115. window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y);
  6116. // We also hide the window from rendering because we've already added its border to the command list.
  6117. // (we could perform the check earlier in the function but it is simpler at this point)
  6118. if (window->Collapsed)
  6119. window->Active = false;
  6120. }
  6121. if (style.Alpha <= 0.0f)
  6122. window->Active = false;
  6123. // Return false if we don't intend to display anything to allow user to perform an early out optimization
  6124. window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
  6125. return !window->SkipItems;
  6126. }
  6127. // Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
  6128. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  6129. bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
  6130. {
  6131. // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
  6132. if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
  6133. ImGui::SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
  6134. // Old API feature: override the window background alpha with a parameter.
  6135. if (bg_alpha_override >= 0.0f)
  6136. ImGui::SetNextWindowBgAlpha(bg_alpha_override);
  6137. return ImGui::Begin(name, p_open, flags);
  6138. }
  6139. #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  6140. void ImGui::End()
  6141. {
  6142. ImGuiContext& g = *GImGui;
  6143. ImGuiWindow* window = g.CurrentWindow;
  6144. if (window->DC.ColumnsSet != NULL)
  6145. EndColumns();
  6146. PopClipRect(); // Inner window clip rectangle
  6147. // Stop logging
  6148. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  6149. LogFinish();
  6150. // Pop from window stack
  6151. g.CurrentWindowStack.pop_back();
  6152. if (window->Flags & ImGuiWindowFlags_Popup)
  6153. g.CurrentPopupStack.pop_back();
  6154. CheckStacksSize(window, false);
  6155. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  6156. }
  6157. // Vertical scrollbar
  6158. // The entire piece of code below is rather confusing because:
  6159. // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
  6160. // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
  6161. // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
  6162. void ImGui::Scrollbar(ImGuiLayoutType direction)
  6163. {
  6164. ImGuiContext& g = *GImGui;
  6165. ImGuiWindow* window = g.CurrentWindow;
  6166. const bool horizontal = (direction == ImGuiLayoutType_Horizontal);
  6167. const ImGuiStyle& style = g.Style;
  6168. const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
  6169. // Render background
  6170. bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
  6171. float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
  6172. const ImRect window_rect = window->Rect();
  6173. const float border_size = window->WindowBorderSize;
  6174. ImRect bb = horizontal
  6175. ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size)
  6176. : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size);
  6177. if (!horizontal)
  6178. bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
  6179. if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f)
  6180. return;
  6181. int window_rounding_corners;
  6182. if (horizontal)
  6183. window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
  6184. else
  6185. window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
  6186. window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners);
  6187. bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
  6188. // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
  6189. float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
  6190. float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
  6191. float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w;
  6192. float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
  6193. // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
  6194. // But we maintain a minimum size in pixel to allow for the user to still aim inside.
  6195. IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
  6196. const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f);
  6197. const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
  6198. const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
  6199. // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
  6200. bool held = false;
  6201. bool hovered = false;
  6202. const bool previously_held = (g.ActiveId == id);
  6203. ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
  6204. float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
  6205. float scroll_ratio = ImSaturate(scroll_v / scroll_max);
  6206. float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  6207. if (held && grab_h_norm < 1.0f)
  6208. {
  6209. float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
  6210. float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  6211. float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y;
  6212. // Click position in scrollbar normalized space (0.0f->1.0f)
  6213. const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
  6214. SetHoveredID(id);
  6215. bool seek_absolute = false;
  6216. if (!previously_held)
  6217. {
  6218. // On initial click calculate the distance between mouse and the center of the grab
  6219. if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
  6220. {
  6221. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  6222. }
  6223. else
  6224. {
  6225. seek_absolute = true;
  6226. *click_delta_to_grab_center_v = 0.0f;
  6227. }
  6228. }
  6229. // Apply scroll
  6230. // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position
  6231. const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm));
  6232. scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
  6233. if (horizontal)
  6234. window->Scroll.x = scroll_v;
  6235. else
  6236. window->Scroll.y = scroll_v;
  6237. // Update values for rendering
  6238. scroll_ratio = ImSaturate(scroll_v / scroll_max);
  6239. grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  6240. // Update distance to grab now that we have seeked and saturated
  6241. if (seek_absolute)
  6242. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  6243. }
  6244. // Render
  6245. const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
  6246. ImRect grab_rect;
  6247. if (horizontal)
  6248. grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y);
  6249. else
  6250. grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y));
  6251. window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
  6252. }
  6253. void ImGui::BringWindowToFront(ImGuiWindow* window)
  6254. {
  6255. ImGuiContext& g = *GImGui;
  6256. ImGuiWindow* current_front_window = g.Windows.back();
  6257. if (current_front_window == window || current_front_window->RootWindow == window)
  6258. return;
  6259. for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
  6260. if (g.Windows[i] == window)
  6261. {
  6262. g.Windows.erase(g.Windows.Data + i);
  6263. g.Windows.push_back(window);
  6264. break;
  6265. }
  6266. }
  6267. void ImGui::BringWindowToBack(ImGuiWindow* window)
  6268. {
  6269. ImGuiContext& g = *GImGui;
  6270. if (g.Windows[0] == window)
  6271. return;
  6272. for (int i = 0; i < g.Windows.Size; i++)
  6273. if (g.Windows[i] == window)
  6274. {
  6275. memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
  6276. g.Windows[0] = window;
  6277. break;
  6278. }
  6279. }
  6280. // Moving window to front of display and set focus (which happens to be back of our sorted list)
  6281. void ImGui::FocusWindow(ImGuiWindow* window)
  6282. {
  6283. ImGuiContext& g = *GImGui;
  6284. if (g.NavWindow != window)
  6285. {
  6286. g.NavWindow = window;
  6287. if (window && g.NavDisableMouseHover)
  6288. g.NavMousePosDirty = true;
  6289. g.NavInitRequest = false;
  6290. g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
  6291. g.NavIdIsAlive = false;
  6292. g.NavLayer = 0;
  6293. }
  6294. // Passing NULL allow to disable keyboard focus
  6295. if (!window)
  6296. return;
  6297. // Move the root window to the top of the pile
  6298. if (window->RootWindow)
  6299. window = window->RootWindow;
  6300. // Steal focus on active widgets
  6301. if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
  6302. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
  6303. ClearActiveID();
  6304. // Bring to front
  6305. if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
  6306. BringWindowToFront(window);
  6307. }
  6308. void ImGui::FocusFrontMostActiveWindow(ImGuiWindow* ignore_window)
  6309. {
  6310. ImGuiContext& g = *GImGui;
  6311. for (int i = g.Windows.Size - 1; i >= 0; i--)
  6312. if (g.Windows[i] != ignore_window && g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
  6313. {
  6314. ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(g.Windows[i]);
  6315. FocusWindow(focus_window);
  6316. return;
  6317. }
  6318. }
  6319. void ImGui::PushItemWidth(float item_width)
  6320. {
  6321. ImGuiWindow* window = GetCurrentWindow();
  6322. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  6323. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
  6324. }
  6325. void ImGui::PushMultiItemsWidths(int components, float w_full)
  6326. {
  6327. ImGuiWindow* window = GetCurrentWindow();
  6328. const ImGuiStyle& style = GImGui->Style;
  6329. if (w_full <= 0.0f)
  6330. w_full = CalcItemWidth();
  6331. const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  6332. const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  6333. window->DC.ItemWidthStack.push_back(w_item_last);
  6334. for (int i = 0; i < components-1; i++)
  6335. window->DC.ItemWidthStack.push_back(w_item_one);
  6336. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  6337. }
  6338. void ImGui::PopItemWidth()
  6339. {
  6340. ImGuiWindow* window = GetCurrentWindow();
  6341. window->DC.ItemWidthStack.pop_back();
  6342. window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
  6343. }
  6344. float ImGui::CalcItemWidth()
  6345. {
  6346. ImGuiWindow* window = GetCurrentWindowRead();
  6347. float w = window->DC.ItemWidth;
  6348. if (w < 0.0f)
  6349. {
  6350. // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well.
  6351. float width_to_right_edge = GetContentRegionAvail().x;
  6352. w = ImMax(1.0f, width_to_right_edge + w);
  6353. }
  6354. w = (float)(int)w;
  6355. return w;
  6356. }
  6357. static ImFont* GetDefaultFont()
  6358. {
  6359. ImGuiContext& g = *GImGui;
  6360. return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0];
  6361. }
  6362. void ImGui::SetCurrentFont(ImFont* font)
  6363. {
  6364. ImGuiContext& g = *GImGui;
  6365. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  6366. IM_ASSERT(font->Scale > 0.0f);
  6367. g.Font = font;
  6368. g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
  6369. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  6370. ImFontAtlas* atlas = g.Font->ContainerAtlas;
  6371. g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
  6372. g.DrawListSharedData.Font = g.Font;
  6373. g.DrawListSharedData.FontSize = g.FontSize;
  6374. }
  6375. void ImGui::PushFont(ImFont* font)
  6376. {
  6377. ImGuiContext& g = *GImGui;
  6378. if (!font)
  6379. font = GetDefaultFont();
  6380. SetCurrentFont(font);
  6381. g.FontStack.push_back(font);
  6382. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  6383. }
  6384. void ImGui::PopFont()
  6385. {
  6386. ImGuiContext& g = *GImGui;
  6387. g.CurrentWindow->DrawList->PopTextureID();
  6388. g.FontStack.pop_back();
  6389. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  6390. }
  6391. void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
  6392. {
  6393. ImGuiWindow* window = GetCurrentWindow();
  6394. if (enabled)
  6395. window->DC.ItemFlags |= option;
  6396. else
  6397. window->DC.ItemFlags &= ~option;
  6398. window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
  6399. }
  6400. void ImGui::PopItemFlag()
  6401. {
  6402. ImGuiWindow* window = GetCurrentWindow();
  6403. window->DC.ItemFlagsStack.pop_back();
  6404. window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
  6405. }
  6406. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  6407. {
  6408. PushItemFlag(ImGuiItemFlags_AllowKeyboardFocus, allow_keyboard_focus);
  6409. }
  6410. void ImGui::PopAllowKeyboardFocus()
  6411. {
  6412. PopItemFlag();
  6413. }
  6414. void ImGui::PushButtonRepeat(bool repeat)
  6415. {
  6416. PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
  6417. }
  6418. void ImGui::PopButtonRepeat()
  6419. {
  6420. PopItemFlag();
  6421. }
  6422. void ImGui::PushTextWrapPos(float wrap_pos_x)
  6423. {
  6424. ImGuiWindow* window = GetCurrentWindow();
  6425. window->DC.TextWrapPos = wrap_pos_x;
  6426. window->DC.TextWrapPosStack.push_back(wrap_pos_x);
  6427. }
  6428. void ImGui::PopTextWrapPos()
  6429. {
  6430. ImGuiWindow* window = GetCurrentWindow();
  6431. window->DC.TextWrapPosStack.pop_back();
  6432. window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
  6433. }
  6434. // 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
  6435. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  6436. {
  6437. ImGuiContext& g = *GImGui;
  6438. ImGuiColMod backup;
  6439. backup.Col = idx;
  6440. backup.BackupValue = g.Style.Colors[idx];
  6441. g.ColorModifiers.push_back(backup);
  6442. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  6443. }
  6444. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  6445. {
  6446. ImGuiContext& g = *GImGui;
  6447. ImGuiColMod backup;
  6448. backup.Col = idx;
  6449. backup.BackupValue = g.Style.Colors[idx];
  6450. g.ColorModifiers.push_back(backup);
  6451. g.Style.Colors[idx] = col;
  6452. }
  6453. void ImGui::PopStyleColor(int count)
  6454. {
  6455. ImGuiContext& g = *GImGui;
  6456. while (count > 0)
  6457. {
  6458. ImGuiColMod& backup = g.ColorModifiers.back();
  6459. g.Style.Colors[backup.Col] = backup.BackupValue;
  6460. g.ColorModifiers.pop_back();
  6461. count--;
  6462. }
  6463. }
  6464. struct ImGuiStyleVarInfo
  6465. {
  6466. ImGuiDataType Type;
  6467. ImU32 Offset;
  6468. void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  6469. };
  6470. static const ImGuiStyleVarInfo GStyleVarInfo[] =
  6471. {
  6472. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  6473. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  6474. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  6475. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
  6476. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  6477. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
  6478. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
  6479. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
  6480. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
  6481. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
  6482. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  6483. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  6484. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
  6485. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  6486. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  6487. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  6488. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
  6489. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
  6490. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  6491. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
  6492. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  6493. };
  6494. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  6495. {
  6496. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
  6497. IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
  6498. return &GStyleVarInfo[idx];
  6499. }
  6500. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  6501. {
  6502. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  6503. if (var_info->Type == ImGuiDataType_Float)
  6504. {
  6505. ImGuiContext& g = *GImGui;
  6506. float* pvar = (float*)var_info->GetVarPtr(&g.Style);
  6507. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  6508. *pvar = val;
  6509. return;
  6510. }
  6511. IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
  6512. }
  6513. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  6514. {
  6515. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  6516. if (var_info->Type == ImGuiDataType_Float2)
  6517. {
  6518. ImGuiContext& g = *GImGui;
  6519. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
  6520. g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  6521. *pvar = val;
  6522. return;
  6523. }
  6524. IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
  6525. }
  6526. void ImGui::PopStyleVar(int count)
  6527. {
  6528. ImGuiContext& g = *GImGui;
  6529. while (count > 0)
  6530. {
  6531. ImGuiStyleMod& backup = g.StyleModifiers.back();
  6532. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  6533. if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr(&g.Style)) = backup.BackupFloat[0];
  6534. else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr(&g.Style)) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]);
  6535. else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr(&g.Style)) = backup.BackupInt[0];
  6536. g.StyleModifiers.pop_back();
  6537. count--;
  6538. }
  6539. }
  6540. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  6541. {
  6542. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  6543. switch (idx)
  6544. {
  6545. case ImGuiCol_Text: return "Text";
  6546. case ImGuiCol_TextDisabled: return "TextDisabled";
  6547. case ImGuiCol_WindowBg: return "WindowBg";
  6548. case ImGuiCol_ChildBg: return "ChildBg";
  6549. case ImGuiCol_PopupBg: return "PopupBg";
  6550. case ImGuiCol_Border: return "Border";
  6551. case ImGuiCol_BorderShadow: return "BorderShadow";
  6552. case ImGuiCol_FrameBg: return "FrameBg";
  6553. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  6554. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  6555. case ImGuiCol_TitleBg: return "TitleBg";
  6556. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  6557. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  6558. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  6559. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  6560. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  6561. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  6562. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  6563. case ImGuiCol_CheckMark: return "CheckMark";
  6564. case ImGuiCol_SliderGrab: return "SliderGrab";
  6565. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  6566. case ImGuiCol_Button: return "Button";
  6567. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  6568. case ImGuiCol_ButtonActive: return "ButtonActive";
  6569. case ImGuiCol_Header: return "Header";
  6570. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  6571. case ImGuiCol_HeaderActive: return "HeaderActive";
  6572. case ImGuiCol_Separator: return "Separator";
  6573. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  6574. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  6575. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  6576. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  6577. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  6578. case ImGuiCol_PlotLines: return "PlotLines";
  6579. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  6580. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  6581. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  6582. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  6583. case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
  6584. case ImGuiCol_DragDropTarget: return "DragDropTarget";
  6585. case ImGuiCol_NavHighlight: return "NavHighlight";
  6586. case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
  6587. }
  6588. IM_ASSERT(0);
  6589. return "Unknown";
  6590. }
  6591. bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
  6592. {
  6593. if (window->RootWindow == potential_parent)
  6594. return true;
  6595. while (window != NULL)
  6596. {
  6597. if (window == potential_parent)
  6598. return true;
  6599. window = window->ParentWindow;
  6600. }
  6601. return false;
  6602. }
  6603. bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
  6604. {
  6605. IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
  6606. ImGuiContext& g = *GImGui;
  6607. if (flags & ImGuiHoveredFlags_AnyWindow)
  6608. {
  6609. if (g.HoveredWindow == NULL)
  6610. return false;
  6611. }
  6612. else
  6613. {
  6614. switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
  6615. {
  6616. case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
  6617. if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
  6618. return false;
  6619. break;
  6620. case ImGuiHoveredFlags_RootWindow:
  6621. if (g.HoveredWindow != g.CurrentWindow->RootWindow)
  6622. return false;
  6623. break;
  6624. case ImGuiHoveredFlags_ChildWindows:
  6625. if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
  6626. return false;
  6627. break;
  6628. default:
  6629. if (g.HoveredWindow != g.CurrentWindow)
  6630. return false;
  6631. break;
  6632. }
  6633. }
  6634. if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
  6635. return false;
  6636. if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  6637. if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
  6638. return false;
  6639. return true;
  6640. }
  6641. bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
  6642. {
  6643. ImGuiContext& g = *GImGui;
  6644. IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
  6645. if (flags & ImGuiFocusedFlags_AnyWindow)
  6646. return g.NavWindow != NULL;
  6647. switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
  6648. {
  6649. case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
  6650. return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
  6651. case ImGuiFocusedFlags_RootWindow:
  6652. return g.NavWindow == g.CurrentWindow->RootWindow;
  6653. case ImGuiFocusedFlags_ChildWindows:
  6654. return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
  6655. default:
  6656. return g.NavWindow == g.CurrentWindow;
  6657. }
  6658. }
  6659. // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
  6660. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
  6661. {
  6662. ImGuiContext& g = *GImGui;
  6663. return window->Active && window == window->RootWindowForTabbing && (!(window->Flags & ImGuiWindowFlags_NoNavFocus) || window == g.NavWindow);
  6664. }
  6665. float ImGui::GetWindowWidth()
  6666. {
  6667. ImGuiWindow* window = GImGui->CurrentWindow;
  6668. return window->Size.x;
  6669. }
  6670. float ImGui::GetWindowHeight()
  6671. {
  6672. ImGuiWindow* window = GImGui->CurrentWindow;
  6673. return window->Size.y;
  6674. }
  6675. ImVec2 ImGui::GetWindowPos()
  6676. {
  6677. ImGuiContext& g = *GImGui;
  6678. ImGuiWindow* window = g.CurrentWindow;
  6679. return window->Pos;
  6680. }
  6681. static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
  6682. {
  6683. window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
  6684. window->Scroll.x = new_scroll_x;
  6685. window->DC.CursorMaxPos.x -= window->Scroll.x;
  6686. }
  6687. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
  6688. {
  6689. window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
  6690. window->Scroll.y = new_scroll_y;
  6691. window->DC.CursorMaxPos.y -= window->Scroll.y;
  6692. }
  6693. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  6694. {
  6695. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6696. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  6697. return;
  6698. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6699. window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
  6700. // Set
  6701. const ImVec2 old_pos = window->Pos;
  6702. window->PosFloat = pos;
  6703. window->Pos = ImFloor(pos);
  6704. window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
  6705. window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
  6706. }
  6707. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  6708. {
  6709. ImGuiWindow* window = GetCurrentWindowRead();
  6710. SetWindowPos(window, pos, cond);
  6711. }
  6712. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  6713. {
  6714. if (ImGuiWindow* window = FindWindowByName(name))
  6715. SetWindowPos(window, pos, cond);
  6716. }
  6717. ImVec2 ImGui::GetWindowSize()
  6718. {
  6719. ImGuiWindow* window = GetCurrentWindowRead();
  6720. return window->Size;
  6721. }
  6722. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  6723. {
  6724. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6725. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  6726. return;
  6727. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6728. // Set
  6729. if (size.x > 0.0f)
  6730. {
  6731. window->AutoFitFramesX = 0;
  6732. window->SizeFull.x = size.x;
  6733. }
  6734. else
  6735. {
  6736. window->AutoFitFramesX = 2;
  6737. window->AutoFitOnlyGrows = false;
  6738. }
  6739. if (size.y > 0.0f)
  6740. {
  6741. window->AutoFitFramesY = 0;
  6742. window->SizeFull.y = size.y;
  6743. }
  6744. else
  6745. {
  6746. window->AutoFitFramesY = 2;
  6747. window->AutoFitOnlyGrows = false;
  6748. }
  6749. }
  6750. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  6751. {
  6752. SetWindowSize(GImGui->CurrentWindow, size, cond);
  6753. }
  6754. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  6755. {
  6756. if (ImGuiWindow* window = FindWindowByName(name))
  6757. SetWindowSize(window, size, cond);
  6758. }
  6759. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  6760. {
  6761. // Test condition (NB: bit 0 is always true) and clear flags for next time
  6762. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  6763. return;
  6764. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  6765. // Set
  6766. window->Collapsed = collapsed;
  6767. }
  6768. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  6769. {
  6770. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  6771. }
  6772. bool ImGui::IsWindowCollapsed()
  6773. {
  6774. ImGuiWindow* window = GetCurrentWindowRead();
  6775. return window->Collapsed;
  6776. }
  6777. bool ImGui::IsWindowAppearing()
  6778. {
  6779. ImGuiWindow* window = GetCurrentWindowRead();
  6780. return window->Appearing;
  6781. }
  6782. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  6783. {
  6784. if (ImGuiWindow* window = FindWindowByName(name))
  6785. SetWindowCollapsed(window, collapsed, cond);
  6786. }
  6787. void ImGui::SetWindowFocus()
  6788. {
  6789. FocusWindow(GImGui->CurrentWindow);
  6790. }
  6791. void ImGui::SetWindowFocus(const char* name)
  6792. {
  6793. if (name)
  6794. {
  6795. if (ImGuiWindow* window = FindWindowByName(name))
  6796. FocusWindow(window);
  6797. }
  6798. else
  6799. {
  6800. FocusWindow(NULL);
  6801. }
  6802. }
  6803. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
  6804. {
  6805. ImGuiContext& g = *GImGui;
  6806. g.NextWindowData.PosVal = pos;
  6807. g.NextWindowData.PosPivotVal = pivot;
  6808. g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
  6809. }
  6810. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  6811. {
  6812. ImGuiContext& g = *GImGui;
  6813. g.NextWindowData.SizeVal = size;
  6814. g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
  6815. }
  6816. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
  6817. {
  6818. ImGuiContext& g = *GImGui;
  6819. g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
  6820. g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
  6821. g.NextWindowData.SizeCallback = custom_callback;
  6822. g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
  6823. }
  6824. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  6825. {
  6826. ImGuiContext& g = *GImGui;
  6827. g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
  6828. g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
  6829. }
  6830. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  6831. {
  6832. ImGuiContext& g = *GImGui;
  6833. g.NextWindowData.CollapsedVal = collapsed;
  6834. g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
  6835. }
  6836. void ImGui::SetNextWindowFocus()
  6837. {
  6838. ImGuiContext& g = *GImGui;
  6839. g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
  6840. }
  6841. void ImGui::SetNextWindowBgAlpha(float alpha)
  6842. {
  6843. ImGuiContext& g = *GImGui;
  6844. g.NextWindowData.BgAlphaVal = alpha;
  6845. g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
  6846. }
  6847. void ImGui::SetNextWindowViewport(ImGuiID id)
  6848. {
  6849. ImGuiContext& g = *GImGui;
  6850. g.NextWindowData.ViewportCond = ImGuiCond_Always;
  6851. g.NextWindowData.ViewportId = id;
  6852. }
  6853. // In window space (not screen space!)
  6854. ImVec2 ImGui::GetContentRegionMax()
  6855. {
  6856. ImGuiWindow* window = GetCurrentWindowRead();
  6857. ImVec2 mx = window->ContentsRegionRect.Max;
  6858. if (window->DC.ColumnsSet)
  6859. mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x;
  6860. return mx;
  6861. }
  6862. ImVec2 ImGui::GetContentRegionAvail()
  6863. {
  6864. ImGuiWindow* window = GetCurrentWindowRead();
  6865. return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
  6866. }
  6867. float ImGui::GetContentRegionAvailWidth()
  6868. {
  6869. return GetContentRegionAvail().x;
  6870. }
  6871. // In window space (not screen space!)
  6872. ImVec2 ImGui::GetWindowContentRegionMin()
  6873. {
  6874. ImGuiWindow* window = GetCurrentWindowRead();
  6875. return window->ContentsRegionRect.Min;
  6876. }
  6877. ImVec2 ImGui::GetWindowContentRegionMax()
  6878. {
  6879. ImGuiWindow* window = GetCurrentWindowRead();
  6880. return window->ContentsRegionRect.Max;
  6881. }
  6882. float ImGui::GetWindowContentRegionWidth()
  6883. {
  6884. ImGuiWindow* window = GetCurrentWindowRead();
  6885. return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x;
  6886. }
  6887. float ImGui::GetTextLineHeight()
  6888. {
  6889. ImGuiContext& g = *GImGui;
  6890. return g.FontSize;
  6891. }
  6892. float ImGui::GetTextLineHeightWithSpacing()
  6893. {
  6894. ImGuiContext& g = *GImGui;
  6895. return g.FontSize + g.Style.ItemSpacing.y;
  6896. }
  6897. float ImGui::GetFrameHeight()
  6898. {
  6899. ImGuiContext& g = *GImGui;
  6900. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  6901. }
  6902. float ImGui::GetFrameHeightWithSpacing()
  6903. {
  6904. ImGuiContext& g = *GImGui;
  6905. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  6906. }
  6907. ImDrawList* ImGui::GetWindowDrawList()
  6908. {
  6909. ImGuiWindow* window = GetCurrentWindow();
  6910. return window->DrawList;
  6911. }
  6912. ImFont* ImGui::GetFont()
  6913. {
  6914. return GImGui->Font;
  6915. }
  6916. float ImGui::GetFontSize()
  6917. {
  6918. return GImGui->FontSize;
  6919. }
  6920. ImVec2 ImGui::GetFontTexUvWhitePixel()
  6921. {
  6922. return GImGui->DrawListSharedData.TexUvWhitePixel;
  6923. }
  6924. void ImGui::SetWindowFontScale(float scale)
  6925. {
  6926. ImGuiContext& g = *GImGui;
  6927. ImGuiWindow* window = GetCurrentWindow();
  6928. window->FontWindowScale = scale;
  6929. g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
  6930. }
  6931. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  6932. // 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'.
  6933. ImVec2 ImGui::GetCursorPos()
  6934. {
  6935. ImGuiWindow* window = GetCurrentWindowRead();
  6936. return window->DC.CursorPos - window->Pos + window->Scroll;
  6937. }
  6938. float ImGui::GetCursorPosX()
  6939. {
  6940. ImGuiWindow* window = GetCurrentWindowRead();
  6941. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  6942. }
  6943. float ImGui::GetCursorPosY()
  6944. {
  6945. ImGuiWindow* window = GetCurrentWindowRead();
  6946. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  6947. }
  6948. void ImGui::SetCursorPos(const ImVec2& local_pos)
  6949. {
  6950. ImGuiWindow* window = GetCurrentWindow();
  6951. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  6952. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  6953. }
  6954. void ImGui::SetCursorPosX(float x)
  6955. {
  6956. ImGuiWindow* window = GetCurrentWindow();
  6957. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  6958. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  6959. }
  6960. void ImGui::SetCursorPosY(float y)
  6961. {
  6962. ImGuiWindow* window = GetCurrentWindow();
  6963. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  6964. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  6965. }
  6966. ImVec2 ImGui::GetCursorStartPos()
  6967. {
  6968. ImGuiWindow* window = GetCurrentWindowRead();
  6969. return window->DC.CursorStartPos - window->Pos;
  6970. }
  6971. ImVec2 ImGui::GetCursorScreenPos()
  6972. {
  6973. ImGuiWindow* window = GetCurrentWindowRead();
  6974. return window->DC.CursorPos;
  6975. }
  6976. void ImGui::SetCursorScreenPos(const ImVec2& screen_pos)
  6977. {
  6978. ImGuiWindow* window = GetCurrentWindow();
  6979. window->DC.CursorPos = screen_pos;
  6980. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  6981. }
  6982. float ImGui::GetScrollX()
  6983. {
  6984. return GImGui->CurrentWindow->Scroll.x;
  6985. }
  6986. float ImGui::GetScrollY()
  6987. {
  6988. return GImGui->CurrentWindow->Scroll.y;
  6989. }
  6990. float ImGui::GetScrollMaxX()
  6991. {
  6992. return GetScrollMaxX(GImGui->CurrentWindow);
  6993. }
  6994. float ImGui::GetScrollMaxY()
  6995. {
  6996. return GetScrollMaxY(GImGui->CurrentWindow);
  6997. }
  6998. void ImGui::SetScrollX(float scroll_x)
  6999. {
  7000. ImGuiWindow* window = GetCurrentWindow();
  7001. window->ScrollTarget.x = scroll_x;
  7002. window->ScrollTargetCenterRatio.x = 0.0f;
  7003. }
  7004. void ImGui::SetScrollY(float scroll_y)
  7005. {
  7006. ImGuiWindow* window = GetCurrentWindow();
  7007. window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
  7008. window->ScrollTargetCenterRatio.y = 0.0f;
  7009. }
  7010. void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
  7011. {
  7012. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  7013. ImGuiWindow* window = GetCurrentWindow();
  7014. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  7015. window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
  7016. window->ScrollTargetCenterRatio.y = center_y_ratio;
  7017. // Minor hack to to make scrolling to top/bottom of window take account of WindowPadding, it looks more right to the user this way
  7018. if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y)
  7019. window->ScrollTarget.y = 0.0f;
  7020. else if (center_y_ratio >= 1.0f && window->ScrollTarget.y >= window->SizeContents.y - window->WindowPadding.y + GImGui->Style.ItemSpacing.y)
  7021. window->ScrollTarget.y = window->SizeContents.y;
  7022. }
  7023. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  7024. void ImGui::SetScrollHere(float center_y_ratio)
  7025. {
  7026. ImGuiWindow* window = GetCurrentWindow();
  7027. float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
  7028. target_y += (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
  7029. SetScrollFromPosY(target_y, center_y_ratio);
  7030. }
  7031. void ImGui::ActivateItem(ImGuiID id)
  7032. {
  7033. ImGuiContext& g = *GImGui;
  7034. g.NavNextActivateId = id;
  7035. }
  7036. void ImGui::SetKeyboardFocusHere(int offset)
  7037. {
  7038. IM_ASSERT(offset >= -1); // -1 is allowed but not below
  7039. ImGuiWindow* window = GetCurrentWindow();
  7040. window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
  7041. window->FocusIdxTabRequestNext = INT_MAX;
  7042. }
  7043. void ImGui::SetItemDefaultFocus()
  7044. {
  7045. ImGuiContext& g = *GImGui;
  7046. ImGuiWindow* window = g.CurrentWindow;
  7047. if (!window->Appearing)
  7048. return;
  7049. if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
  7050. {
  7051. g.NavInitRequest = false;
  7052. g.NavInitResultId = g.NavWindow->DC.LastItemId;
  7053. g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
  7054. NavUpdateAnyRequestFlag();
  7055. if (!IsItemVisible())
  7056. SetScrollHere();
  7057. }
  7058. }
  7059. void ImGui::SetStateStorage(ImGuiStorage* tree)
  7060. {
  7061. ImGuiWindow* window = GetCurrentWindow();
  7062. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  7063. }
  7064. ImGuiStorage* ImGui::GetStateStorage()
  7065. {
  7066. ImGuiWindow* window = GetCurrentWindowRead();
  7067. return window->DC.StateStorage;
  7068. }
  7069. void ImGui::TextV(const char* fmt, va_list args)
  7070. {
  7071. ImGuiWindow* window = GetCurrentWindow();
  7072. if (window->SkipItems)
  7073. return;
  7074. ImGuiContext& g = *GImGui;
  7075. const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  7076. TextUnformatted(g.TempBuffer, text_end);
  7077. }
  7078. void ImGui::Text(const char* fmt, ...)
  7079. {
  7080. va_list args;
  7081. va_start(args, fmt);
  7082. TextV(fmt, args);
  7083. va_end(args);
  7084. }
  7085. void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
  7086. {
  7087. PushStyleColor(ImGuiCol_Text, col);
  7088. TextV(fmt, args);
  7089. PopStyleColor();
  7090. }
  7091. void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
  7092. {
  7093. va_list args;
  7094. va_start(args, fmt);
  7095. TextColoredV(col, fmt, args);
  7096. va_end(args);
  7097. }
  7098. void ImGui::TextDisabledV(const char* fmt, va_list args)
  7099. {
  7100. PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
  7101. TextV(fmt, args);
  7102. PopStyleColor();
  7103. }
  7104. void ImGui::TextDisabled(const char* fmt, ...)
  7105. {
  7106. va_list args;
  7107. va_start(args, fmt);
  7108. TextDisabledV(fmt, args);
  7109. va_end(args);
  7110. }
  7111. void ImGui::TextWrappedV(const char* fmt, va_list args)
  7112. {
  7113. bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set
  7114. if (need_wrap) PushTextWrapPos(0.0f);
  7115. TextV(fmt, args);
  7116. if (need_wrap) PopTextWrapPos();
  7117. }
  7118. void ImGui::TextWrapped(const char* fmt, ...)
  7119. {
  7120. va_list args;
  7121. va_start(args, fmt);
  7122. TextWrappedV(fmt, args);
  7123. va_end(args);
  7124. }
  7125. void ImGui::TextUnformatted(const char* text, const char* text_end)
  7126. {
  7127. ImGuiWindow* window = GetCurrentWindow();
  7128. if (window->SkipItems)
  7129. return;
  7130. ImGuiContext& g = *GImGui;
  7131. IM_ASSERT(text != NULL);
  7132. const char* text_begin = text;
  7133. if (text_end == NULL)
  7134. text_end = text + strlen(text); // FIXME-OPT
  7135. const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
  7136. const float wrap_pos_x = window->DC.TextWrapPos;
  7137. const bool wrap_enabled = wrap_pos_x >= 0.0f;
  7138. if (text_end - text > 2000 && !wrap_enabled)
  7139. {
  7140. // Long text!
  7141. // Perform manual coarse clipping to optimize for long multi-line text
  7142. // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
  7143. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
  7144. const char* line = text;
  7145. const float line_height = GetTextLineHeight();
  7146. const ImRect clip_rect = window->ClipRect;
  7147. ImVec2 text_size(0,0);
  7148. if (text_pos.y <= clip_rect.Max.y)
  7149. {
  7150. ImVec2 pos = text_pos;
  7151. // Lines to skip (can't skip when logging text)
  7152. if (!g.LogEnabled)
  7153. {
  7154. int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height);
  7155. if (lines_skippable > 0)
  7156. {
  7157. int lines_skipped = 0;
  7158. while (line < text_end && lines_skipped < lines_skippable)
  7159. {
  7160. const char* line_end = strchr(line, '\n');
  7161. if (!line_end)
  7162. line_end = text_end;
  7163. line = line_end + 1;
  7164. lines_skipped++;
  7165. }
  7166. pos.y += lines_skipped * line_height;
  7167. }
  7168. }
  7169. // Lines to render
  7170. if (line < text_end)
  7171. {
  7172. ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
  7173. while (line < text_end)
  7174. {
  7175. const char* line_end = strchr(line, '\n');
  7176. if (IsClippedEx(line_rect, 0, false))
  7177. break;
  7178. const ImVec2 line_size = CalcTextSize(line, line_end, false);
  7179. text_size.x = ImMax(text_size.x, line_size.x);
  7180. RenderText(pos, line, line_end, false);
  7181. if (!line_end)
  7182. line_end = text_end;
  7183. line = line_end + 1;
  7184. line_rect.Min.y += line_height;
  7185. line_rect.Max.y += line_height;
  7186. pos.y += line_height;
  7187. }
  7188. // Count remaining lines
  7189. int lines_skipped = 0;
  7190. while (line < text_end)
  7191. {
  7192. const char* line_end = strchr(line, '\n');
  7193. if (!line_end)
  7194. line_end = text_end;
  7195. line = line_end + 1;
  7196. lines_skipped++;
  7197. }
  7198. pos.y += lines_skipped * line_height;
  7199. }
  7200. text_size.y += (pos - text_pos).y;
  7201. }
  7202. ImRect bb(text_pos, text_pos + text_size);
  7203. ItemSize(bb);
  7204. ItemAdd(bb, 0);
  7205. }
  7206. else
  7207. {
  7208. const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
  7209. const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
  7210. // Account of baseline offset
  7211. ImRect bb(text_pos, text_pos + text_size);
  7212. ItemSize(text_size);
  7213. if (!ItemAdd(bb, 0))
  7214. return;
  7215. // Render (we don't hide text after ## in this end-user function)
  7216. RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
  7217. }
  7218. }
  7219. void ImGui::AlignTextToFramePadding()
  7220. {
  7221. ImGuiWindow* window = GetCurrentWindow();
  7222. if (window->SkipItems)
  7223. return;
  7224. ImGuiContext& g = *GImGui;
  7225. window->DC.CurrentLineHeight = ImMax(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y * 2);
  7226. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  7227. }
  7228. // Add a label+text combo aligned to other label+value widgets
  7229. void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
  7230. {
  7231. ImGuiWindow* window = GetCurrentWindow();
  7232. if (window->SkipItems)
  7233. return;
  7234. ImGuiContext& g = *GImGui;
  7235. const ImGuiStyle& style = g.Style;
  7236. const float w = CalcItemWidth();
  7237. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7238. const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
  7239. const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size);
  7240. ItemSize(total_bb, style.FramePadding.y);
  7241. if (!ItemAdd(total_bb, 0))
  7242. return;
  7243. // Render
  7244. const char* value_text_begin = &g.TempBuffer[0];
  7245. const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  7246. RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
  7247. if (label_size.x > 0.0f)
  7248. RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
  7249. }
  7250. void ImGui::LabelText(const char* label, const char* fmt, ...)
  7251. {
  7252. va_list args;
  7253. va_start(args, fmt);
  7254. LabelTextV(label, fmt, args);
  7255. va_end(args);
  7256. }
  7257. bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
  7258. {
  7259. ImGuiContext& g = *GImGui;
  7260. ImGuiWindow* window = GetCurrentWindow();
  7261. if (flags & ImGuiButtonFlags_Disabled)
  7262. {
  7263. if (out_hovered) *out_hovered = false;
  7264. if (out_held) *out_held = false;
  7265. if (g.ActiveId == id) ClearActiveID();
  7266. return false;
  7267. }
  7268. // Default behavior requires click+release on same spot
  7269. if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
  7270. flags |= ImGuiButtonFlags_PressedOnClickRelease;
  7271. ImGuiWindow* backup_hovered_window = g.HoveredWindow;
  7272. if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
  7273. g.HoveredWindow = window;
  7274. bool pressed = false;
  7275. bool hovered = ItemHoverable(bb, id);
  7276. // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
  7277. if ((flags & ImGuiButtonFlags_PressedOnDragDropHold) && g.DragDropActive && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
  7278. if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
  7279. {
  7280. hovered = true;
  7281. SetHoveredID(id);
  7282. if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy
  7283. {
  7284. pressed = true;
  7285. FocusWindow(window);
  7286. }
  7287. }
  7288. if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
  7289. g.HoveredWindow = backup_hovered_window;
  7290. // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
  7291. if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
  7292. hovered = false;
  7293. // Mouse
  7294. if (hovered)
  7295. {
  7296. if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
  7297. {
  7298. // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
  7299. // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
  7300. // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
  7301. // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
  7302. // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
  7303. // FIXME-NAV: We don't honor those different behaviors.
  7304. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
  7305. {
  7306. SetActiveID(id, window);
  7307. if (!(flags & ImGuiButtonFlags_NoNavFocus))
  7308. SetFocusID(id, window);
  7309. FocusWindow(window);
  7310. }
  7311. if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
  7312. {
  7313. pressed = true;
  7314. if (flags & ImGuiButtonFlags_NoHoldingActiveID)
  7315. ClearActiveID();
  7316. else
  7317. SetActiveID(id, window); // Hold on ID
  7318. FocusWindow(window);
  7319. }
  7320. if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
  7321. {
  7322. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  7323. pressed = true;
  7324. ClearActiveID();
  7325. }
  7326. // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
  7327. // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
  7328. if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
  7329. pressed = true;
  7330. }
  7331. if (pressed)
  7332. g.NavDisableHighlight = true;
  7333. }
  7334. // Gamepad/Keyboard navigation
  7335. // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse.
  7336. if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId))
  7337. hovered = true;
  7338. if (g.NavActivateDownId == id)
  7339. {
  7340. bool nav_activated_by_code = (g.NavActivateId == id);
  7341. bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed);
  7342. if (nav_activated_by_code || nav_activated_by_inputs)
  7343. pressed = true;
  7344. if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id)
  7345. {
  7346. // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
  7347. g.NavActivateId = id; // This is so SetActiveId assign a Nav source
  7348. SetActiveID(id, window);
  7349. if (!(flags & ImGuiButtonFlags_NoNavFocus))
  7350. SetFocusID(id, window);
  7351. g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
  7352. }
  7353. }
  7354. bool held = false;
  7355. if (g.ActiveId == id)
  7356. {
  7357. if (g.ActiveIdSource == ImGuiInputSource_Mouse)
  7358. {
  7359. if (g.ActiveIdIsJustActivated)
  7360. g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
  7361. if (g.IO.MouseDown[0])
  7362. {
  7363. held = true;
  7364. }
  7365. else
  7366. {
  7367. if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
  7368. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  7369. if (!g.DragDropActive)
  7370. pressed = true;
  7371. ClearActiveID();
  7372. }
  7373. if (!(flags & ImGuiButtonFlags_NoNavFocus))
  7374. g.NavDisableHighlight = true;
  7375. }
  7376. else if (g.ActiveIdSource == ImGuiInputSource_Nav)
  7377. {
  7378. if (g.NavActivateDownId != id)
  7379. ClearActiveID();
  7380. }
  7381. }
  7382. if (out_hovered) *out_hovered = hovered;
  7383. if (out_held) *out_held = held;
  7384. return pressed;
  7385. }
  7386. bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
  7387. {
  7388. ImGuiWindow* window = GetCurrentWindow();
  7389. if (window->SkipItems)
  7390. return false;
  7391. ImGuiContext& g = *GImGui;
  7392. const ImGuiStyle& style = g.Style;
  7393. const ImGuiID id = window->GetID(label);
  7394. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7395. ImVec2 pos = window->DC.CursorPos;
  7396. if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
  7397. pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;
  7398. ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
  7399. const ImRect bb(pos, pos + size);
  7400. ItemSize(bb, style.FramePadding.y);
  7401. if (!ItemAdd(bb, id))
  7402. return false;
  7403. if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
  7404. flags |= ImGuiButtonFlags_Repeat;
  7405. bool hovered, held;
  7406. bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
  7407. // Render
  7408. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  7409. RenderNavHighlight(bb, id);
  7410. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  7411. RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
  7412. // Automatically close popups
  7413. //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  7414. // CloseCurrentPopup();
  7415. return pressed;
  7416. }
  7417. bool ImGui::Button(const char* label, const ImVec2& size_arg)
  7418. {
  7419. return ButtonEx(label, size_arg, 0);
  7420. }
  7421. // Small buttons fits within text without additional vertical spacing.
  7422. bool ImGui::SmallButton(const char* label)
  7423. {
  7424. ImGuiContext& g = *GImGui;
  7425. float backup_padding_y = g.Style.FramePadding.y;
  7426. g.Style.FramePadding.y = 0.0f;
  7427. bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine);
  7428. g.Style.FramePadding.y = backup_padding_y;
  7429. return pressed;
  7430. }
  7431. bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
  7432. {
  7433. ImGuiWindow* window = GetCurrentWindow();
  7434. if (window->SkipItems)
  7435. return false;
  7436. ImGuiContext& g = *GImGui;
  7437. const ImGuiID id = window->GetID(str_id);
  7438. float sz = ImGui::GetFrameHeight();
  7439. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(sz, sz));
  7440. ItemSize(bb);
  7441. if (!ItemAdd(bb, id))
  7442. return false;
  7443. bool hovered, held;
  7444. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  7445. // Render
  7446. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  7447. RenderNavHighlight(bb, id);
  7448. RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding);
  7449. RenderArrow(bb.Min + g.Style.FramePadding, dir);
  7450. return pressed;
  7451. }
  7452. // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
  7453. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
  7454. bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
  7455. {
  7456. ImGuiWindow* window = GetCurrentWindow();
  7457. if (window->SkipItems)
  7458. return false;
  7459. const ImGuiID id = window->GetID(str_id);
  7460. ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
  7461. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  7462. ItemSize(bb);
  7463. if (!ItemAdd(bb, id))
  7464. return false;
  7465. bool hovered, held;
  7466. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  7467. return pressed;
  7468. }
  7469. // Button to close a window
  7470. bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
  7471. {
  7472. ImGuiContext& g = *GImGui;
  7473. ImGuiWindow* window = g.CurrentWindow;
  7474. // We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window.
  7475. // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible).
  7476. const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
  7477. bool is_clipped = !ItemAdd(bb, id);
  7478. bool hovered, held;
  7479. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  7480. if (is_clipped)
  7481. return pressed;
  7482. // Render
  7483. ImVec2 center = bb.GetCenter();
  7484. if (hovered)
  7485. window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered), 9);
  7486. float cross_extent = (radius * 0.7071f) - 1.0f;
  7487. ImU32 cross_col = GetColorU32(ImGuiCol_Text);
  7488. center -= ImVec2(0.5f, 0.5f);
  7489. window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f);
  7490. window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f);
  7491. return pressed;
  7492. }
  7493. // [Internal]
  7494. bool ImGui::ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags)
  7495. {
  7496. ImGuiContext& g = *GImGui;
  7497. ImGuiWindow* window = g.CurrentWindow;
  7498. if (window->SkipItems)
  7499. return false;
  7500. const ImGuiStyle& style = g.Style;
  7501. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + padding.x * 2.0f, g.FontSize + padding.y * 2.0f));
  7502. ItemSize(bb, style.FramePadding.y);
  7503. if (!ItemAdd(bb, id))
  7504. return false;
  7505. bool hovered, held;
  7506. bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
  7507. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  7508. RenderNavHighlight(bb, id);
  7509. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  7510. RenderArrow(bb.Min + padding, dir, 1.0f);
  7511. return pressed;
  7512. }
  7513. void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
  7514. {
  7515. ImGuiWindow* window = GetCurrentWindow();
  7516. if (window->SkipItems)
  7517. return;
  7518. ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  7519. if (border_col.w > 0.0f)
  7520. bb.Max += ImVec2(2,2);
  7521. ItemSize(bb);
  7522. if (!ItemAdd(bb, 0))
  7523. return;
  7524. if (border_col.w > 0.0f)
  7525. {
  7526. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
  7527. window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col));
  7528. }
  7529. else
  7530. {
  7531. window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
  7532. }
  7533. }
  7534. // frame_padding < 0: uses FramePadding from style (default)
  7535. // frame_padding = 0: no framing
  7536. // frame_padding > 0: set framing size
  7537. // The color used are the button colors.
  7538. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
  7539. {
  7540. ImGuiWindow* window = GetCurrentWindow();
  7541. if (window->SkipItems)
  7542. return false;
  7543. ImGuiContext& g = *GImGui;
  7544. const ImGuiStyle& style = g.Style;
  7545. // Default to using texture ID as ID. User can still push string/integer prefixes.
  7546. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
  7547. PushID((void *)user_texture_id);
  7548. const ImGuiID id = window->GetID("#image");
  7549. PopID();
  7550. const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
  7551. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2);
  7552. const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
  7553. ItemSize(bb);
  7554. if (!ItemAdd(bb, id))
  7555. return false;
  7556. bool hovered, held;
  7557. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  7558. // Render
  7559. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  7560. RenderNavHighlight(bb, id);
  7561. RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
  7562. if (bg_col.w > 0.0f)
  7563. window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
  7564. window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
  7565. return pressed;
  7566. }
  7567. // Start logging ImGui output to TTY
  7568. void ImGui::LogToTTY(int max_depth)
  7569. {
  7570. ImGuiContext& g = *GImGui;
  7571. if (g.LogEnabled)
  7572. return;
  7573. ImGuiWindow* window = g.CurrentWindow;
  7574. IM_ASSERT(g.LogFile == NULL);
  7575. g.LogFile = stdout;
  7576. g.LogEnabled = true;
  7577. g.LogStartDepth = window->DC.TreeDepth;
  7578. if (max_depth >= 0)
  7579. g.LogAutoExpandMaxDepth = max_depth;
  7580. }
  7581. // Start logging ImGui output to given file
  7582. void ImGui::LogToFile(int max_depth, const char* filename)
  7583. {
  7584. ImGuiContext& g = *GImGui;
  7585. if (g.LogEnabled)
  7586. return;
  7587. ImGuiWindow* window = g.CurrentWindow;
  7588. if (!filename)
  7589. {
  7590. filename = g.IO.LogFilename;
  7591. if (!filename)
  7592. return;
  7593. }
  7594. IM_ASSERT(g.LogFile == NULL);
  7595. g.LogFile = ImFileOpen(filename, "ab");
  7596. if (!g.LogFile)
  7597. {
  7598. IM_ASSERT(g.LogFile != NULL); // Consider this an error
  7599. return;
  7600. }
  7601. g.LogEnabled = true;
  7602. g.LogStartDepth = window->DC.TreeDepth;
  7603. if (max_depth >= 0)
  7604. g.LogAutoExpandMaxDepth = max_depth;
  7605. }
  7606. // Start logging ImGui output to clipboard
  7607. void ImGui::LogToClipboard(int max_depth)
  7608. {
  7609. ImGuiContext& g = *GImGui;
  7610. if (g.LogEnabled)
  7611. return;
  7612. ImGuiWindow* window = g.CurrentWindow;
  7613. IM_ASSERT(g.LogFile == NULL);
  7614. g.LogFile = NULL;
  7615. g.LogEnabled = true;
  7616. g.LogStartDepth = window->DC.TreeDepth;
  7617. if (max_depth >= 0)
  7618. g.LogAutoExpandMaxDepth = max_depth;
  7619. }
  7620. void ImGui::LogFinish()
  7621. {
  7622. ImGuiContext& g = *GImGui;
  7623. if (!g.LogEnabled)
  7624. return;
  7625. LogText(IM_NEWLINE);
  7626. if (g.LogFile != NULL)
  7627. {
  7628. if (g.LogFile == stdout)
  7629. fflush(g.LogFile);
  7630. else
  7631. fclose(g.LogFile);
  7632. g.LogFile = NULL;
  7633. }
  7634. if (g.LogClipboard->size() > 1)
  7635. {
  7636. SetClipboardText(g.LogClipboard->begin());
  7637. g.LogClipboard->clear();
  7638. }
  7639. g.LogEnabled = false;
  7640. }
  7641. // Helper to display logging buttons
  7642. void ImGui::LogButtons()
  7643. {
  7644. ImGuiContext& g = *GImGui;
  7645. PushID("LogButtons");
  7646. const bool log_to_tty = Button("Log To TTY"); SameLine();
  7647. const bool log_to_file = Button("Log To File"); SameLine();
  7648. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  7649. PushItemWidth(80.0f);
  7650. PushAllowKeyboardFocus(false);
  7651. SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
  7652. PopAllowKeyboardFocus();
  7653. PopItemWidth();
  7654. PopID();
  7655. // Start logging at the end of the function so that the buttons don't appear in the log
  7656. if (log_to_tty)
  7657. LogToTTY(g.LogAutoExpandMaxDepth);
  7658. if (log_to_file)
  7659. LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
  7660. if (log_to_clipboard)
  7661. LogToClipboard(g.LogAutoExpandMaxDepth);
  7662. }
  7663. bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
  7664. {
  7665. if (flags & ImGuiTreeNodeFlags_Leaf)
  7666. return true;
  7667. // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions)
  7668. ImGuiContext& g = *GImGui;
  7669. ImGuiWindow* window = g.CurrentWindow;
  7670. ImGuiStorage* storage = window->DC.StateStorage;
  7671. bool is_open;
  7672. if (g.NextTreeNodeOpenCond != 0)
  7673. {
  7674. if (g.NextTreeNodeOpenCond & ImGuiCond_Always)
  7675. {
  7676. is_open = g.NextTreeNodeOpenVal;
  7677. storage->SetInt(id, is_open);
  7678. }
  7679. else
  7680. {
  7681. // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
  7682. const int stored_value = storage->GetInt(id, -1);
  7683. if (stored_value == -1)
  7684. {
  7685. is_open = g.NextTreeNodeOpenVal;
  7686. storage->SetInt(id, is_open);
  7687. }
  7688. else
  7689. {
  7690. is_open = stored_value != 0;
  7691. }
  7692. }
  7693. g.NextTreeNodeOpenCond = 0;
  7694. }
  7695. else
  7696. {
  7697. is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
  7698. }
  7699. // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
  7700. // NB- If we are above max depth we still allow manually opened nodes to be logged.
  7701. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth)
  7702. is_open = true;
  7703. return is_open;
  7704. }
  7705. bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
  7706. {
  7707. ImGuiWindow* window = GetCurrentWindow();
  7708. if (window->SkipItems)
  7709. return false;
  7710. ImGuiContext& g = *GImGui;
  7711. const ImGuiStyle& style = g.Style;
  7712. const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
  7713. const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
  7714. if (!label_end)
  7715. label_end = FindRenderedTextEnd(label);
  7716. const ImVec2 label_size = CalcTextSize(label, label_end, false);
  7717. // We vertically grow up to current line height up the typical widget height.
  7718. const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
  7719. const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
  7720. ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
  7721. if (display_frame)
  7722. {
  7723. // Framed header expand a little outside the default padding
  7724. frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
  7725. frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
  7726. }
  7727. const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing
  7728. const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
  7729. ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
  7730. // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
  7731. // (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
  7732. const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y);
  7733. bool is_open = TreeNodeBehaviorIsOpen(id, flags);
  7734. // Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
  7735. // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
  7736. // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
  7737. if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  7738. window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth);
  7739. bool item_add = ItemAdd(interact_bb, id);
  7740. window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
  7741. window->DC.LastItemDisplayRect = frame_bb;
  7742. if (!item_add)
  7743. {
  7744. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  7745. TreePushRawID(id);
  7746. return is_open;
  7747. }
  7748. // Flags that affects opening behavior:
  7749. // - 0(default) ..................... single-click anywhere to open
  7750. // - OpenOnDoubleClick .............. double-click anywhere to open
  7751. // - OpenOnArrow .................... single-click on arrow to open
  7752. // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
  7753. ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0);
  7754. if (!(flags & ImGuiTreeNodeFlags_Leaf))
  7755. button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
  7756. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  7757. button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
  7758. bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
  7759. if (!(flags & ImGuiTreeNodeFlags_Leaf))
  7760. {
  7761. bool toggled = false;
  7762. if (pressed)
  7763. {
  7764. toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id);
  7765. if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
  7766. toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover);
  7767. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  7768. toggled |= g.IO.MouseDoubleClicked[0];
  7769. if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
  7770. toggled = false;
  7771. }
  7772. if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
  7773. {
  7774. toggled = true;
  7775. NavMoveRequestCancel();
  7776. }
  7777. if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
  7778. {
  7779. toggled = true;
  7780. NavMoveRequestCancel();
  7781. }
  7782. if (toggled)
  7783. {
  7784. is_open = !is_open;
  7785. window->DC.StateStorage->SetInt(id, is_open);
  7786. }
  7787. }
  7788. if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
  7789. SetItemAllowOverlap();
  7790. // Render
  7791. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  7792. const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
  7793. if (display_frame)
  7794. {
  7795. // Framed type
  7796. RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding);
  7797. RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
  7798. RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
  7799. if (g.LogEnabled)
  7800. {
  7801. // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
  7802. const char log_prefix[] = "\n##";
  7803. const char log_suffix[] = "##";
  7804. LogRenderedText(&text_pos, log_prefix, log_prefix+3);
  7805. RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
  7806. LogRenderedText(&text_pos, log_suffix+1, log_suffix+3);
  7807. }
  7808. else
  7809. {
  7810. RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
  7811. }
  7812. }
  7813. else
  7814. {
  7815. // Unframed typed for tree nodes
  7816. if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
  7817. {
  7818. RenderFrame(frame_bb.Min, frame_bb.Max, col, false);
  7819. RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
  7820. }
  7821. if (flags & ImGuiTreeNodeFlags_Bullet)
  7822. RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
  7823. else if (!(flags & ImGuiTreeNodeFlags_Leaf))
  7824. RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
  7825. if (g.LogEnabled)
  7826. LogRenderedText(&text_pos, ">");
  7827. RenderText(text_pos, label, label_end, false);
  7828. }
  7829. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  7830. TreePushRawID(id);
  7831. return is_open;
  7832. }
  7833. // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
  7834. // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
  7835. bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
  7836. {
  7837. ImGuiWindow* window = GetCurrentWindow();
  7838. if (window->SkipItems)
  7839. return false;
  7840. return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
  7841. }
  7842. bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
  7843. {
  7844. ImGuiWindow* window = GetCurrentWindow();
  7845. if (window->SkipItems)
  7846. return false;
  7847. if (p_open && !*p_open)
  7848. return false;
  7849. ImGuiID id = window->GetID(label);
  7850. bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label);
  7851. if (p_open)
  7852. {
  7853. // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
  7854. ImGuiContext& g = *GImGui;
  7855. float button_sz = g.FontSize * 0.5f;
  7856. ImGuiItemHoveredDataBackup last_item_backup;
  7857. if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz))
  7858. *p_open = false;
  7859. last_item_backup.Restore();
  7860. }
  7861. return is_open;
  7862. }
  7863. bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
  7864. {
  7865. ImGuiWindow* window = GetCurrentWindow();
  7866. if (window->SkipItems)
  7867. return false;
  7868. return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
  7869. }
  7870. bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  7871. {
  7872. ImGuiWindow* window = GetCurrentWindow();
  7873. if (window->SkipItems)
  7874. return false;
  7875. ImGuiContext& g = *GImGui;
  7876. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  7877. return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
  7878. }
  7879. bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  7880. {
  7881. ImGuiWindow* window = GetCurrentWindow();
  7882. if (window->SkipItems)
  7883. return false;
  7884. ImGuiContext& g = *GImGui;
  7885. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  7886. return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
  7887. }
  7888. bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
  7889. {
  7890. return TreeNodeExV(str_id, 0, fmt, args);
  7891. }
  7892. bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
  7893. {
  7894. return TreeNodeExV(ptr_id, 0, fmt, args);
  7895. }
  7896. bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  7897. {
  7898. va_list args;
  7899. va_start(args, fmt);
  7900. bool is_open = TreeNodeExV(str_id, flags, fmt, args);
  7901. va_end(args);
  7902. return is_open;
  7903. }
  7904. bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  7905. {
  7906. va_list args;
  7907. va_start(args, fmt);
  7908. bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
  7909. va_end(args);
  7910. return is_open;
  7911. }
  7912. bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
  7913. {
  7914. va_list args;
  7915. va_start(args, fmt);
  7916. bool is_open = TreeNodeExV(str_id, 0, fmt, args);
  7917. va_end(args);
  7918. return is_open;
  7919. }
  7920. bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
  7921. {
  7922. va_list args;
  7923. va_start(args, fmt);
  7924. bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
  7925. va_end(args);
  7926. return is_open;
  7927. }
  7928. bool ImGui::TreeNode(const char* label)
  7929. {
  7930. ImGuiWindow* window = GetCurrentWindow();
  7931. if (window->SkipItems)
  7932. return false;
  7933. return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
  7934. }
  7935. void ImGui::TreeAdvanceToLabelPos()
  7936. {
  7937. ImGuiContext& g = *GImGui;
  7938. g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
  7939. }
  7940. // Horizontal distance preceding label when using TreeNode() or Bullet()
  7941. float ImGui::GetTreeNodeToLabelSpacing()
  7942. {
  7943. ImGuiContext& g = *GImGui;
  7944. return g.FontSize + (g.Style.FramePadding.x * 2.0f);
  7945. }
  7946. void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond)
  7947. {
  7948. ImGuiContext& g = *GImGui;
  7949. if (g.CurrentWindow->SkipItems)
  7950. return;
  7951. g.NextTreeNodeOpenVal = is_open;
  7952. g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
  7953. }
  7954. void ImGui::PushID(const char* str_id)
  7955. {
  7956. ImGuiWindow* window = GetCurrentWindowRead();
  7957. window->IDStack.push_back(window->GetID(str_id));
  7958. }
  7959. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  7960. {
  7961. ImGuiWindow* window = GetCurrentWindowRead();
  7962. window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
  7963. }
  7964. void ImGui::PushID(const void* ptr_id)
  7965. {
  7966. ImGuiWindow* window = GetCurrentWindowRead();
  7967. window->IDStack.push_back(window->GetID(ptr_id));
  7968. }
  7969. void ImGui::PushID(int int_id)
  7970. {
  7971. const void* ptr_id = (void*)(intptr_t)int_id;
  7972. ImGuiWindow* window = GetCurrentWindowRead();
  7973. window->IDStack.push_back(window->GetID(ptr_id));
  7974. }
  7975. void ImGui::PopID()
  7976. {
  7977. ImGuiWindow* window = GetCurrentWindowRead();
  7978. window->IDStack.pop_back();
  7979. }
  7980. ImGuiID ImGui::GetID(const char* str_id)
  7981. {
  7982. return GImGui->CurrentWindow->GetID(str_id);
  7983. }
  7984. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  7985. {
  7986. return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
  7987. }
  7988. ImGuiID ImGui::GetID(const void* ptr_id)
  7989. {
  7990. return GImGui->CurrentWindow->GetID(ptr_id);
  7991. }
  7992. void ImGui::Bullet()
  7993. {
  7994. ImGuiWindow* window = GetCurrentWindow();
  7995. if (window->SkipItems)
  7996. return;
  7997. ImGuiContext& g = *GImGui;
  7998. const ImGuiStyle& style = g.Style;
  7999. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  8000. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
  8001. ItemSize(bb);
  8002. if (!ItemAdd(bb, 0))
  8003. {
  8004. SameLine(0, style.FramePadding.x*2);
  8005. return;
  8006. }
  8007. // Render and stay on same line
  8008. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  8009. SameLine(0, style.FramePadding.x*2);
  8010. }
  8011. // Text with a little bullet aligned to the typical tree node.
  8012. void ImGui::BulletTextV(const char* fmt, va_list args)
  8013. {
  8014. ImGuiWindow* window = GetCurrentWindow();
  8015. if (window->SkipItems)
  8016. return;
  8017. ImGuiContext& g = *GImGui;
  8018. const ImGuiStyle& style = g.Style;
  8019. const char* text_begin = g.TempBuffer;
  8020. const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  8021. const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
  8022. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
  8023. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  8024. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding
  8025. ItemSize(bb);
  8026. if (!ItemAdd(bb, 0))
  8027. return;
  8028. // Render
  8029. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  8030. RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false);
  8031. }
  8032. void ImGui::BulletText(const char* fmt, ...)
  8033. {
  8034. va_list args;
  8035. va_start(args, fmt);
  8036. BulletTextV(fmt, args);
  8037. va_end(args);
  8038. }
  8039. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
  8040. {
  8041. if (data_type == ImGuiDataType_Int)
  8042. ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
  8043. else if (data_type == ImGuiDataType_Float)
  8044. ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
  8045. }
  8046. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
  8047. {
  8048. if (data_type == ImGuiDataType_Int)
  8049. {
  8050. if (decimal_precision < 0)
  8051. ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
  8052. else
  8053. ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
  8054. }
  8055. else if (data_type == ImGuiDataType_Float)
  8056. {
  8057. if (decimal_precision < 0)
  8058. ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits?
  8059. else
  8060. ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
  8061. }
  8062. }
  8063. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
  8064. {
  8065. if (data_type == ImGuiDataType_Int)
  8066. {
  8067. if (op == '+')
  8068. *(int*)value1 = *(int*)value1 + *(const int*)value2;
  8069. else if (op == '-')
  8070. *(int*)value1 = *(int*)value1 - *(const int*)value2;
  8071. }
  8072. else if (data_type == ImGuiDataType_Float)
  8073. {
  8074. if (op == '+')
  8075. *(float*)value1 = *(float*)value1 + *(const float*)value2;
  8076. else if (op == '-')
  8077. *(float*)value1 = *(float*)value1 - *(const float*)value2;
  8078. }
  8079. }
  8080. // User can input math operators (e.g. +100) to edit a numerical values.
  8081. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
  8082. {
  8083. while (ImCharIsSpace(*buf))
  8084. buf++;
  8085. // We don't support '-' op because it would conflict with inputing negative value.
  8086. // Instead you can use +-100 to subtract from an existing value
  8087. char op = buf[0];
  8088. if (op == '+' || op == '*' || op == '/')
  8089. {
  8090. buf++;
  8091. while (ImCharIsSpace(*buf))
  8092. buf++;
  8093. }
  8094. else
  8095. {
  8096. op = 0;
  8097. }
  8098. if (!buf[0])
  8099. return false;
  8100. if (data_type == ImGuiDataType_Int)
  8101. {
  8102. if (!scalar_format)
  8103. scalar_format = "%d";
  8104. int* v = (int*)data_ptr;
  8105. const int old_v = *v;
  8106. int arg0i = *v;
  8107. if (op && sscanf(initial_value_buf, scalar_format, &arg0i) < 1)
  8108. return false;
  8109. // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
  8110. float arg1f = 0.0f;
  8111. if (op == '+') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i + arg1f); } // Add (use "+-" to subtract)
  8112. else if (op == '*') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i * arg1f); } // Multiply
  8113. else if (op == '/') { if (sscanf(buf, "%f", &arg1f) == 1 && arg1f != 0.0f) *v = (int)(arg0i / arg1f); }// Divide
  8114. else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign constant (read as integer so big values are not lossy)
  8115. return (old_v != *v);
  8116. }
  8117. else if (data_type == ImGuiDataType_Float)
  8118. {
  8119. // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
  8120. scalar_format = "%f";
  8121. float* v = (float*)data_ptr;
  8122. const float old_v = *v;
  8123. float arg0f = *v;
  8124. if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
  8125. return false;
  8126. float arg1f = 0.0f;
  8127. if (sscanf(buf, scalar_format, &arg1f) < 1)
  8128. return false;
  8129. if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
  8130. else if (op == '*') { *v = arg0f * arg1f; } // Multiply
  8131. else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
  8132. else { *v = arg1f; } // Assign constant
  8133. return (old_v != *v);
  8134. }
  8135. return false;
  8136. }
  8137. // Create text input in place of a slider (when CTRL+Clicking on slider)
  8138. // FIXME: Logic is messy and confusing.
  8139. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
  8140. {
  8141. ImGuiContext& g = *GImGui;
  8142. ImGuiWindow* window = GetCurrentWindow();
  8143. // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
  8144. // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id
  8145. SetActiveID(g.ScalarAsInputTextId, window);
  8146. g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
  8147. SetHoveredID(0);
  8148. FocusableItemUnregister(window);
  8149. char buf[32];
  8150. DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
  8151. bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
  8152. if (g.ScalarAsInputTextId == 0) // First frame we started displaying the InputText widget
  8153. {
  8154. IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible)
  8155. g.ScalarAsInputTextId = g.ActiveId;
  8156. SetHoveredID(id);
  8157. }
  8158. if (text_value_changed)
  8159. return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
  8160. return false;
  8161. }
  8162. // Parse display precision back from the display format string
  8163. int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
  8164. {
  8165. int precision = default_precision;
  8166. while ((fmt = strchr(fmt, '%')) != NULL)
  8167. {
  8168. fmt++;
  8169. if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
  8170. while (*fmt >= '0' && *fmt <= '9')
  8171. fmt++;
  8172. if (*fmt == '.')
  8173. {
  8174. fmt = ImAtoi(fmt + 1, &precision);
  8175. if (precision < 0 || precision > 10)
  8176. precision = default_precision;
  8177. }
  8178. if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
  8179. precision = -1;
  8180. break;
  8181. }
  8182. return precision;
  8183. }
  8184. static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
  8185. {
  8186. static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
  8187. return (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
  8188. }
  8189. float ImGui::RoundScalar(float value, int decimal_precision)
  8190. {
  8191. // Round past decimal precision
  8192. // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
  8193. // FIXME: Investigate better rounding methods
  8194. if (decimal_precision < 0)
  8195. return value;
  8196. const float min_step = GetMinimumStepAtDecimalPrecision(decimal_precision);
  8197. bool negative = value < 0.0f;
  8198. value = fabsf(value);
  8199. float remainder = fmodf(value, min_step);
  8200. if (remainder <= min_step*0.5f)
  8201. value -= remainder;
  8202. else
  8203. value += (min_step - remainder);
  8204. return negative ? -value : value;
  8205. }
  8206. static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos)
  8207. {
  8208. if (v_min == v_max)
  8209. return 0.0f;
  8210. const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
  8211. const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
  8212. if (is_non_linear)
  8213. {
  8214. if (v_clamped < 0.0f)
  8215. {
  8216. const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min);
  8217. return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos;
  8218. }
  8219. else
  8220. {
  8221. const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min));
  8222. return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos);
  8223. }
  8224. }
  8225. // Linear slider
  8226. return (v_clamped - v_min) / (v_max - v_min);
  8227. }
  8228. bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
  8229. {
  8230. ImGuiContext& g = *GImGui;
  8231. ImGuiWindow* window = GetCurrentWindow();
  8232. const ImGuiStyle& style = g.Style;
  8233. // Draw frame
  8234. const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
  8235. RenderNavHighlight(frame_bb, id);
  8236. RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
  8237. const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
  8238. const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
  8239. const float grab_padding = 2.0f;
  8240. const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
  8241. float grab_sz;
  8242. if (decimal_precision != 0)
  8243. grab_sz = ImMin(style.GrabMinSize, slider_sz);
  8244. else
  8245. grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
  8246. const float slider_usable_sz = slider_sz - grab_sz;
  8247. const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
  8248. const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
  8249. // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
  8250. float linear_zero_pos = 0.0f; // 0.0->1.0f
  8251. if (v_min * v_max < 0.0f)
  8252. {
  8253. // Different sign
  8254. const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power);
  8255. const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power);
  8256. linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0);
  8257. }
  8258. else
  8259. {
  8260. // Same sign
  8261. linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
  8262. }
  8263. // Process interacting with the slider
  8264. bool value_changed = false;
  8265. if (g.ActiveId == id)
  8266. {
  8267. bool set_new_value = false;
  8268. float clicked_t = 0.0f;
  8269. if (g.ActiveIdSource == ImGuiInputSource_Mouse)
  8270. {
  8271. if (!g.IO.MouseDown[0])
  8272. {
  8273. ClearActiveID();
  8274. }
  8275. else
  8276. {
  8277. const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  8278. clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
  8279. if (!is_horizontal)
  8280. clicked_t = 1.0f - clicked_t;
  8281. set_new_value = true;
  8282. }
  8283. }
  8284. else if (g.ActiveIdSource == ImGuiInputSource_Nav)
  8285. {
  8286. const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f);
  8287. float delta = is_horizontal ? delta2.x : -delta2.y;
  8288. if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
  8289. {
  8290. ClearActiveID();
  8291. }
  8292. else if (delta != 0.0f)
  8293. {
  8294. clicked_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
  8295. if (decimal_precision == 0 && !is_non_linear)
  8296. {
  8297. if (fabsf(v_max - v_min) <= 100.0f || IsNavInputDown(ImGuiNavInput_TweakSlow))
  8298. delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (v_max - v_min); // Gamepad/keyboard tweak speeds in integer steps
  8299. else
  8300. delta /= 100.0f;
  8301. }
  8302. else
  8303. {
  8304. delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds
  8305. if (IsNavInputDown(ImGuiNavInput_TweakSlow))
  8306. delta /= 10.0f;
  8307. }
  8308. if (IsNavInputDown(ImGuiNavInput_TweakFast))
  8309. delta *= 10.0f;
  8310. set_new_value = true;
  8311. if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits
  8312. set_new_value = false;
  8313. else
  8314. clicked_t = ImSaturate(clicked_t + delta);
  8315. }
  8316. }
  8317. if (set_new_value)
  8318. {
  8319. float new_value;
  8320. if (is_non_linear)
  8321. {
  8322. // Account for logarithmic scale on both sides of the zero
  8323. if (clicked_t < linear_zero_pos)
  8324. {
  8325. // Negative: rescale to the negative range before powering
  8326. float a = 1.0f - (clicked_t / linear_zero_pos);
  8327. a = powf(a, power);
  8328. new_value = ImLerp(ImMin(v_max,0.0f), v_min, a);
  8329. }
  8330. else
  8331. {
  8332. // Positive: rescale to the positive range before powering
  8333. float a;
  8334. if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f)
  8335. a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
  8336. else
  8337. a = clicked_t;
  8338. a = powf(a, power);
  8339. new_value = ImLerp(ImMax(v_min,0.0f), v_max, a);
  8340. }
  8341. }
  8342. else
  8343. {
  8344. // Linear slider
  8345. new_value = ImLerp(v_min, v_max, clicked_t);
  8346. }
  8347. // Round past decimal precision
  8348. new_value = RoundScalar(new_value, decimal_precision);
  8349. if (*v != new_value)
  8350. {
  8351. *v = new_value;
  8352. value_changed = true;
  8353. }
  8354. }
  8355. }
  8356. // Draw
  8357. float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
  8358. if (!is_horizontal)
  8359. grab_t = 1.0f - grab_t;
  8360. const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
  8361. ImRect grab_bb;
  8362. if (is_horizontal)
  8363. grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding));
  8364. else
  8365. grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f));
  8366. window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
  8367. return value_changed;
  8368. }
  8369. // Use power!=1.0 for logarithmic sliders.
  8370. // Adjust display_format to decorate the value with a prefix or a suffix.
  8371. // "%.3f" 1.234
  8372. // "%5.2f secs" 01.23 secs
  8373. // "Gold: %.0f" Gold: 1
  8374. bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
  8375. {
  8376. ImGuiWindow* window = GetCurrentWindow();
  8377. if (window->SkipItems)
  8378. return false;
  8379. ImGuiContext& g = *GImGui;
  8380. const ImGuiStyle& style = g.Style;
  8381. const ImGuiID id = window->GetID(label);
  8382. const float w = CalcItemWidth();
  8383. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8384. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  8385. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  8386. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  8387. if (!ItemAdd(total_bb, id, &frame_bb))
  8388. {
  8389. ItemSize(total_bb, style.FramePadding.y);
  8390. return false;
  8391. }
  8392. const bool hovered = ItemHoverable(frame_bb, id);
  8393. if (!display_format)
  8394. display_format = "%.3f";
  8395. int decimal_precision = ParseFormatPrecision(display_format, 3);
  8396. // Tabbing or CTRL-clicking on Slider turns it into an input box
  8397. bool start_text_input = false;
  8398. const bool tab_focus_requested = FocusableItemRegister(window, id);
  8399. if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
  8400. {
  8401. SetActiveID(id, window);
  8402. SetFocusID(id, window);
  8403. FocusWindow(window);
  8404. g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
  8405. if (tab_focus_requested || g.IO.KeyCtrl || g.NavInputId == id)
  8406. {
  8407. start_text_input = true;
  8408. g.ScalarAsInputTextId = 0;
  8409. }
  8410. }
  8411. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  8412. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  8413. // Actual slider behavior + render grab
  8414. ItemSize(total_bb, style.FramePadding.y);
  8415. const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
  8416. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  8417. char value_buf[64];
  8418. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  8419. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
  8420. if (label_size.x > 0.0f)
  8421. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8422. return value_changed;
  8423. }
  8424. bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power)
  8425. {
  8426. ImGuiWindow* window = GetCurrentWindow();
  8427. if (window->SkipItems)
  8428. return false;
  8429. ImGuiContext& g = *GImGui;
  8430. const ImGuiStyle& style = g.Style;
  8431. const ImGuiID id = window->GetID(label);
  8432. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8433. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  8434. const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  8435. ItemSize(bb, style.FramePadding.y);
  8436. if (!ItemAdd(frame_bb, id))
  8437. return false;
  8438. const bool hovered = ItemHoverable(frame_bb, id);
  8439. if (!display_format)
  8440. display_format = "%.3f";
  8441. int decimal_precision = ParseFormatPrecision(display_format, 3);
  8442. if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id)
  8443. {
  8444. SetActiveID(id, window);
  8445. SetFocusID(id, window);
  8446. FocusWindow(window);
  8447. g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
  8448. }
  8449. // Actual slider behavior + render grab
  8450. bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
  8451. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  8452. // For the vertical slider we allow centered text to overlap the frame padding
  8453. char value_buf[64];
  8454. char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  8455. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f));
  8456. if (label_size.x > 0.0f)
  8457. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8458. return value_changed;
  8459. }
  8460. bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
  8461. {
  8462. float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
  8463. bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f);
  8464. *v_rad = v_deg * (2*IM_PI) / 360.0f;
  8465. return value_changed;
  8466. }
  8467. bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format)
  8468. {
  8469. if (!display_format)
  8470. display_format = "%.0f";
  8471. float v_f = (float)*v;
  8472. bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  8473. *v = (int)v_f;
  8474. return value_changed;
  8475. }
  8476. bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
  8477. {
  8478. if (!display_format)
  8479. display_format = "%.0f";
  8480. float v_f = (float)*v;
  8481. bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  8482. *v = (int)v_f;
  8483. return value_changed;
  8484. }
  8485. // Add multiple sliders on 1 line for compact edition of multiple components
  8486. bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
  8487. {
  8488. ImGuiWindow* window = GetCurrentWindow();
  8489. if (window->SkipItems)
  8490. return false;
  8491. ImGuiContext& g = *GImGui;
  8492. bool value_changed = false;
  8493. BeginGroup();
  8494. PushID(label);
  8495. PushMultiItemsWidths(components);
  8496. for (int i = 0; i < components; i++)
  8497. {
  8498. PushID(i);
  8499. value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
  8500. SameLine(0, g.Style.ItemInnerSpacing.x);
  8501. PopID();
  8502. PopItemWidth();
  8503. }
  8504. PopID();
  8505. TextUnformatted(label, FindRenderedTextEnd(label));
  8506. EndGroup();
  8507. return value_changed;
  8508. }
  8509. bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
  8510. {
  8511. return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
  8512. }
  8513. bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
  8514. {
  8515. return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
  8516. }
  8517. bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
  8518. {
  8519. return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
  8520. }
  8521. bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
  8522. {
  8523. ImGuiWindow* window = GetCurrentWindow();
  8524. if (window->SkipItems)
  8525. return false;
  8526. ImGuiContext& g = *GImGui;
  8527. bool value_changed = false;
  8528. BeginGroup();
  8529. PushID(label);
  8530. PushMultiItemsWidths(components);
  8531. for (int i = 0; i < components; i++)
  8532. {
  8533. PushID(i);
  8534. value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format);
  8535. SameLine(0, g.Style.ItemInnerSpacing.x);
  8536. PopID();
  8537. PopItemWidth();
  8538. }
  8539. PopID();
  8540. TextUnformatted(label, FindRenderedTextEnd(label));
  8541. EndGroup();
  8542. return value_changed;
  8543. }
  8544. bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
  8545. {
  8546. return SliderIntN(label, v, 2, v_min, v_max, display_format);
  8547. }
  8548. bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
  8549. {
  8550. return SliderIntN(label, v, 3, v_min, v_max, display_format);
  8551. }
  8552. bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
  8553. {
  8554. return SliderIntN(label, v, 4, v_min, v_max, display_format);
  8555. }
  8556. bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power)
  8557. {
  8558. ImGuiContext& g = *GImGui;
  8559. const ImGuiStyle& style = g.Style;
  8560. // Draw frame
  8561. const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
  8562. RenderNavHighlight(frame_bb, id);
  8563. RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
  8564. bool value_changed = false;
  8565. // Process interacting with the drag
  8566. if (g.ActiveId == id)
  8567. {
  8568. if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
  8569. ClearActiveID();
  8570. else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
  8571. ClearActiveID();
  8572. }
  8573. if (g.ActiveId == id)
  8574. {
  8575. if (g.ActiveIdIsJustActivated)
  8576. {
  8577. // Lock current value on click
  8578. g.DragCurrentValue = *v;
  8579. g.DragLastMouseDelta = ImVec2(0.f, 0.f);
  8580. }
  8581. if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
  8582. v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
  8583. float v_cur = g.DragCurrentValue;
  8584. const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
  8585. float adjust_delta = 0.0f;
  8586. if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid())
  8587. {
  8588. adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x;
  8589. if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
  8590. adjust_delta *= g.DragSpeedScaleFast;
  8591. if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
  8592. adjust_delta *= g.DragSpeedScaleSlow;
  8593. g.DragLastMouseDelta.x = mouse_drag_delta.x;
  8594. }
  8595. if (g.ActiveIdSource == ImGuiInputSource_Nav)
  8596. {
  8597. adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard|ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f/10.0f, 10.0f).x;
  8598. if (v_min < v_max && ((v_cur >= v_max && adjust_delta > 0.0f) || (v_cur <= v_min && adjust_delta < 0.0f))) // This is to avoid applying the saturation when already past the limits
  8599. adjust_delta = 0.0f;
  8600. v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
  8601. }
  8602. adjust_delta *= v_speed;
  8603. if (fabsf(adjust_delta) > 0.0f)
  8604. {
  8605. if (fabsf(power - 1.0f) > 0.001f)
  8606. {
  8607. // Logarithmic curve on both side of 0.0
  8608. float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
  8609. float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
  8610. float v1 = powf(v0_abs, 1.0f / power) + (adjust_delta * v0_sign);
  8611. float v1_abs = v1 >= 0.0f ? v1 : -v1;
  8612. float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
  8613. v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
  8614. }
  8615. else
  8616. {
  8617. v_cur += adjust_delta;
  8618. }
  8619. // Clamp
  8620. if (v_min < v_max)
  8621. v_cur = ImClamp(v_cur, v_min, v_max);
  8622. g.DragCurrentValue = v_cur;
  8623. }
  8624. // Round to user desired precision, then apply
  8625. v_cur = RoundScalar(v_cur, decimal_precision);
  8626. if (*v != v_cur)
  8627. {
  8628. *v = v_cur;
  8629. value_changed = true;
  8630. }
  8631. }
  8632. return value_changed;
  8633. }
  8634. bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
  8635. {
  8636. ImGuiWindow* window = GetCurrentWindow();
  8637. if (window->SkipItems)
  8638. return false;
  8639. ImGuiContext& g = *GImGui;
  8640. const ImGuiStyle& style = g.Style;
  8641. const ImGuiID id = window->GetID(label);
  8642. const float w = CalcItemWidth();
  8643. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8644. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  8645. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  8646. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  8647. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  8648. if (!ItemAdd(total_bb, id, &frame_bb))
  8649. {
  8650. ItemSize(total_bb, style.FramePadding.y);
  8651. return false;
  8652. }
  8653. const bool hovered = ItemHoverable(frame_bb, id);
  8654. if (!display_format)
  8655. display_format = "%.3f";
  8656. int decimal_precision = ParseFormatPrecision(display_format, 3);
  8657. // Tabbing or CTRL-clicking on Drag turns it into an input box
  8658. bool start_text_input = false;
  8659. const bool tab_focus_requested = FocusableItemRegister(window, id);
  8660. if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
  8661. {
  8662. SetActiveID(id, window);
  8663. SetFocusID(id, window);
  8664. FocusWindow(window);
  8665. g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
  8666. if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id)
  8667. {
  8668. start_text_input = true;
  8669. g.ScalarAsInputTextId = 0;
  8670. }
  8671. }
  8672. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  8673. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  8674. // Actual drag behavior
  8675. ItemSize(total_bb, style.FramePadding.y);
  8676. const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
  8677. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  8678. char value_buf[64];
  8679. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  8680. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
  8681. if (label_size.x > 0.0f)
  8682. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  8683. return value_changed;
  8684. }
  8685. bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power)
  8686. {
  8687. ImGuiWindow* window = GetCurrentWindow();
  8688. if (window->SkipItems)
  8689. return false;
  8690. ImGuiContext& g = *GImGui;
  8691. bool value_changed = false;
  8692. BeginGroup();
  8693. PushID(label);
  8694. PushMultiItemsWidths(components);
  8695. for (int i = 0; i < components; i++)
  8696. {
  8697. PushID(i);
  8698. value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
  8699. SameLine(0, g.Style.ItemInnerSpacing.x);
  8700. PopID();
  8701. PopItemWidth();
  8702. }
  8703. PopID();
  8704. TextUnformatted(label, FindRenderedTextEnd(label));
  8705. EndGroup();
  8706. return value_changed;
  8707. }
  8708. bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
  8709. {
  8710. return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
  8711. }
  8712. bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
  8713. {
  8714. return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
  8715. }
  8716. bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
  8717. {
  8718. return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power);
  8719. }
  8720. bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power)
  8721. {
  8722. ImGuiWindow* window = GetCurrentWindow();
  8723. if (window->SkipItems)
  8724. return false;
  8725. ImGuiContext& g = *GImGui;
  8726. PushID(label);
  8727. BeginGroup();
  8728. PushMultiItemsWidths(2);
  8729. bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power);
  8730. PopItemWidth();
  8731. SameLine(0, g.Style.ItemInnerSpacing.x);
  8732. value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power);
  8733. PopItemWidth();
  8734. SameLine(0, g.Style.ItemInnerSpacing.x);
  8735. TextUnformatted(label, FindRenderedTextEnd(label));
  8736. EndGroup();
  8737. PopID();
  8738. return value_changed;
  8739. }
  8740. // NB: v_speed is float to allow adjusting the drag speed with more precision
  8741. bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
  8742. {
  8743. if (!display_format)
  8744. display_format = "%.0f";
  8745. float v_f = (float)*v;
  8746. bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
  8747. *v = (int)v_f;
  8748. return value_changed;
  8749. }
  8750. bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
  8751. {
  8752. ImGuiWindow* window = GetCurrentWindow();
  8753. if (window->SkipItems)
  8754. return false;
  8755. ImGuiContext& g = *GImGui;
  8756. bool value_changed = false;
  8757. BeginGroup();
  8758. PushID(label);
  8759. PushMultiItemsWidths(components);
  8760. for (int i = 0; i < components; i++)
  8761. {
  8762. PushID(i);
  8763. value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
  8764. SameLine(0, g.Style.ItemInnerSpacing.x);
  8765. PopID();
  8766. PopItemWidth();
  8767. }
  8768. PopID();
  8769. TextUnformatted(label, FindRenderedTextEnd(label));
  8770. EndGroup();
  8771. return value_changed;
  8772. }
  8773. bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
  8774. {
  8775. return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
  8776. }
  8777. bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
  8778. {
  8779. return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
  8780. }
  8781. bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
  8782. {
  8783. return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format);
  8784. }
  8785. bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max)
  8786. {
  8787. ImGuiWindow* window = GetCurrentWindow();
  8788. if (window->SkipItems)
  8789. return false;
  8790. ImGuiContext& g = *GImGui;
  8791. PushID(label);
  8792. BeginGroup();
  8793. PushMultiItemsWidths(2);
  8794. bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format);
  8795. PopItemWidth();
  8796. SameLine(0, g.Style.ItemInnerSpacing.x);
  8797. value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format);
  8798. PopItemWidth();
  8799. SameLine(0, g.Style.ItemInnerSpacing.x);
  8800. TextUnformatted(label, FindRenderedTextEnd(label));
  8801. EndGroup();
  8802. PopID();
  8803. return value_changed;
  8804. }
  8805. void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  8806. {
  8807. ImGuiWindow* window = GetCurrentWindow();
  8808. if (window->SkipItems)
  8809. return;
  8810. ImGuiContext& g = *GImGui;
  8811. const ImGuiStyle& style = g.Style;
  8812. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8813. if (graph_size.x == 0.0f)
  8814. graph_size.x = CalcItemWidth();
  8815. if (graph_size.y == 0.0f)
  8816. graph_size.y = label_size.y + (style.FramePadding.y * 2);
  8817. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y));
  8818. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  8819. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
  8820. ItemSize(total_bb, style.FramePadding.y);
  8821. if (!ItemAdd(total_bb, 0, &frame_bb))
  8822. return;
  8823. const bool hovered = ItemHoverable(inner_bb, 0);
  8824. // Determine scale from values if not specified
  8825. if (scale_min == FLT_MAX || scale_max == FLT_MAX)
  8826. {
  8827. float v_min = FLT_MAX;
  8828. float v_max = -FLT_MAX;
  8829. for (int i = 0; i < values_count; i++)
  8830. {
  8831. const float v = values_getter(data, i);
  8832. v_min = ImMin(v_min, v);
  8833. v_max = ImMax(v_max, v);
  8834. }
  8835. if (scale_min == FLT_MAX)
  8836. scale_min = v_min;
  8837. if (scale_max == FLT_MAX)
  8838. scale_max = v_max;
  8839. }
  8840. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  8841. if (values_count > 0)
  8842. {
  8843. int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  8844. int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  8845. // Tooltip on hover
  8846. int v_hovered = -1;
  8847. if (hovered)
  8848. {
  8849. const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
  8850. const int v_idx = (int)(t * item_count);
  8851. IM_ASSERT(v_idx >= 0 && v_idx < values_count);
  8852. const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
  8853. const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
  8854. if (plot_type == ImGuiPlotType_Lines)
  8855. SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
  8856. else if (plot_type == ImGuiPlotType_Histogram)
  8857. SetTooltip("%d: %8.4g", v_idx, v0);
  8858. v_hovered = v_idx;
  8859. }
  8860. const float t_step = 1.0f / (float)res_w;
  8861. const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
  8862. float v0 = values_getter(data, (0 + values_offset) % values_count);
  8863. float t0 = 0.0f;
  8864. ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
  8865. float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
  8866. const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
  8867. const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
  8868. for (int n = 0; n < res_w; n++)
  8869. {
  8870. const float t1 = t0 + t_step;
  8871. const int v1_idx = (int)(t0 * item_count + 0.5f);
  8872. IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
  8873. const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
  8874. const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
  8875. // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
  8876. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
  8877. ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
  8878. if (plot_type == ImGuiPlotType_Lines)
  8879. {
  8880. window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  8881. }
  8882. else if (plot_type == ImGuiPlotType_Histogram)
  8883. {
  8884. if (pos1.x >= pos0.x + 2.0f)
  8885. pos1.x -= 1.0f;
  8886. window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  8887. }
  8888. t0 = t1;
  8889. tp0 = tp1;
  8890. }
  8891. }
  8892. // Text overlay
  8893. if (overlay_text)
  8894. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f));
  8895. if (label_size.x > 0.0f)
  8896. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  8897. }
  8898. struct ImGuiPlotArrayGetterData
  8899. {
  8900. const float* Values;
  8901. int Stride;
  8902. ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
  8903. };
  8904. static float Plot_ArrayGetter(void* data, int idx)
  8905. {
  8906. ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
  8907. const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
  8908. return v;
  8909. }
  8910. void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
  8911. {
  8912. ImGuiPlotArrayGetterData data(values, stride);
  8913. PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  8914. }
  8915. void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  8916. {
  8917. PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  8918. }
  8919. void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
  8920. {
  8921. ImGuiPlotArrayGetterData data(values, stride);
  8922. PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  8923. }
  8924. void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  8925. {
  8926. PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  8927. }
  8928. // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
  8929. void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
  8930. {
  8931. ImGuiWindow* window = GetCurrentWindow();
  8932. if (window->SkipItems)
  8933. return;
  8934. ImGuiContext& g = *GImGui;
  8935. const ImGuiStyle& style = g.Style;
  8936. ImVec2 pos = window->DC.CursorPos;
  8937. ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
  8938. ItemSize(bb, style.FramePadding.y);
  8939. if (!ItemAdd(bb, 0))
  8940. return;
  8941. // Render
  8942. fraction = ImSaturate(fraction);
  8943. RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  8944. bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
  8945. const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
  8946. RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
  8947. // Default displaying the fraction as percentage string, but user can override it
  8948. char overlay_buf[32];
  8949. if (!overlay)
  8950. {
  8951. ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
  8952. overlay = overlay_buf;
  8953. }
  8954. ImVec2 overlay_size = CalcTextSize(overlay, NULL);
  8955. if (overlay_size.x > 0.0f)
  8956. RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb);
  8957. }
  8958. bool ImGui::Checkbox(const char* label, bool* v)
  8959. {
  8960. ImGuiWindow* window = GetCurrentWindow();
  8961. if (window->SkipItems)
  8962. return false;
  8963. ImGuiContext& g = *GImGui;
  8964. const ImGuiStyle& style = g.Style;
  8965. const ImGuiID id = window->GetID(label);
  8966. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8967. const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); // We want a square shape to we use Y twice
  8968. ItemSize(check_bb, style.FramePadding.y);
  8969. ImRect total_bb = check_bb;
  8970. if (label_size.x > 0)
  8971. SameLine(0, style.ItemInnerSpacing.x);
  8972. const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size);
  8973. if (label_size.x > 0)
  8974. {
  8975. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  8976. total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
  8977. }
  8978. if (!ItemAdd(total_bb, id))
  8979. return false;
  8980. bool hovered, held;
  8981. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  8982. if (pressed)
  8983. *v = !(*v);
  8984. RenderNavHighlight(total_bb, id);
  8985. RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
  8986. if (*v)
  8987. {
  8988. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  8989. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  8990. RenderCheckMark(check_bb.Min + ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad*2.0f);
  8991. }
  8992. if (g.LogEnabled)
  8993. LogRenderedText(&text_bb.Min, *v ? "[x]" : "[ ]");
  8994. if (label_size.x > 0.0f)
  8995. RenderText(text_bb.Min, label);
  8996. return pressed;
  8997. }
  8998. bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
  8999. {
  9000. bool v = ((*flags & flags_value) == flags_value);
  9001. bool pressed = Checkbox(label, &v);
  9002. if (pressed)
  9003. {
  9004. if (v)
  9005. *flags |= flags_value;
  9006. else
  9007. *flags &= ~flags_value;
  9008. }
  9009. return pressed;
  9010. }
  9011. bool ImGui::RadioButton(const char* label, bool active)
  9012. {
  9013. ImGuiWindow* window = GetCurrentWindow();
  9014. if (window->SkipItems)
  9015. return false;
  9016. ImGuiContext& g = *GImGui;
  9017. const ImGuiStyle& style = g.Style;
  9018. const ImGuiID id = window->GetID(label);
  9019. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  9020. const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1));
  9021. ItemSize(check_bb, style.FramePadding.y);
  9022. ImRect total_bb = check_bb;
  9023. if (label_size.x > 0)
  9024. SameLine(0, style.ItemInnerSpacing.x);
  9025. const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
  9026. if (label_size.x > 0)
  9027. {
  9028. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  9029. total_bb.Add(text_bb);
  9030. }
  9031. if (!ItemAdd(total_bb, id))
  9032. return false;
  9033. ImVec2 center = check_bb.GetCenter();
  9034. center.x = (float)(int)center.x + 0.5f;
  9035. center.y = (float)(int)center.y + 0.5f;
  9036. const float radius = check_bb.GetHeight() * 0.5f;
  9037. bool hovered, held;
  9038. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  9039. RenderNavHighlight(total_bb, id);
  9040. window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
  9041. if (active)
  9042. {
  9043. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  9044. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  9045. window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16);
  9046. }
  9047. if (style.FrameBorderSize > 0.0f)
  9048. {
  9049. window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
  9050. window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);
  9051. }
  9052. if (g.LogEnabled)
  9053. LogRenderedText(&text_bb.Min, active ? "(x)" : "( )");
  9054. if (label_size.x > 0.0f)
  9055. RenderText(text_bb.Min, label);
  9056. return pressed;
  9057. }
  9058. bool ImGui::RadioButton(const char* label, int* v, int v_button)
  9059. {
  9060. const bool pressed = RadioButton(label, *v == v_button);
  9061. if (pressed)
  9062. {
  9063. *v = v_button;
  9064. }
  9065. return pressed;
  9066. }
  9067. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
  9068. {
  9069. int line_count = 0;
  9070. const char* s = text_begin;
  9071. while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
  9072. if (c == '\n')
  9073. line_count++;
  9074. s--;
  9075. if (s[0] != '\n' && s[0] != '\r')
  9076. line_count++;
  9077. *out_text_end = s;
  9078. return line_count;
  9079. }
  9080. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
  9081. {
  9082. ImFont* font = GImGui->Font;
  9083. const float line_height = GImGui->FontSize;
  9084. const float scale = line_height / font->FontSize;
  9085. ImVec2 text_size = ImVec2(0,0);
  9086. float line_width = 0.0f;
  9087. const ImWchar* s = text_begin;
  9088. while (s < text_end)
  9089. {
  9090. unsigned int c = (unsigned int)(*s++);
  9091. if (c == '\n')
  9092. {
  9093. text_size.x = ImMax(text_size.x, line_width);
  9094. text_size.y += line_height;
  9095. line_width = 0.0f;
  9096. if (stop_on_new_line)
  9097. break;
  9098. continue;
  9099. }
  9100. if (c == '\r')
  9101. continue;
  9102. const float char_width = font->GetCharAdvance((unsigned short)c) * scale;
  9103. line_width += char_width;
  9104. }
  9105. if (text_size.x < line_width)
  9106. text_size.x = line_width;
  9107. if (out_offset)
  9108. *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
  9109. if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
  9110. text_size.y += line_height;
  9111. if (remaining)
  9112. *remaining = s;
  9113. return text_size;
  9114. }
  9115. // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
  9116. namespace ImGuiStb
  9117. {
  9118. static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
  9119. static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; }
  9120. static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); }
  9121. static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
  9122. static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
  9123. static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
  9124. {
  9125. const ImWchar* text = obj->Text.Data;
  9126. const ImWchar* text_remaining = NULL;
  9127. const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
  9128. r->x0 = 0.0f;
  9129. r->x1 = size.x;
  9130. r->baseline_y_delta = size.y;
  9131. r->ymin = 0.0f;
  9132. r->ymax = size.y;
  9133. r->num_chars = (int)(text_remaining - (text + line_start_idx));
  9134. }
  9135. static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
  9136. static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; }
  9137. static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
  9138. #ifdef __APPLE__ // FIXME: Move setting to IO structure
  9139. static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; }
  9140. static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
  9141. #else
  9142. static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
  9143. #endif
  9144. #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
  9145. #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
  9146. static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
  9147. {
  9148. ImWchar* dst = obj->Text.Data + pos;
  9149. // We maintain our buffer length in both UTF-8 and wchar formats
  9150. obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
  9151. obj->CurLenW -= n;
  9152. // Offset remaining text
  9153. const ImWchar* src = obj->Text.Data + pos + n;
  9154. while (ImWchar c = *src++)
  9155. *dst++ = c;
  9156. *dst = '\0';
  9157. }
  9158. static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
  9159. {
  9160. const int text_len = obj->CurLenW;
  9161. IM_ASSERT(pos <= text_len);
  9162. if (new_text_len + text_len + 1 > obj->Text.Size)
  9163. return false;
  9164. const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
  9165. if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
  9166. return false;
  9167. ImWchar* text = obj->Text.Data;
  9168. if (pos != text_len)
  9169. memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
  9170. memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
  9171. obj->CurLenW += new_text_len;
  9172. obj->CurLenA += new_text_len_utf8;
  9173. obj->Text[obj->CurLenW] = '\0';
  9174. return true;
  9175. }
  9176. // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
  9177. #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
  9178. #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
  9179. #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
  9180. #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
  9181. #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
  9182. #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
  9183. #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
  9184. #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
  9185. #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
  9186. #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
  9187. #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
  9188. #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
  9189. #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
  9190. #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
  9191. #define STB_TEXTEDIT_K_SHIFT 0x20000
  9192. #define STB_TEXTEDIT_IMPLEMENTATION
  9193. #include "stb_textedit.h"
  9194. }
  9195. void ImGuiTextEditState::OnKeyPressed(int key)
  9196. {
  9197. stb_textedit_key(this, &StbState, key);
  9198. CursorFollow = true;
  9199. CursorAnimReset();
  9200. }
  9201. // Public API to manipulate UTF-8 text
  9202. // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
  9203. // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
  9204. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count)
  9205. {
  9206. IM_ASSERT(pos + bytes_count <= BufTextLen);
  9207. char* dst = Buf + pos;
  9208. const char* src = Buf + pos + bytes_count;
  9209. while (char c = *src++)
  9210. *dst++ = c;
  9211. *dst = '\0';
  9212. if (CursorPos + bytes_count >= pos)
  9213. CursorPos -= bytes_count;
  9214. else if (CursorPos >= pos)
  9215. CursorPos = pos;
  9216. SelectionStart = SelectionEnd = CursorPos;
  9217. BufDirty = true;
  9218. BufTextLen -= bytes_count;
  9219. }
  9220. void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
  9221. {
  9222. const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
  9223. if (new_text_len + BufTextLen + 1 >= BufSize)
  9224. return;
  9225. if (BufTextLen != pos)
  9226. memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
  9227. memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
  9228. Buf[BufTextLen + new_text_len] = '\0';
  9229. if (CursorPos >= pos)
  9230. CursorPos += new_text_len;
  9231. SelectionStart = SelectionEnd = CursorPos;
  9232. BufDirty = true;
  9233. BufTextLen += new_text_len;
  9234. }
  9235. // Return false to discard a character.
  9236. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  9237. {
  9238. unsigned int c = *p_char;
  9239. if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
  9240. {
  9241. bool pass = false;
  9242. pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
  9243. pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
  9244. if (!pass)
  9245. return false;
  9246. }
  9247. if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys.
  9248. return false;
  9249. if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank))
  9250. {
  9251. if (flags & ImGuiInputTextFlags_CharsDecimal)
  9252. if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
  9253. return false;
  9254. if (flags & ImGuiInputTextFlags_CharsHexadecimal)
  9255. if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
  9256. return false;
  9257. if (flags & ImGuiInputTextFlags_CharsUppercase)
  9258. if (c >= 'a' && c <= 'z')
  9259. *p_char = (c += (unsigned int)('A'-'a'));
  9260. if (flags & ImGuiInputTextFlags_CharsNoBlank)
  9261. if (ImCharIsSpace(c))
  9262. return false;
  9263. }
  9264. if (flags & ImGuiInputTextFlags_CallbackCharFilter)
  9265. {
  9266. ImGuiTextEditCallbackData callback_data;
  9267. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  9268. callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
  9269. callback_data.EventChar = (ImWchar)c;
  9270. callback_data.Flags = flags;
  9271. callback_data.UserData = user_data;
  9272. if (callback(&callback_data) != 0)
  9273. return false;
  9274. *p_char = callback_data.EventChar;
  9275. if (!callback_data.EventChar)
  9276. return false;
  9277. }
  9278. return true;
  9279. }
  9280. // Edit a string of text
  9281. // NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect.
  9282. // FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188
  9283. bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  9284. {
  9285. ImGuiWindow* window = GetCurrentWindow();
  9286. if (window->SkipItems)
  9287. return false;
  9288. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
  9289. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
  9290. ImGuiContext& g = *GImGui;
  9291. const ImGuiIO& io = g.IO;
  9292. const ImGuiStyle& style = g.Style;
  9293. const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
  9294. const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
  9295. const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
  9296. const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
  9297. if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn
  9298. BeginGroup();
  9299. const ImGuiID id = window->GetID(label);
  9300. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  9301. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
  9302. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  9303. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f));
  9304. ImGuiWindow* draw_window = window;
  9305. if (is_multiline)
  9306. {
  9307. ItemAdd(total_bb, id, &frame_bb);
  9308. if (!BeginChildFrame(id, frame_bb.GetSize()))
  9309. {
  9310. EndChildFrame();
  9311. EndGroup();
  9312. return false;
  9313. }
  9314. draw_window = GetCurrentWindow();
  9315. size.x -= draw_window->ScrollbarSizes.x;
  9316. }
  9317. else
  9318. {
  9319. ItemSize(total_bb, style.FramePadding.y);
  9320. if (!ItemAdd(total_bb, id, &frame_bb))
  9321. return false;
  9322. }
  9323. const bool hovered = ItemHoverable(frame_bb, id);
  9324. if (hovered)
  9325. g.MouseCursor = ImGuiMouseCursor_TextInput;
  9326. // Password pushes a temporary font with only a fallback glyph
  9327. if (is_password)
  9328. {
  9329. const ImFontGlyph* glyph = g.Font->FindGlyph('*');
  9330. ImFont* password_font = &g.InputTextPasswordFont;
  9331. password_font->FontSize = g.Font->FontSize;
  9332. password_font->Scale = g.Font->Scale;
  9333. password_font->DisplayOffset = g.Font->DisplayOffset;
  9334. password_font->Ascent = g.Font->Ascent;
  9335. password_font->Descent = g.Font->Descent;
  9336. password_font->ContainerAtlas = g.Font->ContainerAtlas;
  9337. password_font->FallbackGlyph = glyph;
  9338. password_font->FallbackAdvanceX = glyph->AdvanceX;
  9339. IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
  9340. PushFont(password_font);
  9341. }
  9342. // NB: we are only allowed to access 'edit_state' if we are the active widget.
  9343. ImGuiTextEditState& edit_state = g.InputTextState;
  9344. const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
  9345. const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
  9346. const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
  9347. const bool user_clicked = hovered && io.MouseClicked[0];
  9348. const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
  9349. bool clear_active_id = false;
  9350. bool select_all = (g.ActiveId != id) && (((flags & ImGuiInputTextFlags_AutoSelectAll) != 0) || (g.NavInputId == id)) && (!is_multiline);
  9351. if (focus_requested || user_clicked || user_scrolled || g.NavInputId == id)
  9352. {
  9353. if (g.ActiveId != id)
  9354. {
  9355. // Start edition
  9356. // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
  9357. // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
  9358. const int prev_len_w = edit_state.CurLenW;
  9359. edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
  9360. edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
  9361. ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size);
  9362. const char* buf_end = NULL;
  9363. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  9364. edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
  9365. edit_state.CursorAnimReset();
  9366. // Preserve cursor position and undo/redo stack if we come back to same widget
  9367. // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar).
  9368. const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW);
  9369. if (recycle_state)
  9370. {
  9371. // Recycle existing cursor/selection/undo stack but clamp position
  9372. // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
  9373. edit_state.CursorClamp();
  9374. }
  9375. else
  9376. {
  9377. edit_state.Id = id;
  9378. edit_state.ScrollX = 0.0f;
  9379. stb_textedit_initialize_state(&edit_state.StbState, !is_multiline);
  9380. if (!is_multiline && focus_requested_by_code)
  9381. select_all = true;
  9382. }
  9383. if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
  9384. edit_state.StbState.insert_mode = true;
  9385. if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
  9386. select_all = true;
  9387. }
  9388. SetActiveID(id, window);
  9389. SetFocusID(id, window);
  9390. FocusWindow(window);
  9391. if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory))
  9392. g.ActiveIdAllowNavDirFlags |= ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down));
  9393. }
  9394. else if (io.MouseClicked[0])
  9395. {
  9396. // Release focus when we click outside
  9397. clear_active_id = true;
  9398. }
  9399. bool value_changed = false;
  9400. bool enter_pressed = false;
  9401. if (g.ActiveId == id)
  9402. {
  9403. if (!is_editable && !g.ActiveIdIsJustActivated)
  9404. {
  9405. // When read-only we always use the live data passed to the function
  9406. edit_state.Text.resize(buf_size+1);
  9407. const char* buf_end = NULL;
  9408. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  9409. edit_state.CurLenA = (int)(buf_end - buf);
  9410. edit_state.CursorClamp();
  9411. }
  9412. edit_state.BufSizeA = buf_size;
  9413. // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
  9414. // Down the line we should have a cleaner library-wide concept of Selected vs Active.
  9415. g.ActiveIdAllowOverlap = !io.MouseDown[0];
  9416. g.WantTextInputNextFrame = 1;
  9417. // Edit in progress
  9418. const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
  9419. const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
  9420. const bool osx_double_click_selects_words = io.OptMacOSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
  9421. if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0]))
  9422. {
  9423. edit_state.SelectAll();
  9424. edit_state.SelectedAllMouseLock = true;
  9425. }
  9426. else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0])
  9427. {
  9428. // Select a word only, OS X style (by simulating keystrokes)
  9429. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
  9430. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
  9431. }
  9432. else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
  9433. {
  9434. if (hovered)
  9435. {
  9436. stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  9437. edit_state.CursorAnimReset();
  9438. }
  9439. }
  9440. else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
  9441. {
  9442. stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  9443. edit_state.CursorAnimReset();
  9444. edit_state.CursorFollow = true;
  9445. }
  9446. if (edit_state.SelectedAllMouseLock && !io.MouseDown[0])
  9447. edit_state.SelectedAllMouseLock = false;
  9448. if (io.InputCharacters[0])
  9449. {
  9450. // Process text input (before we check for Return because using some IME will effectively send a Return?)
  9451. // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters.
  9452. if (!(io.KeyCtrl && !io.KeyAlt) && is_editable)
  9453. {
  9454. for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++)
  9455. if (unsigned int c = (unsigned int)io.InputCharacters[n])
  9456. {
  9457. // Insert character if they pass filtering
  9458. if (!InputTextFilterCharacter(&c, flags, callback, user_data))
  9459. continue;
  9460. edit_state.OnKeyPressed((int)c);
  9461. }
  9462. }
  9463. // Consume characters
  9464. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  9465. }
  9466. }
  9467. bool cancel_edit = false;
  9468. if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
  9469. {
  9470. // Handle key-presses
  9471. const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
  9472. const bool is_shortcut_key_only = (io.OptMacOSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
  9473. const bool is_wordmove_key_down = io.OptMacOSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
  9474. const bool is_startend_key_down = io.OptMacOSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
  9475. const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper;
  9476. const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
  9477. const bool is_cut = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection());
  9478. const bool is_copy = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection());
  9479. const bool is_paste = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable;
  9480. if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
  9481. else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
  9482. else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
  9483. else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
  9484. else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
  9485. else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
  9486. else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
  9487. else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable)
  9488. {
  9489. if (!edit_state.HasSelection())
  9490. {
  9491. if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
  9492. else if (io.OptMacOSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
  9493. }
  9494. edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
  9495. }
  9496. else if (IsKeyPressedMap(ImGuiKey_Enter))
  9497. {
  9498. bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
  9499. if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
  9500. {
  9501. enter_pressed = clear_active_id = true;
  9502. }
  9503. else if (is_editable)
  9504. {
  9505. unsigned int c = '\n'; // Insert new line
  9506. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  9507. edit_state.OnKeyPressed((int)c);
  9508. }
  9509. }
  9510. else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable)
  9511. {
  9512. unsigned int c = '\t'; // Insert TAB
  9513. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  9514. edit_state.OnKeyPressed((int)c);
  9515. }
  9516. else if (IsKeyPressedMap(ImGuiKey_Escape)) { clear_active_id = cancel_edit = true; }
  9517. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
  9518. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
  9519. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
  9520. else if (is_cut || is_copy)
  9521. {
  9522. // Cut, Copy
  9523. if (io.SetClipboardTextFn)
  9524. {
  9525. const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
  9526. const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW;
  9527. edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1);
  9528. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie);
  9529. SetClipboardText(edit_state.TempTextBuffer.Data);
  9530. }
  9531. if (is_cut)
  9532. {
  9533. if (!edit_state.HasSelection())
  9534. edit_state.SelectAll();
  9535. edit_state.CursorFollow = true;
  9536. stb_textedit_cut(&edit_state, &edit_state.StbState);
  9537. }
  9538. }
  9539. else if (is_paste)
  9540. {
  9541. // Paste
  9542. if (const char* clipboard = GetClipboardText())
  9543. {
  9544. // Filter pasted buffer
  9545. const int clipboard_len = (int)strlen(clipboard);
  9546. ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar));
  9547. int clipboard_filtered_len = 0;
  9548. for (const char* s = clipboard; *s; )
  9549. {
  9550. unsigned int c;
  9551. s += ImTextCharFromUtf8(&c, s, NULL);
  9552. if (c == 0)
  9553. break;
  9554. if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data))
  9555. continue;
  9556. clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
  9557. }
  9558. clipboard_filtered[clipboard_filtered_len] = 0;
  9559. if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
  9560. {
  9561. stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len);
  9562. edit_state.CursorFollow = true;
  9563. }
  9564. ImGui::MemFree(clipboard_filtered);
  9565. }
  9566. }
  9567. }
  9568. if (g.ActiveId == id)
  9569. {
  9570. if (cancel_edit)
  9571. {
  9572. // Restore initial value
  9573. if (is_editable)
  9574. {
  9575. ImStrncpy(buf, edit_state.InitialText.Data, buf_size);
  9576. value_changed = true;
  9577. }
  9578. }
  9579. // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
  9580. // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage.
  9581. bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
  9582. if (apply_edit_back_to_user_buffer)
  9583. {
  9584. // Apply new value immediately - copy modified buffer back
  9585. // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
  9586. // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
  9587. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
  9588. if (is_editable)
  9589. {
  9590. edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4);
  9591. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL);
  9592. }
  9593. // User callback
  9594. if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
  9595. {
  9596. IM_ASSERT(callback != NULL);
  9597. // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
  9598. ImGuiInputTextFlags event_flag = 0;
  9599. ImGuiKey event_key = ImGuiKey_COUNT;
  9600. if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
  9601. {
  9602. event_flag = ImGuiInputTextFlags_CallbackCompletion;
  9603. event_key = ImGuiKey_Tab;
  9604. }
  9605. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
  9606. {
  9607. event_flag = ImGuiInputTextFlags_CallbackHistory;
  9608. event_key = ImGuiKey_UpArrow;
  9609. }
  9610. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
  9611. {
  9612. event_flag = ImGuiInputTextFlags_CallbackHistory;
  9613. event_key = ImGuiKey_DownArrow;
  9614. }
  9615. else if (flags & ImGuiInputTextFlags_CallbackAlways)
  9616. event_flag = ImGuiInputTextFlags_CallbackAlways;
  9617. if (event_flag)
  9618. {
  9619. ImGuiTextEditCallbackData callback_data;
  9620. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  9621. callback_data.EventFlag = event_flag;
  9622. callback_data.Flags = flags;
  9623. callback_data.UserData = user_data;
  9624. callback_data.ReadOnly = !is_editable;
  9625. callback_data.EventKey = event_key;
  9626. callback_data.Buf = edit_state.TempTextBuffer.Data;
  9627. callback_data.BufTextLen = edit_state.CurLenA;
  9628. callback_data.BufSize = edit_state.BufSizeA;
  9629. callback_data.BufDirty = false;
  9630. // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
  9631. ImWchar* text = edit_state.Text.Data;
  9632. const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor);
  9633. const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start);
  9634. const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end);
  9635. // Call user code
  9636. callback(&callback_data);
  9637. // Read back what user may have modified
  9638. IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields
  9639. IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
  9640. IM_ASSERT(callback_data.Flags == flags);
  9641. if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos);
  9642. if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart);
  9643. if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd);
  9644. if (callback_data.BufDirty)
  9645. {
  9646. IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
  9647. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL);
  9648. edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
  9649. edit_state.CursorAnimReset();
  9650. }
  9651. }
  9652. }
  9653. // Copy back to user buffer
  9654. if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
  9655. {
  9656. ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size);
  9657. value_changed = true;
  9658. }
  9659. }
  9660. }
  9661. // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
  9662. if (clear_active_id && g.ActiveId == id)
  9663. ClearActiveID();
  9664. // Render
  9665. // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on.
  9666. const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
  9667. RenderNavHighlight(frame_bb, id);
  9668. if (!is_multiline)
  9669. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  9670. const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size
  9671. ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
  9672. ImVec2 text_size(0.f, 0.f);
  9673. const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY"));
  9674. if (g.ActiveId == id || is_currently_scrolling)
  9675. {
  9676. edit_state.CursorAnim += io.DeltaTime;
  9677. // This is going to be messy. We need to:
  9678. // - Display the text (this alone can be more easily clipped)
  9679. // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
  9680. // - Measure text height (for scrollbar)
  9681. // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
  9682. // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
  9683. const ImWchar* text_begin = edit_state.Text.Data;
  9684. ImVec2 cursor_offset, select_start_offset;
  9685. {
  9686. // Count lines + find lines numbers straddling 'cursor' and 'select_start' position.
  9687. const ImWchar* searches_input_ptr[2];
  9688. searches_input_ptr[0] = text_begin + edit_state.StbState.cursor;
  9689. searches_input_ptr[1] = NULL;
  9690. int searches_remaining = 1;
  9691. int searches_result_line_number[2] = { -1, -999 };
  9692. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  9693. {
  9694. searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  9695. searches_result_line_number[1] = -1;
  9696. searches_remaining++;
  9697. }
  9698. // Iterate all lines to find our line numbers
  9699. // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
  9700. searches_remaining += is_multiline ? 1 : 0;
  9701. int line_count = 0;
  9702. for (const ImWchar* s = text_begin; *s != 0; s++)
  9703. if (*s == '\n')
  9704. {
  9705. line_count++;
  9706. if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; }
  9707. if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; }
  9708. }
  9709. line_count++;
  9710. if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count;
  9711. if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count;
  9712. // Calculate 2d position by finding the beginning of the line and measuring distance
  9713. cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
  9714. cursor_offset.y = searches_result_line_number[0] * g.FontSize;
  9715. if (searches_result_line_number[1] >= 0)
  9716. {
  9717. select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
  9718. select_start_offset.y = searches_result_line_number[1] * g.FontSize;
  9719. }
  9720. // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
  9721. if (is_multiline)
  9722. text_size = ImVec2(size.x, line_count * g.FontSize);
  9723. }
  9724. // Scroll
  9725. if (edit_state.CursorFollow)
  9726. {
  9727. // Horizontal scroll in chunks of quarter width
  9728. if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
  9729. {
  9730. const float scroll_increment_x = size.x * 0.25f;
  9731. if (cursor_offset.x < edit_state.ScrollX)
  9732. edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
  9733. else if (cursor_offset.x - size.x >= edit_state.ScrollX)
  9734. edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
  9735. }
  9736. else
  9737. {
  9738. edit_state.ScrollX = 0.0f;
  9739. }
  9740. // Vertical scroll
  9741. if (is_multiline)
  9742. {
  9743. float scroll_y = draw_window->Scroll.y;
  9744. if (cursor_offset.y - g.FontSize < scroll_y)
  9745. scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
  9746. else if (cursor_offset.y - size.y >= scroll_y)
  9747. scroll_y = cursor_offset.y - size.y;
  9748. draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag
  9749. draw_window->Scroll.y = scroll_y;
  9750. render_pos.y = draw_window->DC.CursorPos.y;
  9751. }
  9752. }
  9753. edit_state.CursorFollow = false;
  9754. const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f);
  9755. // Draw selection
  9756. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  9757. {
  9758. const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  9759. const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end);
  9760. float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
  9761. float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
  9762. ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg);
  9763. ImVec2 rect_pos = render_pos + select_start_offset - render_scroll;
  9764. for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
  9765. {
  9766. if (rect_pos.y > clip_rect.w + g.FontSize)
  9767. break;
  9768. if (rect_pos.y < clip_rect.y)
  9769. {
  9770. while (p < text_selected_end)
  9771. if (*p++ == '\n')
  9772. break;
  9773. }
  9774. else
  9775. {
  9776. ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
  9777. if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines
  9778. ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
  9779. rect.ClipWith(clip_rect);
  9780. if (rect.Overlaps(clip_rect))
  9781. draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
  9782. }
  9783. rect_pos.x = render_pos.x - render_scroll.x;
  9784. rect_pos.y += g.FontSize;
  9785. }
  9786. }
  9787. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
  9788. // Draw blinking cursor
  9789. bool cursor_is_visible = (!g.IO.OptCursorBlink) || (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
  9790. ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll;
  9791. ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f);
  9792. if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
  9793. draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
  9794. // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
  9795. if (is_editable)
  9796. g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize);
  9797. }
  9798. else
  9799. {
  9800. // Render text only
  9801. const char* buf_end = NULL;
  9802. if (is_multiline)
  9803. text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width
  9804. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect);
  9805. }
  9806. if (is_multiline)
  9807. {
  9808. Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
  9809. EndChildFrame();
  9810. EndGroup();
  9811. }
  9812. if (is_password)
  9813. PopFont();
  9814. // Log as text
  9815. if (g.LogEnabled && !is_password)
  9816. LogRenderedText(&render_pos, buf_display, NULL);
  9817. if (label_size.x > 0)
  9818. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  9819. if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
  9820. return enter_pressed;
  9821. else
  9822. return value_changed;
  9823. }
  9824. bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  9825. {
  9826. IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
  9827. return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
  9828. }
  9829. bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  9830. {
  9831. return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
  9832. }
  9833. // NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
  9834. bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags)
  9835. {
  9836. ImGuiWindow* window = GetCurrentWindow();
  9837. if (window->SkipItems)
  9838. return false;
  9839. ImGuiContext& g = *GImGui;
  9840. const ImGuiStyle& style = g.Style;
  9841. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  9842. BeginGroup();
  9843. PushID(label);
  9844. const ImVec2 button_sz = ImVec2(GetFrameHeight(), GetFrameHeight());
  9845. if (step_ptr)
  9846. PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
  9847. char buf[64];
  9848. DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
  9849. bool value_changed = false;
  9850. if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
  9851. extra_flags |= ImGuiInputTextFlags_CharsDecimal;
  9852. extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
  9853. if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view
  9854. value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
  9855. // Step buttons
  9856. if (step_ptr)
  9857. {
  9858. PopItemWidth();
  9859. SameLine(0, style.ItemInnerSpacing.x);
  9860. if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  9861. {
  9862. DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  9863. value_changed = true;
  9864. }
  9865. SameLine(0, style.ItemInnerSpacing.x);
  9866. if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  9867. {
  9868. DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  9869. value_changed = true;
  9870. }
  9871. }
  9872. PopID();
  9873. if (label_size.x > 0)
  9874. {
  9875. SameLine(0, style.ItemInnerSpacing.x);
  9876. RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
  9877. ItemSize(label_size, style.FramePadding.y);
  9878. }
  9879. EndGroup();
  9880. return value_changed;
  9881. }
  9882. bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
  9883. {
  9884. char display_format[16];
  9885. if (decimal_precision < 0)
  9886. strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
  9887. else
  9888. ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision);
  9889. return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
  9890. }
  9891. bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags)
  9892. {
  9893. // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
  9894. const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
  9895. return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags);
  9896. }
  9897. bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
  9898. {
  9899. ImGuiWindow* window = GetCurrentWindow();
  9900. if (window->SkipItems)
  9901. return false;
  9902. ImGuiContext& g = *GImGui;
  9903. bool value_changed = false;
  9904. BeginGroup();
  9905. PushID(label);
  9906. PushMultiItemsWidths(components);
  9907. for (int i = 0; i < components; i++)
  9908. {
  9909. PushID(i);
  9910. value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
  9911. SameLine(0, g.Style.ItemInnerSpacing.x);
  9912. PopID();
  9913. PopItemWidth();
  9914. }
  9915. PopID();
  9916. TextUnformatted(label, FindRenderedTextEnd(label));
  9917. EndGroup();
  9918. return value_changed;
  9919. }
  9920. bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
  9921. {
  9922. return InputFloatN(label, v, 2, decimal_precision, extra_flags);
  9923. }
  9924. bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
  9925. {
  9926. return InputFloatN(label, v, 3, decimal_precision, extra_flags);
  9927. }
  9928. bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
  9929. {
  9930. return InputFloatN(label, v, 4, decimal_precision, extra_flags);
  9931. }
  9932. bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
  9933. {
  9934. ImGuiWindow* window = GetCurrentWindow();
  9935. if (window->SkipItems)
  9936. return false;
  9937. ImGuiContext& g = *GImGui;
  9938. bool value_changed = false;
  9939. BeginGroup();
  9940. PushID(label);
  9941. PushMultiItemsWidths(components);
  9942. for (int i = 0; i < components; i++)
  9943. {
  9944. PushID(i);
  9945. value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags);
  9946. SameLine(0, g.Style.ItemInnerSpacing.x);
  9947. PopID();
  9948. PopItemWidth();
  9949. }
  9950. PopID();
  9951. TextUnformatted(label, FindRenderedTextEnd(label));
  9952. EndGroup();
  9953. return value_changed;
  9954. }
  9955. bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
  9956. {
  9957. return InputIntN(label, v, 2, extra_flags);
  9958. }
  9959. bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
  9960. {
  9961. return InputIntN(label, v, 3, extra_flags);
  9962. }
  9963. bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
  9964. {
  9965. return InputIntN(label, v, 4, extra_flags);
  9966. }
  9967. static float CalcMaxPopupHeightFromItemCount(int items_count)
  9968. {
  9969. ImGuiContext& g = *GImGui;
  9970. if (items_count <= 0)
  9971. return FLT_MAX;
  9972. return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
  9973. }
  9974. bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
  9975. {
  9976. // Always consume the SetNextWindowSizeConstraint() call in our early return paths
  9977. ImGuiContext& g = *GImGui;
  9978. ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond;
  9979. g.NextWindowData.SizeConstraintCond = 0;
  9980. ImGuiWindow* window = GetCurrentWindow();
  9981. if (window->SkipItems)
  9982. return false;
  9983. IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
  9984. const ImGuiStyle& style = g.Style;
  9985. const ImGuiID id = window->GetID(label);
  9986. const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
  9987. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  9988. const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth();
  9989. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  9990. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  9991. ItemSize(total_bb, style.FramePadding.y);
  9992. if (!ItemAdd(total_bb, id, &frame_bb))
  9993. return false;
  9994. bool hovered, held;
  9995. bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
  9996. bool popup_open = IsPopupOpen(id);
  9997. const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
  9998. const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
  9999. RenderNavHighlight(frame_bb, id);
  10000. if (!(flags & ImGuiComboFlags_NoPreview))
  10001. window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left);
  10002. if (!(flags & ImGuiComboFlags_NoArrowButton))
  10003. {
  10004. window->DrawList->AddRectFilled(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right);
  10005. RenderArrow(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down);
  10006. }
  10007. RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding);
  10008. if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
  10009. RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
  10010. if (label_size.x > 0)
  10011. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  10012. if ((pressed || g.NavActivateId == id) && !popup_open)
  10013. {
  10014. if (window->DC.NavLayerCurrent == 0)
  10015. window->NavLastIds[0] = id;
  10016. OpenPopupEx(id);
  10017. popup_open = true;
  10018. }
  10019. if (!popup_open)
  10020. return false;
  10021. if (backup_next_window_size_constraint)
  10022. {
  10023. g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint;
  10024. g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
  10025. }
  10026. else
  10027. {
  10028. if ((flags & ImGuiComboFlags_HeightMask_) == 0)
  10029. flags |= ImGuiComboFlags_HeightRegular;
  10030. IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
  10031. int popup_max_height_in_items = -1;
  10032. if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
  10033. else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
  10034. else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
  10035. SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
  10036. }
  10037. char name[16];
  10038. ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
  10039. // Peak into expected window size so we can position it
  10040. if (ImGuiWindow* popup_window = FindWindowByName(name))
  10041. if (popup_window->WasActive)
  10042. {
  10043. ImVec2 size_contents = CalcSizeContents(popup_window);
  10044. ImVec2 size_expected = CalcSizeAfterConstraint(popup_window, CalcSizeAutoFit(popup_window, size_contents));
  10045. if (flags & ImGuiComboFlags_PopupAlignLeft)
  10046. popup_window->AutoPosLastDirection = ImGuiDir_Left;
  10047. ImVec2 pos = FindBestWindowPosForPopup(popup_window, frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
  10048. SetNextWindowPos(pos);
  10049. }
  10050. ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
  10051. if (!Begin(name, NULL, window_flags))
  10052. {
  10053. EndPopup();
  10054. IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
  10055. return false;
  10056. }
  10057. // Horizontally align ourselves with the framed text
  10058. if (style.FramePadding.x != style.WindowPadding.x)
  10059. Indent(style.FramePadding.x - style.WindowPadding.x);
  10060. return true;
  10061. }
  10062. void ImGui::EndCombo()
  10063. {
  10064. const ImGuiStyle& style = GImGui->Style;
  10065. if (style.FramePadding.x != style.WindowPadding.x)
  10066. Unindent(style.FramePadding.x - style.WindowPadding.x);
  10067. EndPopup();
  10068. }
  10069. // Old API, prefer using BeginCombo() nowadays if you can.
  10070. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)
  10071. {
  10072. ImGuiContext& g = *GImGui;
  10073. const char* preview_text = NULL;
  10074. if (*current_item >= 0 && *current_item < items_count)
  10075. items_getter(data, *current_item, &preview_text);
  10076. // The old Combo() API exposed "popup_max_height_in_items", however the new more general BeginCombo() API doesn't, so we emulate it here.
  10077. if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond)
  10078. {
  10079. float popup_max_height = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
  10080. SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, popup_max_height));
  10081. }
  10082. if (!BeginCombo(label, preview_text, 0))
  10083. return false;
  10084. // Display items
  10085. // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)
  10086. bool value_changed = false;
  10087. for (int i = 0; i < items_count; i++)
  10088. {
  10089. PushID((void*)(intptr_t)i);
  10090. const bool item_selected = (i == *current_item);
  10091. const char* item_text;
  10092. if (!items_getter(data, i, &item_text))
  10093. item_text = "*Unknown item*";
  10094. if (Selectable(item_text, item_selected))
  10095. {
  10096. value_changed = true;
  10097. *current_item = i;
  10098. }
  10099. if (item_selected)
  10100. SetItemDefaultFocus();
  10101. PopID();
  10102. }
  10103. EndCombo();
  10104. return value_changed;
  10105. }
  10106. static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
  10107. {
  10108. const char* const* items = (const char* const*)data;
  10109. if (out_text)
  10110. *out_text = items[idx];
  10111. return true;
  10112. }
  10113. static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
  10114. {
  10115. // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
  10116. const char* items_separated_by_zeros = (const char*)data;
  10117. int items_count = 0;
  10118. const char* p = items_separated_by_zeros;
  10119. while (*p)
  10120. {
  10121. if (idx == items_count)
  10122. break;
  10123. p += strlen(p) + 1;
  10124. items_count++;
  10125. }
  10126. if (!*p)
  10127. return false;
  10128. if (out_text)
  10129. *out_text = p;
  10130. return true;
  10131. }
  10132. // Combo box helper allowing to pass an array of strings.
  10133. bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
  10134. {
  10135. const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
  10136. return value_changed;
  10137. }
  10138. // Combo box helper allowing to pass all items in a single string.
  10139. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
  10140. {
  10141. int items_count = 0;
  10142. const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
  10143. while (*p)
  10144. {
  10145. p += strlen(p) + 1;
  10146. items_count++;
  10147. }
  10148. bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
  10149. return value_changed;
  10150. }
  10151. // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image.
  10152. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID.
  10153. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  10154. {
  10155. ImGuiWindow* window = GetCurrentWindow();
  10156. if (window->SkipItems)
  10157. return false;
  10158. ImGuiContext& g = *GImGui;
  10159. const ImGuiStyle& style = g.Style;
  10160. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped.
  10161. PopClipRect();
  10162. ImGuiID id = window->GetID(label);
  10163. ImVec2 label_size = CalcTextSize(label, NULL, true);
  10164. ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
  10165. ImVec2 pos = window->DC.CursorPos;
  10166. pos.y += window->DC.CurrentLineTextBaseOffset;
  10167. ImRect bb(pos, pos + size);
  10168. ItemSize(bb);
  10169. // Fill horizontal space.
  10170. ImVec2 window_padding = window->WindowPadding;
  10171. float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
  10172. float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x);
  10173. ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y);
  10174. ImRect bb_with_spacing(pos, pos + size_draw);
  10175. if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
  10176. bb_with_spacing.Max.x += window_padding.x;
  10177. // Selectables are tightly packed together, we extend the box to cover spacing between selectable.
  10178. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
  10179. float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
  10180. float spacing_R = style.ItemSpacing.x - spacing_L;
  10181. float spacing_D = style.ItemSpacing.y - spacing_U;
  10182. bb_with_spacing.Min.x -= spacing_L;
  10183. bb_with_spacing.Min.y -= spacing_U;
  10184. bb_with_spacing.Max.x += spacing_R;
  10185. bb_with_spacing.Max.y += spacing_D;
  10186. if (!ItemAdd(bb_with_spacing, (flags & ImGuiSelectableFlags_Disabled) ? 0 : id))
  10187. {
  10188. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
  10189. PushColumnClipRect();
  10190. return false;
  10191. }
  10192. ImGuiButtonFlags button_flags = 0;
  10193. if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_NoHoldingActiveID;
  10194. if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnRelease;
  10195. if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
  10196. if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
  10197. bool hovered, held;
  10198. bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
  10199. if (flags & ImGuiSelectableFlags_Disabled)
  10200. selected = false;
  10201. // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets)
  10202. if (pressed || hovered)// && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f))
  10203. if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerActiveMask)
  10204. {
  10205. g.NavDisableHighlight = true;
  10206. SetNavID(id, window->DC.NavLayerCurrent);
  10207. }
  10208. // Render
  10209. if (hovered || selected)
  10210. {
  10211. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  10212. RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
  10213. RenderNavHighlight(bb_with_spacing, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
  10214. }
  10215. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
  10216. {
  10217. PushColumnClipRect();
  10218. bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
  10219. }
  10220. if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  10221. RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f));
  10222. if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
  10223. // Automatically close popups
  10224. if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
  10225. CloseCurrentPopup();
  10226. return pressed;
  10227. }
  10228. bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  10229. {
  10230. if (Selectable(label, *p_selected, flags, size_arg))
  10231. {
  10232. *p_selected = !*p_selected;
  10233. return true;
  10234. }
  10235. return false;
  10236. }
  10237. // Helper to calculate the size of a listbox and display a label on the right.
  10238. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty"
  10239. bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
  10240. {
  10241. ImGuiWindow* window = GetCurrentWindow();
  10242. if (window->SkipItems)
  10243. return false;
  10244. const ImGuiStyle& style = GetStyle();
  10245. const ImGuiID id = GetID(label);
  10246. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  10247. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  10248. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
  10249. ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
  10250. ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
  10251. ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  10252. window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy.
  10253. BeginGroup();
  10254. if (label_size.x > 0)
  10255. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  10256. BeginChildFrame(id, frame_bb.GetSize());
  10257. return true;
  10258. }
  10259. bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
  10260. {
  10261. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  10262. // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size.
  10263. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
  10264. if (height_in_items < 0)
  10265. height_in_items = ImMin(items_count, 7);
  10266. float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f);
  10267. // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild().
  10268. ImVec2 size;
  10269. size.x = 0.0f;
  10270. size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y;
  10271. return ListBoxHeader(label, size);
  10272. }
  10273. void ImGui::ListBoxFooter()
  10274. {
  10275. ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow;
  10276. const ImRect bb = parent_window->DC.LastItemRect;
  10277. const ImGuiStyle& style = GetStyle();
  10278. EndChildFrame();
  10279. // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
  10280. // We call SameLine() to restore DC.CurrentLine* data
  10281. SameLine();
  10282. parent_window->DC.CursorPos = bb.Min;
  10283. ItemSize(bb, style.FramePadding.y);
  10284. EndGroup();
  10285. }
  10286. bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
  10287. {
  10288. const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
  10289. return value_changed;
  10290. }
  10291. bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
  10292. {
  10293. if (!ListBoxHeader(label, items_count, height_in_items))
  10294. return false;
  10295. // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
  10296. bool value_changed = false;
  10297. ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
  10298. while (clipper.Step())
  10299. for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
  10300. {
  10301. const bool item_selected = (i == *current_item);
  10302. const char* item_text;
  10303. if (!items_getter(data, i, &item_text))
  10304. item_text = "*Unknown item*";
  10305. PushID(i);
  10306. if (Selectable(item_text, item_selected))
  10307. {
  10308. *current_item = i;
  10309. value_changed = true;
  10310. }
  10311. if (item_selected)
  10312. SetItemDefaultFocus();
  10313. PopID();
  10314. }
  10315. ListBoxFooter();
  10316. return value_changed;
  10317. }
  10318. bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
  10319. {
  10320. ImGuiWindow* window = GetCurrentWindow();
  10321. if (window->SkipItems)
  10322. return false;
  10323. ImGuiContext& g = *GImGui;
  10324. ImGuiStyle& style = g.Style;
  10325. ImVec2 pos = window->DC.CursorPos;
  10326. ImVec2 label_size = CalcTextSize(label, NULL, true);
  10327. ImGuiSelectableFlags flags = ImGuiSelectableFlags_MenuItem | (enabled ? 0 : ImGuiSelectableFlags_Disabled);
  10328. bool pressed;
  10329. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  10330. {
  10331. // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
  10332. // Note that in this situation we render neither the shortcut neither the selected tick mark
  10333. float w = label_size.x;
  10334. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  10335. PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
  10336. pressed = Selectable(label, false, flags, ImVec2(w, 0.0f));
  10337. PopStyleVar();
  10338. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
  10339. }
  10340. else
  10341. {
  10342. ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
  10343. float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
  10344. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  10345. pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f));
  10346. if (shortcut_size.x > 0.0f)
  10347. {
  10348. PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  10349. RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
  10350. PopStyleColor();
  10351. }
  10352. if (selected)
  10353. RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f);
  10354. }
  10355. return pressed;
  10356. }
  10357. bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
  10358. {
  10359. if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
  10360. {
  10361. if (p_selected)
  10362. *p_selected = !*p_selected;
  10363. return true;
  10364. }
  10365. return false;
  10366. }
  10367. bool ImGui::BeginMainMenuBar()
  10368. {
  10369. ImGuiContext& g = *GImGui;
  10370. SetNextWindowPos(ImVec2(0.0f, 0.0f));
  10371. SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
  10372. PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  10373. PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
  10374. if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar)
  10375. || !BeginMenuBar())
  10376. {
  10377. End();
  10378. PopStyleVar(2);
  10379. return false;
  10380. }
  10381. g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
  10382. return true;
  10383. }
  10384. void ImGui::EndMainMenuBar()
  10385. {
  10386. EndMenuBar();
  10387. // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
  10388. ImGuiContext& g = *GImGui;
  10389. if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0)
  10390. FocusFrontMostActiveWindow(g.NavWindow);
  10391. End();
  10392. PopStyleVar(2);
  10393. }
  10394. bool ImGui::BeginMenuBar()
  10395. {
  10396. ImGuiWindow* window = GetCurrentWindow();
  10397. if (window->SkipItems)
  10398. return false;
  10399. if (!(window->Flags & ImGuiWindowFlags_MenuBar))
  10400. return false;
  10401. IM_ASSERT(!window->DC.MenuBarAppending);
  10402. BeginGroup(); // Save position
  10403. PushID("##menubar");
  10404. // We don't clip with regular window clipping rectangle as it is already set to the area below. However we clip with window full rect.
  10405. // We remove 1 worth of rounding to Max.x to that text in long menus don't tend to display over the lower-right rounded area, which looks particularly glitchy.
  10406. ImRect bar_rect = window->MenuBarRect();
  10407. ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f));
  10408. clip_rect.ClipWith(window->WindowRectClipped);
  10409. PushClipRect(clip_rect.Min, clip_rect.Max, false);
  10410. window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffsetX, bar_rect.Min.y);// + g.Style.FramePadding.y);
  10411. window->DC.LayoutType = ImGuiLayoutType_Horizontal;
  10412. window->DC.NavLayerCurrent++;
  10413. window->DC.NavLayerCurrentMask <<= 1;
  10414. window->DC.MenuBarAppending = true;
  10415. AlignTextToFramePadding();
  10416. return true;
  10417. }
  10418. void ImGui::EndMenuBar()
  10419. {
  10420. ImGuiWindow* window = GetCurrentWindow();
  10421. if (window->SkipItems)
  10422. return;
  10423. ImGuiContext& g = *GImGui;
  10424. // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
  10425. if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
  10426. {
  10427. ImGuiWindow* nav_earliest_child = g.NavWindow;
  10428. while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
  10429. nav_earliest_child = nav_earliest_child->ParentWindow;
  10430. if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None)
  10431. {
  10432. // To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
  10433. // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost)
  10434. IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check
  10435. FocusWindow(window);
  10436. SetNavIDAndMoveMouse(window->NavLastIds[1], 1, window->NavRectRel[1]);
  10437. g.NavLayer = 1;
  10438. g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.
  10439. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
  10440. NavMoveRequestCancel();
  10441. }
  10442. }
  10443. IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
  10444. IM_ASSERT(window->DC.MenuBarAppending);
  10445. PopClipRect();
  10446. PopID();
  10447. window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
  10448. window->DC.GroupStack.back().AdvanceCursor = false;
  10449. EndGroup();
  10450. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  10451. window->DC.NavLayerCurrent--;
  10452. window->DC.NavLayerCurrentMask >>= 1;
  10453. window->DC.MenuBarAppending = false;
  10454. }
  10455. bool ImGui::BeginMenu(const char* label, bool enabled)
  10456. {
  10457. ImGuiWindow* window = GetCurrentWindow();
  10458. if (window->SkipItems)
  10459. return false;
  10460. ImGuiContext& g = *GImGui;
  10461. const ImGuiStyle& style = g.Style;
  10462. const ImGuiID id = window->GetID(label);
  10463. ImVec2 label_size = CalcTextSize(label, NULL, true);
  10464. bool pressed;
  10465. bool menu_is_open = IsPopupOpen(id);
  10466. bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].OpenParentId == window->IDStack.back());
  10467. ImGuiWindow* backed_nav_window = g.NavWindow;
  10468. if (menuset_is_open)
  10469. g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
  10470. // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos).
  10471. ImVec2 popup_pos, pos = window->DC.CursorPos;
  10472. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  10473. {
  10474. // Menu inside an horizontal menu bar
  10475. // Selectable extend their highlight by half ItemSpacing in each direction.
  10476. // For ChildMenu, the popup position will be overwritten by the call to FindBestPopupWindowPos() in Begin()
  10477. popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
  10478. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  10479. PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
  10480. float w = label_size.x;
  10481. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  10482. PopStyleVar();
  10483. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
  10484. }
  10485. else
  10486. {
  10487. // Menu inside a menu
  10488. popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
  10489. float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
  10490. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  10491. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  10492. if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  10493. RenderArrow(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right);
  10494. if (!enabled) PopStyleColor();
  10495. }
  10496. const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id);
  10497. if (menuset_is_open)
  10498. g.NavWindow = backed_nav_window;
  10499. bool want_open = false, want_close = false;
  10500. if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
  10501. {
  10502. // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
  10503. bool moving_within_opened_triangle = false;
  10504. if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar))
  10505. {
  10506. if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window)
  10507. {
  10508. ImRect next_window_rect = next_window->Rect();
  10509. ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
  10510. ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
  10511. ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
  10512. float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
  10513. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
  10514. tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
  10515. tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
  10516. moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
  10517. //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug
  10518. }
  10519. }
  10520. want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
  10521. want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
  10522. if (g.NavActivateId == id)
  10523. {
  10524. want_close = menu_is_open;
  10525. want_open = !menu_is_open;
  10526. }
  10527. if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
  10528. {
  10529. want_open = true;
  10530. NavMoveRequestCancel();
  10531. }
  10532. }
  10533. else
  10534. {
  10535. // Menu bar
  10536. if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
  10537. {
  10538. want_close = true;
  10539. want_open = menu_is_open = false;
  10540. }
  10541. else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
  10542. {
  10543. want_open = true;
  10544. }
  10545. else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
  10546. {
  10547. want_open = true;
  10548. NavMoveRequestCancel();
  10549. }
  10550. }
  10551. if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
  10552. want_close = true;
  10553. if (want_close && IsPopupOpen(id))
  10554. ClosePopupToLevel(g.CurrentPopupStack.Size);
  10555. if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size)
  10556. {
  10557. // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
  10558. OpenPopup(label);
  10559. return false;
  10560. }
  10561. menu_is_open |= want_open;
  10562. if (want_open)
  10563. OpenPopup(label);
  10564. if (menu_is_open)
  10565. {
  10566. SetNextWindowPos(popup_pos, ImGuiCond_Always);
  10567. ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
  10568. menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  10569. }
  10570. return menu_is_open;
  10571. }
  10572. void ImGui::EndMenu()
  10573. {
  10574. // Nav: When a left move request _within our child menu_ failed, close the menu.
  10575. // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.
  10576. // However it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.
  10577. ImGuiContext& g = *GImGui;
  10578. ImGuiWindow* window = g.CurrentWindow;
  10579. if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)
  10580. {
  10581. ClosePopupToLevel(g.OpenPopupStack.Size - 1);
  10582. NavMoveRequestCancel();
  10583. }
  10584. EndPopup();
  10585. }
  10586. // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  10587. void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
  10588. {
  10589. ImGuiContext& g = *GImGui;
  10590. int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
  10591. BeginTooltipEx(0, true);
  10592. const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
  10593. if (text_end > text)
  10594. {
  10595. TextUnformatted(text, text_end);
  10596. Separator();
  10597. }
  10598. ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
  10599. ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
  10600. SameLine();
  10601. if (flags & ImGuiColorEditFlags_NoAlpha)
  10602. Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
  10603. else
  10604. Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
  10605. EndTooltip();
  10606. }
  10607. static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b)
  10608. {
  10609. float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
  10610. int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
  10611. int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
  10612. int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
  10613. return IM_COL32(r, g, b, 0xFF);
  10614. }
  10615. // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
  10616. // I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether.
  10617. void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
  10618. {
  10619. ImGuiWindow* window = GetCurrentWindow();
  10620. if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
  10621. {
  10622. ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col));
  10623. ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col));
  10624. window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags);
  10625. int yi = 0;
  10626. for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
  10627. {
  10628. float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
  10629. if (y2 <= y1)
  10630. continue;
  10631. for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
  10632. {
  10633. float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
  10634. if (x2 <= x1)
  10635. continue;
  10636. int rounding_corners_flags_cell = 0;
  10637. if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; }
  10638. if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; }
  10639. rounding_corners_flags_cell &= rounding_corners_flags;
  10640. window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
  10641. }
  10642. }
  10643. }
  10644. else
  10645. {
  10646. window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
  10647. }
  10648. }
  10649. void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
  10650. {
  10651. ImGuiContext& g = *GImGui;
  10652. if ((flags & ImGuiColorEditFlags__InputsMask) == 0)
  10653. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask;
  10654. if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
  10655. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
  10656. if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
  10657. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
  10658. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected
  10659. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected
  10660. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected
  10661. g.ColorEditOptions = flags;
  10662. }
  10663. // A little colored square. Return true when clicked.
  10664. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
  10665. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
  10666. bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
  10667. {
  10668. ImGuiWindow* window = GetCurrentWindow();
  10669. if (window->SkipItems)
  10670. return false;
  10671. ImGuiContext& g = *GImGui;
  10672. const ImGuiID id = window->GetID(desc_id);
  10673. float default_size = GetFrameHeight();
  10674. if (size.x == 0.0f)
  10675. size.x = default_size;
  10676. if (size.y == 0.0f)
  10677. size.y = default_size;
  10678. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  10679. ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
  10680. if (!ItemAdd(bb, id))
  10681. return false;
  10682. bool hovered, held;
  10683. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  10684. if (flags & ImGuiColorEditFlags_NoAlpha)
  10685. flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
  10686. ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f);
  10687. float grid_step = ImMin(size.x, size.y) / 2.99f;
  10688. float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
  10689. ImRect bb_inner = bb;
  10690. float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
  10691. bb_inner.Expand(off);
  10692. if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f)
  10693. {
  10694. float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f);
  10695. RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight);
  10696. window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft);
  10697. }
  10698. else
  10699. {
  10700. // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
  10701. ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha;
  10702. if (col_source.w < 1.0f)
  10703. RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
  10704. else
  10705. window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
  10706. }
  10707. RenderNavHighlight(bb, id);
  10708. if (g.Style.FrameBorderSize > 0.0f)
  10709. RenderFrameBorder(bb.Min, bb.Max, rounding);
  10710. else
  10711. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
  10712. // Drag and Drop Source
  10713. if (g.ActiveId == id && BeginDragDropSource()) // NB: The ActiveId test is merely an optional micro-optimization
  10714. {
  10715. if (flags & ImGuiColorEditFlags_NoAlpha)
  10716. SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col, sizeof(float) * 3, ImGuiCond_Once);
  10717. else
  10718. SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once);
  10719. ColorButton(desc_id, col, flags);
  10720. SameLine();
  10721. TextUnformatted("Color");
  10722. EndDragDropSource();
  10723. hovered = false;
  10724. }
  10725. // Tooltip
  10726. if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)
  10727. ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
  10728. return pressed;
  10729. }
  10730. bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
  10731. {
  10732. return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
  10733. }
  10734. void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
  10735. {
  10736. bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask);
  10737. bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
  10738. if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
  10739. return;
  10740. ImGuiContext& g = *GImGui;
  10741. ImGuiColorEditFlags opts = g.ColorEditOptions;
  10742. if (allow_opt_inputs)
  10743. {
  10744. if (RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB;
  10745. if (RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV;
  10746. if (RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX;
  10747. }
  10748. if (allow_opt_datatype)
  10749. {
  10750. if (allow_opt_inputs) Separator();
  10751. if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
  10752. if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
  10753. }
  10754. if (allow_opt_inputs || allow_opt_datatype)
  10755. Separator();
  10756. if (Button("Copy as..", ImVec2(-1,0)))
  10757. OpenPopup("Copy");
  10758. if (BeginPopup("Copy"))
  10759. {
  10760. int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
  10761. char buf[64];
  10762. ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
  10763. if (Selectable(buf))
  10764. SetClipboardText(buf);
  10765. ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
  10766. if (Selectable(buf))
  10767. SetClipboardText(buf);
  10768. if (flags & ImGuiColorEditFlags_NoAlpha)
  10769. ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb);
  10770. else
  10771. ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca);
  10772. if (Selectable(buf))
  10773. SetClipboardText(buf);
  10774. EndPopup();
  10775. }
  10776. g.ColorEditOptions = opts;
  10777. EndPopup();
  10778. }
  10779. static void ColorPickerOptionsPopup(ImGuiColorEditFlags flags, const float* ref_col)
  10780. {
  10781. bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
  10782. bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
  10783. if ((!allow_opt_picker && !allow_opt_alpha_bar) || !ImGui::BeginPopup("context"))
  10784. return;
  10785. ImGuiContext& g = *GImGui;
  10786. if (allow_opt_picker)
  10787. {
  10788. ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
  10789. ImGui::PushItemWidth(picker_size.x);
  10790. for (int picker_type = 0; picker_type < 2; picker_type++)
  10791. {
  10792. // Draw small/thumbnail version of each picker type (over an invisible button for selection)
  10793. if (picker_type > 0) ImGui::Separator();
  10794. ImGui::PushID(picker_type);
  10795. ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha);
  10796. if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
  10797. if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
  10798. ImVec2 backup_pos = ImGui::GetCursorScreenPos();
  10799. if (ImGui::Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
  10800. g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
  10801. ImGui::SetCursorScreenPos(backup_pos);
  10802. ImVec4 dummy_ref_col;
  10803. memcpy(&dummy_ref_col.x, ref_col, sizeof(float) * (picker_flags & ImGuiColorEditFlags_NoAlpha ? 3 : 4));
  10804. ImGui::ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
  10805. ImGui::PopID();
  10806. }
  10807. ImGui::PopItemWidth();
  10808. }
  10809. if (allow_opt_alpha_bar)
  10810. {
  10811. if (allow_opt_picker) ImGui::Separator();
  10812. ImGui::CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
  10813. }
  10814. ImGui::EndPopup();
  10815. }
  10816. // Edit colors components (each component in 0.0f..1.0f range).
  10817. // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  10818. // With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
  10819. bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
  10820. {
  10821. ImGuiWindow* window = GetCurrentWindow();
  10822. if (window->SkipItems)
  10823. return false;
  10824. ImGuiContext& g = *GImGui;
  10825. const ImGuiStyle& style = g.Style;
  10826. const float square_sz = GetFrameHeight();
  10827. const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
  10828. const float w_items_all = CalcItemWidth() - w_extra;
  10829. const char* label_display_end = FindRenderedTextEnd(label);
  10830. const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
  10831. const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
  10832. const int components = alpha ? 4 : 3;
  10833. const ImGuiColorEditFlags flags_untouched = flags;
  10834. BeginGroup();
  10835. PushID(label);
  10836. // If we're not showing any slider there's no point in doing any HSV conversions
  10837. if (flags & ImGuiColorEditFlags_NoInputs)
  10838. flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions;
  10839. // Context menu: display and modify options (before defaults are applied)
  10840. if (!(flags & ImGuiColorEditFlags_NoOptions))
  10841. ColorEditOptionsPopup(col, flags);
  10842. // Read stored options
  10843. if (!(flags & ImGuiColorEditFlags__InputsMask))
  10844. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask);
  10845. if (!(flags & ImGuiColorEditFlags__DataTypeMask))
  10846. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
  10847. if (!(flags & ImGuiColorEditFlags__PickerMask))
  10848. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
  10849. flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask));
  10850. // Convert to the formats we need
  10851. float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
  10852. if (flags & ImGuiColorEditFlags_HSV)
  10853. ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
  10854. int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
  10855. bool value_changed = false;
  10856. bool value_changed_as_float = false;
  10857. if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
  10858. {
  10859. // RGB/HSV 0..255 Sliders
  10860. const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  10861. const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  10862. const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
  10863. const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
  10864. const char* fmt_table_int[3][4] =
  10865. {
  10866. { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, // Short display
  10867. { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, // Long display for RGBA
  10868. { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } // Long display for HSVA
  10869. };
  10870. const char* fmt_table_float[3][4] =
  10871. {
  10872. { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
  10873. { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
  10874. { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
  10875. };
  10876. const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1;
  10877. PushItemWidth(w_item_one);
  10878. for (int n = 0; n < components; n++)
  10879. {
  10880. if (n > 0)
  10881. SameLine(0, style.ItemInnerSpacing.x);
  10882. if (n + 1 == components)
  10883. PushItemWidth(w_item_last);
  10884. if (flags & ImGuiColorEditFlags_Float)
  10885. value_changed = value_changed_as_float = value_changed | DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
  10886. else
  10887. value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
  10888. if (!(flags & ImGuiColorEditFlags_NoOptions))
  10889. OpenPopupOnItemClick("context");
  10890. }
  10891. PopItemWidth();
  10892. PopItemWidth();
  10893. }
  10894. else if ((flags & ImGuiColorEditFlags_HEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
  10895. {
  10896. // RGB Hexadecimal Input
  10897. char buf[64];
  10898. if (alpha)
  10899. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255));
  10900. else
  10901. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255));
  10902. PushItemWidth(w_items_all);
  10903. if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
  10904. {
  10905. value_changed = true;
  10906. char* p = buf;
  10907. while (*p == '#' || ImCharIsSpace(*p))
  10908. p++;
  10909. i[0] = i[1] = i[2] = i[3] = 0;
  10910. if (alpha)
  10911. sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
  10912. else
  10913. sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
  10914. }
  10915. if (!(flags & ImGuiColorEditFlags_NoOptions))
  10916. OpenPopupOnItemClick("context");
  10917. PopItemWidth();
  10918. }
  10919. ImGuiWindow* picker_active_window = NULL;
  10920. if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
  10921. {
  10922. if (!(flags & ImGuiColorEditFlags_NoInputs))
  10923. SameLine(0, style.ItemInnerSpacing.x);
  10924. const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
  10925. if (ColorButton("##ColorButton", col_v4, flags))
  10926. {
  10927. if (!(flags & ImGuiColorEditFlags_NoPicker))
  10928. {
  10929. // Store current color and open a picker
  10930. g.ColorPickerRef = col_v4;
  10931. OpenPopup("picker");
  10932. SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y));
  10933. }
  10934. }
  10935. if (!(flags & ImGuiColorEditFlags_NoOptions))
  10936. OpenPopupOnItemClick("context");
  10937. if (BeginPopup("picker"))
  10938. {
  10939. picker_active_window = g.CurrentWindow;
  10940. if (label != label_display_end)
  10941. {
  10942. TextUnformatted(label, label_display_end);
  10943. Separator();
  10944. }
  10945. ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
  10946. ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
  10947. PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
  10948. value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
  10949. PopItemWidth();
  10950. EndPopup();
  10951. }
  10952. }
  10953. if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
  10954. {
  10955. SameLine(0, style.ItemInnerSpacing.x);
  10956. TextUnformatted(label, label_display_end);
  10957. }
  10958. // Convert back
  10959. if (picker_active_window == NULL)
  10960. {
  10961. if (!value_changed_as_float)
  10962. for (int n = 0; n < 4; n++)
  10963. f[n] = i[n] / 255.0f;
  10964. if (flags & ImGuiColorEditFlags_HSV)
  10965. ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
  10966. if (value_changed)
  10967. {
  10968. col[0] = f[0];
  10969. col[1] = f[1];
  10970. col[2] = f[2];
  10971. if (alpha)
  10972. col[3] = f[3];
  10973. }
  10974. }
  10975. PopID();
  10976. EndGroup();
  10977. // Drag and Drop Target
  10978. if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && BeginDragDropTarget()) // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
  10979. {
  10980. if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
  10981. {
  10982. memcpy((float*)col, payload->Data, sizeof(float) * 3);
  10983. value_changed = true;
  10984. }
  10985. if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
  10986. {
  10987. memcpy((float*)col, payload->Data, sizeof(float) * components);
  10988. value_changed = true;
  10989. }
  10990. EndDragDropTarget();
  10991. }
  10992. // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
  10993. if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
  10994. window->DC.LastItemId = g.ActiveId;
  10995. return value_changed;
  10996. }
  10997. bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
  10998. {
  10999. float col4[4] = { col[0], col[1], col[2], 1.0f };
  11000. if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
  11001. return false;
  11002. col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
  11003. return true;
  11004. }
  11005. // 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side.
  11006. static void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col)
  11007. {
  11008. switch (direction)
  11009. {
  11010. case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return;
  11011. case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return;
  11012. case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return;
  11013. case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return;
  11014. case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings
  11015. }
  11016. }
  11017. static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w)
  11018. {
  11019. RenderArrow(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK);
  11020. RenderArrow(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE);
  11021. RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK);
  11022. RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE);
  11023. }
  11024. // ColorPicker
  11025. // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  11026. // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
  11027. bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
  11028. {
  11029. ImGuiContext& g = *GImGui;
  11030. ImGuiWindow* window = GetCurrentWindow();
  11031. ImDrawList* draw_list = window->DrawList;
  11032. ImGuiStyle& style = g.Style;
  11033. ImGuiIO& io = g.IO;
  11034. PushID(label);
  11035. BeginGroup();
  11036. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  11037. flags |= ImGuiColorEditFlags_NoSmallPreview;
  11038. // Context menu: display and store options.
  11039. if (!(flags & ImGuiColorEditFlags_NoOptions))
  11040. ColorPickerOptionsPopup(flags, col);
  11041. // Read stored options
  11042. if (!(flags & ImGuiColorEditFlags__PickerMask))
  11043. flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
  11044. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected
  11045. if (!(flags & ImGuiColorEditFlags_NoOptions))
  11046. flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
  11047. // Setup
  11048. int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
  11049. bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
  11050. ImVec2 picker_pos = window->DC.CursorPos;
  11051. float square_sz = GetFrameHeight();
  11052. float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
  11053. float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
  11054. float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
  11055. float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
  11056. float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f);
  11057. float backup_initial_col[4];
  11058. memcpy(backup_initial_col, col, components * sizeof(float));
  11059. float wheel_thickness = sv_picker_size * 0.08f;
  11060. float wheel_r_outer = sv_picker_size * 0.50f;
  11061. float wheel_r_inner = wheel_r_outer - wheel_thickness;
  11062. ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f);
  11063. // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
  11064. float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
  11065. ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
  11066. ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
  11067. ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
  11068. float H,S,V;
  11069. ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V);
  11070. bool value_changed = false, value_changed_h = false, value_changed_sv = false;
  11071. PushItemFlag(ImGuiItemFlags_NoNav, true);
  11072. if (flags & ImGuiColorEditFlags_PickerHueWheel)
  11073. {
  11074. // Hue wheel + SV triangle logic
  11075. InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
  11076. if (IsItemActive())
  11077. {
  11078. ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
  11079. ImVec2 current_off = g.IO.MousePos - wheel_center;
  11080. float initial_dist2 = ImLengthSqr(initial_off);
  11081. if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1))
  11082. {
  11083. // Interactive with Hue wheel
  11084. H = atan2f(current_off.y, current_off.x) / IM_PI*0.5f;
  11085. if (H < 0.0f)
  11086. H += 1.0f;
  11087. value_changed = value_changed_h = true;
  11088. }
  11089. float cos_hue_angle = cosf(-H * 2.0f * IM_PI);
  11090. float sin_hue_angle = sinf(-H * 2.0f * IM_PI);
  11091. if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
  11092. {
  11093. // Interacting with SV triangle
  11094. ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
  11095. if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
  11096. current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
  11097. float uu, vv, ww;
  11098. ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
  11099. V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
  11100. S = ImClamp(uu / V, 0.0001f, 1.0f);
  11101. value_changed = value_changed_sv = true;
  11102. }
  11103. }
  11104. if (!(flags & ImGuiColorEditFlags_NoOptions))
  11105. OpenPopupOnItemClick("context");
  11106. }
  11107. else if (flags & ImGuiColorEditFlags_PickerHueBar)
  11108. {
  11109. // SV rectangle logic
  11110. InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
  11111. if (IsItemActive())
  11112. {
  11113. S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1));
  11114. V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
  11115. value_changed = value_changed_sv = true;
  11116. }
  11117. if (!(flags & ImGuiColorEditFlags_NoOptions))
  11118. OpenPopupOnItemClick("context");
  11119. // Hue bar logic
  11120. SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
  11121. InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
  11122. if (IsItemActive())
  11123. {
  11124. H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
  11125. value_changed = value_changed_h = true;
  11126. }
  11127. }
  11128. // Alpha bar logic
  11129. if (alpha_bar)
  11130. {
  11131. SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
  11132. InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
  11133. if (IsItemActive())
  11134. {
  11135. col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
  11136. value_changed = true;
  11137. }
  11138. }
  11139. PopItemFlag(); // ImGuiItemFlags_NoNav
  11140. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  11141. {
  11142. SameLine(0, style.ItemInnerSpacing.x);
  11143. BeginGroup();
  11144. }
  11145. if (!(flags & ImGuiColorEditFlags_NoLabel))
  11146. {
  11147. const char* label_display_end = FindRenderedTextEnd(label);
  11148. if (label != label_display_end)
  11149. {
  11150. if ((flags & ImGuiColorEditFlags_NoSidePreview))
  11151. SameLine(0, style.ItemInnerSpacing.x);
  11152. TextUnformatted(label, label_display_end);
  11153. }
  11154. }
  11155. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  11156. {
  11157. PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
  11158. ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
  11159. if ((flags & ImGuiColorEditFlags_NoLabel))
  11160. Text("Current");
  11161. ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2));
  11162. if (ref_col != NULL)
  11163. {
  11164. Text("Original");
  11165. ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
  11166. if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)))
  11167. {
  11168. memcpy(col, ref_col, components * sizeof(float));
  11169. value_changed = true;
  11170. }
  11171. }
  11172. PopItemFlag();
  11173. EndGroup();
  11174. }
  11175. // Convert back color to RGB
  11176. if (value_changed_h || value_changed_sv)
  11177. ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]);
  11178. // R,G,B and H,S,V slider color editor
  11179. if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
  11180. {
  11181. PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
  11182. ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
  11183. ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
  11184. if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  11185. value_changed |= ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB);
  11186. if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  11187. value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV);
  11188. if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  11189. value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX);
  11190. PopItemWidth();
  11191. }
  11192. // Try to cancel hue wrap (after ColorEdit), if any
  11193. if (value_changed)
  11194. {
  11195. float new_H, new_S, new_V;
  11196. ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
  11197. if (new_H <= 0 && H > 0)
  11198. {
  11199. if (new_V <= 0 && V != new_V)
  11200. ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
  11201. else if (new_S <= 0)
  11202. ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
  11203. }
  11204. }
  11205. ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
  11206. ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
  11207. ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f));
  11208. const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) };
  11209. ImVec2 sv_cursor_pos;
  11210. if (flags & ImGuiColorEditFlags_PickerHueWheel)
  11211. {
  11212. // Render Hue Wheel
  11213. const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
  11214. const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
  11215. for (int n = 0; n < 6; n++)
  11216. {
  11217. const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
  11218. const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
  11219. const int vert_start_idx = draw_list->VtxBuffer.Size;
  11220. draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
  11221. draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness);
  11222. const int vert_end_idx = draw_list->VtxBuffer.Size;
  11223. // Paint colors over existing vertices
  11224. ImVec2 gradient_p0(wheel_center.x + cosf(a0) * wheel_r_inner, wheel_center.y + sinf(a0) * wheel_r_inner);
  11225. ImVec2 gradient_p1(wheel_center.x + cosf(a1) * wheel_r_inner, wheel_center.y + sinf(a1) * wheel_r_inner);
  11226. ShadeVertsLinearColorGradientKeepAlpha(draw_list->VtxBuffer.Data + vert_start_idx, draw_list->VtxBuffer.Data + vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]);
  11227. }
  11228. // Render Cursor + preview on Hue Wheel
  11229. float cos_hue_angle = cosf(H * 2.0f * IM_PI);
  11230. float sin_hue_angle = sinf(H * 2.0f * IM_PI);
  11231. ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f);
  11232. float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
  11233. int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);
  11234. draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
  11235. draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments);
  11236. draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments);
  11237. // Render SV triangle (rotated according to hue)
  11238. ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
  11239. ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
  11240. ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
  11241. ImVec2 uv_white = GetFontTexUvWhitePixel();
  11242. draw_list->PrimReserve(6, 6);
  11243. draw_list->PrimVtx(tra, uv_white, hue_color32);
  11244. draw_list->PrimVtx(trb, uv_white, hue_color32);
  11245. draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE);
  11246. draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS);
  11247. draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK);
  11248. draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS);
  11249. draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f);
  11250. sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
  11251. }
  11252. else if (flags & ImGuiColorEditFlags_PickerHueBar)
  11253. {
  11254. // Render SV Square
  11255. draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE);
  11256. draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK);
  11257. RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f);
  11258. sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
  11259. sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
  11260. // Render Hue Bar
  11261. for (int i = 0; i < 6; ++i)
  11262. draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]);
  11263. float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f);
  11264. RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
  11265. RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
  11266. }
  11267. // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
  11268. float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;
  11269. draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12);
  11270. draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12);
  11271. draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12);
  11272. // Render alpha bar
  11273. if (alpha_bar)
  11274. {
  11275. float alpha = ImSaturate(col[3]);
  11276. ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
  11277. RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
  11278. draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK);
  11279. float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f);
  11280. RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
  11281. RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
  11282. }
  11283. EndGroup();
  11284. PopID();
  11285. return value_changed && memcmp(backup_initial_col, col, components * sizeof(float));
  11286. }
  11287. // Horizontal separating line.
  11288. void ImGui::Separator()
  11289. {
  11290. ImGuiWindow* window = GetCurrentWindow();
  11291. if (window->SkipItems)
  11292. return;
  11293. ImGuiContext& g = *GImGui;
  11294. ImGuiWindowFlags flags = 0;
  11295. if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0)
  11296. flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
  11297. IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected
  11298. if (flags & ImGuiSeparatorFlags_Vertical)
  11299. {
  11300. VerticalSeparator();
  11301. return;
  11302. }
  11303. // Horizontal Separator
  11304. if (window->DC.ColumnsSet)
  11305. PopClipRect();
  11306. float x1 = window->Pos.x;
  11307. float x2 = window->Pos.x + window->Size.x;
  11308. if (!window->DC.GroupStack.empty())
  11309. x1 += window->DC.IndentX;
  11310. const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f));
  11311. ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
  11312. if (!ItemAdd(bb, 0))
  11313. {
  11314. if (window->DC.ColumnsSet)
  11315. PushColumnClipRect();
  11316. return;
  11317. }
  11318. window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator));
  11319. if (g.LogEnabled)
  11320. LogRenderedText(NULL, IM_NEWLINE "--------------------------------");
  11321. if (window->DC.ColumnsSet)
  11322. {
  11323. PushColumnClipRect();
  11324. window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y;
  11325. }
  11326. }
  11327. void ImGui::VerticalSeparator()
  11328. {
  11329. ImGuiWindow* window = GetCurrentWindow();
  11330. if (window->SkipItems)
  11331. return;
  11332. ImGuiContext& g = *GImGui;
  11333. float y1 = window->DC.CursorPos.y;
  11334. float y2 = window->DC.CursorPos.y + window->DC.CurrentLineHeight;
  11335. const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2));
  11336. ItemSize(ImVec2(bb.GetWidth(), 0.0f));
  11337. if (!ItemAdd(bb, 0))
  11338. return;
  11339. window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));
  11340. if (g.LogEnabled)
  11341. LogText(" |");
  11342. }
  11343. bool ImGui::SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend)
  11344. {
  11345. ImGuiContext& g = *GImGui;
  11346. ImGuiWindow* window = g.CurrentWindow;
  11347. const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
  11348. window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
  11349. bool item_add = ItemAdd(bb, id);
  11350. window->DC.ItemFlags = item_flags_backup;
  11351. if (!item_add)
  11352. return false;
  11353. bool hovered, held;
  11354. ImRect bb_interact = bb;
  11355. bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
  11356. ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);
  11357. if (g.ActiveId != id)
  11358. SetItemAllowOverlap();
  11359. if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id))
  11360. SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
  11361. ImRect bb_render = bb;
  11362. if (held)
  11363. {
  11364. ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;
  11365. float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;
  11366. // Minimum pane size
  11367. if (mouse_delta < min_size1 - *size1)
  11368. mouse_delta = min_size1 - *size1;
  11369. if (mouse_delta > *size2 - min_size2)
  11370. mouse_delta = *size2 - min_size2;
  11371. // Apply resize
  11372. *size1 += mouse_delta;
  11373. *size2 -= mouse_delta;
  11374. bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
  11375. }
  11376. // Render
  11377. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  11378. window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding);
  11379. return held;
  11380. }
  11381. void ImGui::Spacing()
  11382. {
  11383. ImGuiWindow* window = GetCurrentWindow();
  11384. if (window->SkipItems)
  11385. return;
  11386. ItemSize(ImVec2(0,0));
  11387. }
  11388. void ImGui::Dummy(const ImVec2& size)
  11389. {
  11390. ImGuiWindow* window = GetCurrentWindow();
  11391. if (window->SkipItems)
  11392. return;
  11393. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  11394. ItemSize(bb);
  11395. ItemAdd(bb, 0);
  11396. }
  11397. bool ImGui::IsRectVisible(const ImVec2& size)
  11398. {
  11399. ImGuiWindow* window = GetCurrentWindowRead();
  11400. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  11401. }
  11402. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  11403. {
  11404. ImGuiWindow* window = GetCurrentWindowRead();
  11405. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  11406. }
  11407. // 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.)
  11408. void ImGui::BeginGroup()
  11409. {
  11410. ImGuiWindow* window = GetCurrentWindow();
  11411. window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
  11412. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  11413. group_data.BackupCursorPos = window->DC.CursorPos;
  11414. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  11415. group_data.BackupIndentX = window->DC.IndentX;
  11416. group_data.BackupGroupOffsetX = window->DC.GroupOffsetX;
  11417. group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
  11418. group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
  11419. group_data.BackupLogLinePosY = window->DC.LogLinePosY;
  11420. group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive;
  11421. group_data.AdvanceCursor = true;
  11422. window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX;
  11423. window->DC.IndentX = window->DC.GroupOffsetX;
  11424. window->DC.CursorMaxPos = window->DC.CursorPos;
  11425. window->DC.CurrentLineHeight = 0.0f;
  11426. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  11427. }
  11428. void ImGui::EndGroup()
  11429. {
  11430. ImGuiContext& g = *GImGui;
  11431. ImGuiWindow* window = GetCurrentWindow();
  11432. IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
  11433. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  11434. ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
  11435. group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
  11436. window->DC.CursorPos = group_data.BackupCursorPos;
  11437. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  11438. window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight;
  11439. window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
  11440. window->DC.IndentX = group_data.BackupIndentX;
  11441. window->DC.GroupOffsetX = group_data.BackupGroupOffsetX;
  11442. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  11443. if (group_data.AdvanceCursor)
  11444. {
  11445. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
  11446. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
  11447. ItemAdd(group_bb, 0);
  11448. }
  11449. // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will be functional on the entire group.
  11450. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context.
  11451. const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow);
  11452. if (active_id_within_group)
  11453. window->DC.LastItemId = g.ActiveId;
  11454. window->DC.LastItemRect = group_bb;
  11455. window->DC.GroupStack.pop_back();
  11456. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  11457. }
  11458. // Gets back to previous line and continue with horizontal layout
  11459. // pos_x == 0 : follow right after previous item
  11460. // pos_x != 0 : align to specified x position (relative to window/group left)
  11461. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  11462. // spacing_w >= 0 : enforce spacing amount
  11463. void ImGui::SameLine(float pos_x, float spacing_w)
  11464. {
  11465. ImGuiWindow* window = GetCurrentWindow();
  11466. if (window->SkipItems)
  11467. return;
  11468. ImGuiContext& g = *GImGui;
  11469. if (pos_x != 0.0f)
  11470. {
  11471. if (spacing_w < 0.0f) spacing_w = 0.0f;
  11472. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX;
  11473. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  11474. }
  11475. else
  11476. {
  11477. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  11478. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  11479. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  11480. }
  11481. window->DC.CurrentLineHeight = window->DC.PrevLineHeight;
  11482. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  11483. }
  11484. void ImGui::NewLine()
  11485. {
  11486. ImGuiWindow* window = GetCurrentWindow();
  11487. if (window->SkipItems)
  11488. return;
  11489. ImGuiContext& g = *GImGui;
  11490. const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
  11491. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  11492. if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
  11493. ItemSize(ImVec2(0,0));
  11494. else
  11495. ItemSize(ImVec2(0.0f, g.FontSize));
  11496. window->DC.LayoutType = backup_layout_type;
  11497. }
  11498. void ImGui::NextColumn()
  11499. {
  11500. ImGuiWindow* window = GetCurrentWindow();
  11501. if (window->SkipItems || window->DC.ColumnsSet == NULL)
  11502. return;
  11503. ImGuiContext& g = *GImGui;
  11504. PopItemWidth();
  11505. PopClipRect();
  11506. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  11507. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  11508. if (++columns->Current < columns->Count)
  11509. {
  11510. // Columns 1+ cancel out IndentX
  11511. window->DC.ColumnsOffsetX = GetColumnOffset(columns->Current) - window->DC.IndentX + g.Style.ItemSpacing.x;
  11512. window->DrawList->ChannelsSetCurrent(columns->Current);
  11513. }
  11514. else
  11515. {
  11516. window->DC.ColumnsOffsetX = 0.0f;
  11517. window->DrawList->ChannelsSetCurrent(0);
  11518. columns->Current = 0;
  11519. columns->LineMinY = columns->LineMaxY;
  11520. }
  11521. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  11522. window->DC.CursorPos.y = columns->LineMinY;
  11523. window->DC.CurrentLineHeight = 0.0f;
  11524. window->DC.CurrentLineTextBaseOffset = 0.0f;
  11525. PushColumnClipRect();
  11526. PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
  11527. }
  11528. int ImGui::GetColumnIndex()
  11529. {
  11530. ImGuiWindow* window = GetCurrentWindowRead();
  11531. return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0;
  11532. }
  11533. int ImGui::GetColumnsCount()
  11534. {
  11535. ImGuiWindow* window = GetCurrentWindowRead();
  11536. return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1;
  11537. }
  11538. static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm)
  11539. {
  11540. return offset_norm * (columns->MaxX - columns->MinX);
  11541. }
  11542. static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset)
  11543. {
  11544. return offset / (columns->MaxX - columns->MinX);
  11545. }
  11546. static inline float GetColumnsRectHalfWidth() { return 4.0f; }
  11547. static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
  11548. {
  11549. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  11550. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  11551. ImGuiContext& g = *GImGui;
  11552. ImGuiWindow* window = g.CurrentWindow;
  11553. IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
  11554. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
  11555. float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
  11556. x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
  11557. if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
  11558. x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
  11559. return x;
  11560. }
  11561. float ImGui::GetColumnOffset(int column_index)
  11562. {
  11563. ImGuiWindow* window = GetCurrentWindowRead();
  11564. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  11565. IM_ASSERT(columns != NULL);
  11566. if (column_index < 0)
  11567. column_index = columns->Current;
  11568. IM_ASSERT(column_index < columns->Columns.Size);
  11569. const float t = columns->Columns[column_index].OffsetNorm;
  11570. const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
  11571. return x_offset;
  11572. }
  11573. static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false)
  11574. {
  11575. if (column_index < 0)
  11576. column_index = columns->Current;
  11577. float offset_norm;
  11578. if (before_resize)
  11579. offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
  11580. else
  11581. offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
  11582. return OffsetNormToPixels(columns, offset_norm);
  11583. }
  11584. float ImGui::GetColumnWidth(int column_index)
  11585. {
  11586. ImGuiWindow* window = GetCurrentWindowRead();
  11587. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  11588. IM_ASSERT(columns != NULL);
  11589. if (column_index < 0)
  11590. column_index = columns->Current;
  11591. return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
  11592. }
  11593. void ImGui::SetColumnOffset(int column_index, float offset)
  11594. {
  11595. ImGuiContext& g = *GImGui;
  11596. ImGuiWindow* window = g.CurrentWindow;
  11597. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  11598. IM_ASSERT(columns != NULL);
  11599. if (column_index < 0)
  11600. column_index = columns->Current;
  11601. IM_ASSERT(column_index < columns->Columns.Size);
  11602. const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
  11603. const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
  11604. if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
  11605. offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
  11606. columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX);
  11607. if (preserve_width)
  11608. SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
  11609. }
  11610. void ImGui::SetColumnWidth(int column_index, float width)
  11611. {
  11612. ImGuiWindow* window = GetCurrentWindowRead();
  11613. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  11614. IM_ASSERT(columns != NULL);
  11615. if (column_index < 0)
  11616. column_index = columns->Current;
  11617. SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
  11618. }
  11619. void ImGui::PushColumnClipRect(int column_index)
  11620. {
  11621. ImGuiWindow* window = GetCurrentWindowRead();
  11622. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  11623. if (column_index < 0)
  11624. column_index = columns->Current;
  11625. PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false);
  11626. }
  11627. static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id)
  11628. {
  11629. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  11630. if (window->ColumnsStorage[n].ID == id)
  11631. return &window->ColumnsStorage[n];
  11632. window->ColumnsStorage.push_back(ImGuiColumnsSet());
  11633. ImGuiColumnsSet* columns = &window->ColumnsStorage.back();
  11634. columns->ID = id;
  11635. return columns;
  11636. }
  11637. void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
  11638. {
  11639. ImGuiContext& g = *GImGui;
  11640. ImGuiWindow* window = GetCurrentWindow();
  11641. IM_ASSERT(columns_count > 1);
  11642. IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported
  11643. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  11644. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  11645. PushID(0x11223347 + (str_id ? 0 : columns_count));
  11646. ImGuiID id = window->GetID(str_id ? str_id : "columns");
  11647. PopID();
  11648. // Acquire storage for the columns set
  11649. ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id);
  11650. IM_ASSERT(columns->ID == id);
  11651. columns->Current = 0;
  11652. columns->Count = columns_count;
  11653. columns->Flags = flags;
  11654. window->DC.ColumnsSet = columns;
  11655. // Set state for first column
  11656. const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x);
  11657. columns->MinX = window->DC.IndentX - g.Style.ItemSpacing.x; // Lock our horizontal range
  11658. columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f);
  11659. columns->StartPosY = window->DC.CursorPos.y;
  11660. columns->StartMaxPosX = window->DC.CursorMaxPos.x;
  11661. columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
  11662. window->DC.ColumnsOffsetX = 0.0f;
  11663. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  11664. // Clear data if columns count changed
  11665. if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
  11666. columns->Columns.resize(0);
  11667. // Initialize defaults
  11668. columns->IsFirstFrame = (columns->Columns.Size == 0);
  11669. if (columns->Columns.Size == 0)
  11670. {
  11671. columns->Columns.reserve(columns_count + 1);
  11672. for (int n = 0; n < columns_count + 1; n++)
  11673. {
  11674. ImGuiColumnData column;
  11675. column.OffsetNorm = n / (float)columns_count;
  11676. columns->Columns.push_back(column);
  11677. }
  11678. }
  11679. for (int n = 0; n < columns_count; n++)
  11680. {
  11681. // Compute clipping rectangle
  11682. ImGuiColumnData* column = &columns->Columns[n];
  11683. float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
  11684. float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
  11685. column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
  11686. column->ClipRect.ClipWith(window->ClipRect);
  11687. }
  11688. window->DrawList->ChannelsSplit(columns->Count);
  11689. PushColumnClipRect();
  11690. PushItemWidth(GetColumnWidth() * 0.65f);
  11691. }
  11692. void ImGui::EndColumns()
  11693. {
  11694. ImGuiContext& g = *GImGui;
  11695. ImGuiWindow* window = GetCurrentWindow();
  11696. ImGuiColumnsSet* columns = window->DC.ColumnsSet;
  11697. IM_ASSERT(columns != NULL);
  11698. PopItemWidth();
  11699. PopClipRect();
  11700. window->DrawList->ChannelsMerge();
  11701. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  11702. window->DC.CursorPos.y = columns->LineMaxY;
  11703. if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
  11704. window->DC.CursorMaxPos.x = ImMax(columns->StartMaxPosX, columns->MaxX); // Restore cursor max pos, as columns don't grow parent
  11705. // Draw columns borders and handle resize
  11706. bool is_being_resized = false;
  11707. if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
  11708. {
  11709. const float y1 = columns->StartPosY;
  11710. const float y2 = window->DC.CursorPos.y;
  11711. int dragging_column = -1;
  11712. for (int n = 1; n < columns->Count; n++)
  11713. {
  11714. float x = window->Pos.x + GetColumnOffset(n);
  11715. const ImGuiID column_id = columns->ID + ImGuiID(n);
  11716. const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction
  11717. const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2));
  11718. KeepAliveID(column_id);
  11719. if (IsClippedEx(column_rect, column_id, false))
  11720. continue;
  11721. bool hovered = false, held = false;
  11722. if (!(columns->Flags & ImGuiColumnsFlags_NoResize))
  11723. {
  11724. ButtonBehavior(column_rect, column_id, &hovered, &held);
  11725. if (hovered || held)
  11726. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  11727. if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize))
  11728. dragging_column = n;
  11729. }
  11730. // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.)
  11731. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  11732. const float xi = (float)(int)x;
  11733. window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col);
  11734. }
  11735. // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
  11736. if (dragging_column != -1)
  11737. {
  11738. if (!columns->IsBeingResized)
  11739. for (int n = 0; n < columns->Count + 1; n++)
  11740. columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
  11741. columns->IsBeingResized = is_being_resized = true;
  11742. float x = GetDraggedColumnOffset(columns, dragging_column);
  11743. SetColumnOffset(dragging_column, x);
  11744. }
  11745. }
  11746. columns->IsBeingResized = is_being_resized;
  11747. window->DC.ColumnsSet = NULL;
  11748. window->DC.ColumnsOffsetX = 0.0f;
  11749. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  11750. }
  11751. // [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
  11752. void ImGui::Columns(int columns_count, const char* id, bool border)
  11753. {
  11754. ImGuiWindow* window = GetCurrentWindow();
  11755. IM_ASSERT(columns_count >= 1);
  11756. if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count != columns_count)
  11757. EndColumns();
  11758. ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
  11759. //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
  11760. if (columns_count != 1)
  11761. BeginColumns(id, columns_count, flags);
  11762. }
  11763. void ImGui::Indent(float indent_w)
  11764. {
  11765. ImGuiContext& g = *GImGui;
  11766. ImGuiWindow* window = GetCurrentWindow();
  11767. window->DC.IndentX += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  11768. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  11769. }
  11770. void ImGui::Unindent(float indent_w)
  11771. {
  11772. ImGuiContext& g = *GImGui;
  11773. ImGuiWindow* window = GetCurrentWindow();
  11774. window->DC.IndentX -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
  11775. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  11776. }
  11777. void ImGui::TreePush(const char* str_id)
  11778. {
  11779. ImGuiWindow* window = GetCurrentWindow();
  11780. Indent();
  11781. window->DC.TreeDepth++;
  11782. PushID(str_id ? str_id : "#TreePush");
  11783. }
  11784. void ImGui::TreePush(const void* ptr_id)
  11785. {
  11786. ImGuiWindow* window = GetCurrentWindow();
  11787. Indent();
  11788. window->DC.TreeDepth++;
  11789. PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
  11790. }
  11791. void ImGui::TreePushRawID(ImGuiID id)
  11792. {
  11793. ImGuiWindow* window = GetCurrentWindow();
  11794. Indent();
  11795. window->DC.TreeDepth++;
  11796. window->IDStack.push_back(id);
  11797. }
  11798. void ImGui::TreePop()
  11799. {
  11800. ImGuiContext& g = *GImGui;
  11801. ImGuiWindow* window = g.CurrentWindow;
  11802. Unindent();
  11803. window->DC.TreeDepth--;
  11804. if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
  11805. if (g.NavIdIsAlive && (window->DC.TreeDepthMayJumpToParentOnPop & (1 << window->DC.TreeDepth)))
  11806. {
  11807. SetNavID(window->IDStack.back(), g.NavLayer);
  11808. NavMoveRequestCancel();
  11809. }
  11810. window->DC.TreeDepthMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1;
  11811. PopID();
  11812. }
  11813. void ImGui::Value(const char* prefix, bool b)
  11814. {
  11815. Text("%s: %s", prefix, (b ? "true" : "false"));
  11816. }
  11817. void ImGui::Value(const char* prefix, int v)
  11818. {
  11819. Text("%s: %d", prefix, v);
  11820. }
  11821. void ImGui::Value(const char* prefix, unsigned int v)
  11822. {
  11823. Text("%s: %d", prefix, v);
  11824. }
  11825. void ImGui::Value(const char* prefix, float v, const char* float_format)
  11826. {
  11827. if (float_format)
  11828. {
  11829. char fmt[64];
  11830. ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
  11831. Text(fmt, prefix, v);
  11832. }
  11833. else
  11834. {
  11835. Text("%s: %.3f", prefix, v);
  11836. }
  11837. }
  11838. //-----------------------------------------------------------------------------
  11839. // DRAG AND DROP
  11840. //-----------------------------------------------------------------------------
  11841. void ImGui::ClearDragDrop()
  11842. {
  11843. ImGuiContext& g = *GImGui;
  11844. g.DragDropActive = false;
  11845. g.DragDropPayload.Clear();
  11846. g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
  11847. g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
  11848. g.DragDropAcceptFrameCount = -1;
  11849. }
  11850. // Call when current ID is active.
  11851. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
  11852. bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
  11853. {
  11854. ImGuiContext& g = *GImGui;
  11855. ImGuiWindow* window = g.CurrentWindow;
  11856. bool source_drag_active = false;
  11857. ImGuiID source_id = 0;
  11858. ImGuiID source_parent_id = 0;
  11859. int mouse_button = 0;
  11860. if (!(flags & ImGuiDragDropFlags_SourceExtern))
  11861. {
  11862. source_id = window->DC.LastItemId;
  11863. if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
  11864. return false;
  11865. if (g.IO.MouseDown[mouse_button] == false)
  11866. return false;
  11867. if (source_id == 0)
  11868. {
  11869. // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
  11870. // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
  11871. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
  11872. {
  11873. IM_ASSERT(0);
  11874. return false;
  11875. }
  11876. // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
  11877. // We build a throwaway ID based on current ID stack + relative AABB of items in window.
  11878. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
  11879. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
  11880. bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0;
  11881. if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
  11882. return false;
  11883. source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
  11884. if (is_hovered)
  11885. SetHoveredID(source_id);
  11886. if (is_hovered && g.IO.MouseClicked[mouse_button])
  11887. {
  11888. SetActiveID(source_id, window);
  11889. FocusWindow(window);
  11890. }
  11891. if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
  11892. g.ActiveIdAllowOverlap = is_hovered;
  11893. }
  11894. if (g.ActiveId != source_id)
  11895. return false;
  11896. source_parent_id = window->IDStack.back();
  11897. source_drag_active = IsMouseDragging(mouse_button);
  11898. }
  11899. else
  11900. {
  11901. window = NULL;
  11902. source_id = ImHash("#SourceExtern", 0);
  11903. source_drag_active = true;
  11904. }
  11905. if (source_drag_active)
  11906. {
  11907. if (!g.DragDropActive)
  11908. {
  11909. IM_ASSERT(source_id != 0);
  11910. ClearDragDrop();
  11911. ImGuiPayload& payload = g.DragDropPayload;
  11912. payload.SourceId = source_id;
  11913. payload.SourceParentId = source_parent_id;
  11914. g.DragDropActive = true;
  11915. g.DragDropSourceFlags = flags;
  11916. g.DragDropMouseButton = mouse_button;
  11917. }
  11918. if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  11919. {
  11920. // FIXME-DRAG
  11921. //SetNextWindowPos(g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding);
  11922. //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This is better but e.g ColorButton with checkboard has issue with transparent colors :(
  11923. SetNextWindowPos(g.IO.MousePos);
  11924. PushStyleColor(ImGuiCol_PopupBg, GetStyleColorVec4(ImGuiCol_PopupBg) * ImVec4(1.0f, 1.0f, 1.0f, 0.6f));
  11925. BeginTooltip();
  11926. }
  11927. if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
  11928. window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
  11929. return true;
  11930. }
  11931. return false;
  11932. }
  11933. void ImGui::EndDragDropSource()
  11934. {
  11935. ImGuiContext& g = *GImGui;
  11936. IM_ASSERT(g.DragDropActive);
  11937. if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
  11938. {
  11939. EndTooltip();
  11940. PopStyleColor();
  11941. //PopStyleVar();
  11942. }
  11943. // Discard the drag if have not called SetDragDropPayload()
  11944. if (g.DragDropPayload.DataFrameCount == -1)
  11945. ClearDragDrop();
  11946. }
  11947. // Use 'cond' to choose to submit payload on drag start or every frame
  11948. bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
  11949. {
  11950. ImGuiContext& g = *GImGui;
  11951. ImGuiPayload& payload = g.DragDropPayload;
  11952. if (cond == 0)
  11953. cond = ImGuiCond_Always;
  11954. IM_ASSERT(type != NULL);
  11955. IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 12 characters long");
  11956. IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
  11957. IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
  11958. IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
  11959. if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
  11960. {
  11961. // Copy payload
  11962. ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
  11963. g.DragDropPayloadBufHeap.resize(0);
  11964. if (data_size > sizeof(g.DragDropPayloadBufLocal))
  11965. {
  11966. // Store in heap
  11967. g.DragDropPayloadBufHeap.resize((int)data_size);
  11968. payload.Data = g.DragDropPayloadBufHeap.Data;
  11969. memcpy((void*)payload.Data, data, data_size);
  11970. }
  11971. else if (data_size > 0)
  11972. {
  11973. // Store locally
  11974. memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
  11975. payload.Data = g.DragDropPayloadBufLocal;
  11976. memcpy((void*)payload.Data, data, data_size);
  11977. }
  11978. else
  11979. {
  11980. payload.Data = NULL;
  11981. }
  11982. payload.DataSize = (int)data_size;
  11983. }
  11984. payload.DataFrameCount = g.FrameCount;
  11985. return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
  11986. }
  11987. bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
  11988. {
  11989. ImGuiContext& g = *GImGui;
  11990. if (!g.DragDropActive)
  11991. return false;
  11992. ImGuiWindow* window = g.CurrentWindow;
  11993. if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
  11994. return false;
  11995. IM_ASSERT(id != 0);
  11996. if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
  11997. return false;
  11998. g.DragDropTargetRect = bb;
  11999. g.DragDropTargetId = id;
  12000. return true;
  12001. }
  12002. // We don't use BeginDragDropTargetCustom() and duplicate its code because:
  12003. // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
  12004. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
  12005. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
  12006. bool ImGui::BeginDragDropTarget()
  12007. {
  12008. ImGuiContext& g = *GImGui;
  12009. if (!g.DragDropActive)
  12010. return false;
  12011. ImGuiWindow* window = g.CurrentWindow;
  12012. if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
  12013. return false;
  12014. if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
  12015. return false;
  12016. const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
  12017. ImGuiID id = window->DC.LastItemId;
  12018. if (id == 0)
  12019. id = window->GetIDFromRectangle(display_rect);
  12020. if (g.DragDropPayload.SourceId == id)
  12021. return false;
  12022. g.DragDropTargetRect = display_rect;
  12023. g.DragDropTargetId = id;
  12024. return true;
  12025. }
  12026. bool ImGui::IsDragDropPayloadBeingAccepted()
  12027. {
  12028. ImGuiContext& g = *GImGui;
  12029. return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
  12030. }
  12031. const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
  12032. {
  12033. ImGuiContext& g = *GImGui;
  12034. ImGuiWindow* window = g.CurrentWindow;
  12035. ImGuiPayload& payload = g.DragDropPayload;
  12036. IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
  12037. IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
  12038. if (type != NULL && !payload.IsDataType(type))
  12039. return NULL;
  12040. // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
  12041. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
  12042. const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
  12043. ImRect r = g.DragDropTargetRect;
  12044. float r_surface = r.GetWidth() * r.GetHeight();
  12045. if (r_surface < g.DragDropAcceptIdCurrRectSurface)
  12046. {
  12047. g.DragDropAcceptIdCurr = g.DragDropTargetId;
  12048. g.DragDropAcceptIdCurrRectSurface = r_surface;
  12049. }
  12050. // Render default drop visuals
  12051. payload.Preview = was_accepted_previously;
  12052. flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
  12053. if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
  12054. {
  12055. // FIXME-DRAG: Settle on a proper default visuals for drop target.
  12056. r.Expand(3.5f);
  12057. bool push_clip_rect = !window->ClipRect.Contains(r);
  12058. if (push_clip_rect) window->DrawList->PushClipRect(r.Min, r.Max);
  12059. window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
  12060. if (push_clip_rect) window->DrawList->PopClipRect();
  12061. }
  12062. g.DragDropAcceptFrameCount = g.FrameCount;
  12063. 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()
  12064. if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
  12065. return NULL;
  12066. return &payload;
  12067. }
  12068. // We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
  12069. void ImGui::EndDragDropTarget()
  12070. {
  12071. ImGuiContext& g = *GImGui; (void)g;
  12072. IM_ASSERT(g.DragDropActive);
  12073. }
  12074. //-----------------------------------------------------------------------------
  12075. // PLATFORM DEPENDENT HELPERS
  12076. //-----------------------------------------------------------------------------
  12077. #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
  12078. #undef WIN32_LEAN_AND_MEAN
  12079. #define WIN32_LEAN_AND_MEAN
  12080. #ifndef __MINGW32__
  12081. #include <Windows.h>
  12082. #else
  12083. #include <windows.h>
  12084. #endif
  12085. #endif
  12086. // Win32 API clipboard implementation
  12087. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
  12088. #ifdef _MSC_VER
  12089. #pragma comment(lib, "user32")
  12090. #endif
  12091. static const char* GetClipboardTextFn_DefaultImpl(void*)
  12092. {
  12093. static ImVector<char> buf_local;
  12094. buf_local.clear();
  12095. if (!OpenClipboard(NULL))
  12096. return NULL;
  12097. HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
  12098. if (wbuf_handle == NULL)
  12099. {
  12100. CloseClipboard();
  12101. return NULL;
  12102. }
  12103. if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
  12104. {
  12105. int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
  12106. buf_local.resize(buf_len);
  12107. ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
  12108. }
  12109. GlobalUnlock(wbuf_handle);
  12110. CloseClipboard();
  12111. return buf_local.Data;
  12112. }
  12113. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  12114. {
  12115. if (!OpenClipboard(NULL))
  12116. return;
  12117. const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
  12118. HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
  12119. if (wbuf_handle == NULL)
  12120. {
  12121. CloseClipboard();
  12122. return;
  12123. }
  12124. ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
  12125. ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
  12126. GlobalUnlock(wbuf_handle);
  12127. EmptyClipboard();
  12128. SetClipboardData(CF_UNICODETEXT, wbuf_handle);
  12129. CloseClipboard();
  12130. }
  12131. #else
  12132. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  12133. static const char* GetClipboardTextFn_DefaultImpl(void*)
  12134. {
  12135. ImGuiContext& g = *GImGui;
  12136. return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
  12137. }
  12138. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  12139. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  12140. {
  12141. ImGuiContext& g = *GImGui;
  12142. g.PrivateClipboard.clear();
  12143. const char* text_end = text + strlen(text);
  12144. g.PrivateClipboard.resize((int)(text_end - text) + 1);
  12145. memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
  12146. g.PrivateClipboard[(int)(text_end - text)] = 0;
  12147. }
  12148. #endif
  12149. // Win32 API IME support (for Asian languages, etc.)
  12150. #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  12151. #include <imm.h>
  12152. #ifdef _MSC_VER
  12153. #pragma comment(lib, "imm32")
  12154. #endif
  12155. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
  12156. {
  12157. // Notify OS Input Method Editor of text input position
  12158. if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
  12159. if (HIMC himc = ImmGetContext(hwnd))
  12160. {
  12161. COMPOSITIONFORM cf;
  12162. cf.ptCurrentPos.x = x;
  12163. cf.ptCurrentPos.y = y;
  12164. cf.dwStyle = CFS_FORCE_POSITION;
  12165. ImmSetCompositionWindow(himc, &cf);
  12166. }
  12167. }
  12168. #else
  12169. static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
  12170. #endif
  12171. //-----------------------------------------------------------------------------
  12172. // HELP
  12173. //-----------------------------------------------------------------------------
  12174. static void RenderViewportThumbnail(ImDrawList* draw_list, const ImRect& bb, const ImVec2& viewport_pos, const ImVec2& viewport_size)
  12175. {
  12176. ImGuiContext& g = *GImGui;
  12177. ImGuiWindow* window = g.CurrentWindow;
  12178. ImRect viewport_r(viewport_pos, viewport_pos + viewport_size);
  12179. ImVec2 scale = bb.GetSize() / viewport_size;
  12180. for (int i = 0; i != g.Windows.Size; i++)
  12181. {
  12182. ImGuiWindow* thumb_window = g.Windows[i];
  12183. if (!thumb_window->WasActive || ((thumb_window->Flags & ImGuiWindowFlags_ChildWindow)))
  12184. continue;
  12185. if (thumb_window->SkipItems && (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME-DOCK: Skip hidden docked windows. Identify those betters.
  12186. continue;
  12187. if (!viewport_r.Overlaps(thumb_window->WindowRectClipped))
  12188. continue;
  12189. ImRect thumb_r = thumb_window->Rect();
  12190. ImRect title_r = thumb_window->TitleBarRect();
  12191. ImRect thumb_r_scaled = ImRect(ImFloor(bb.Min + (thumb_r.Min - viewport_pos) * scale), ImFloor(bb.Min + (thumb_r.Max - viewport_pos) * scale));
  12192. ImRect title_r_scaled = ImRect(ImFloor(bb.Min + (title_r.Min - viewport_pos) * scale), ImFloor(bb.Min + (title_r.Max - viewport_pos) * scale));
  12193. thumb_r_scaled.ClipWithFull(bb);
  12194. title_r_scaled.ClipWithFull(bb);
  12195. const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
  12196. window->DrawList->AddRectFilled(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_WindowBg));
  12197. window->DrawList->AddRectFilled(title_r_scaled.Min, title_r_scaled.Max, ImGui::GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg));
  12198. window->DrawList->AddRect(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_Border));
  12199. }
  12200. draw_list->AddRect(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border));
  12201. }
  12202. static void ScaleWindow(ImGuiWindow* window, float scale)
  12203. {
  12204. ImVec2 origin = window->Viewport->Pos;
  12205. window->Pos = window->PosFloat = ImFloor((window->PosFloat - origin) * scale + origin);
  12206. window->Size = ImFloor(window->Size * scale);
  12207. window->SizeFull = ImFloor(window->SizeFull * scale);
  12208. window->SizeContents = ImFloor(window->SizeContents * scale);
  12209. }
  12210. // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
  12211. void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
  12212. {
  12213. ImGuiContext& g = *GImGui;
  12214. if (g.IO.MousePosViewport == viewport->ID)
  12215. {
  12216. //g.IO.MousePos = g.IO.MousePosPrev = ImFloor((g.IO.MousePos - viewport->Pos) * scale) + viewport->Pos;
  12217. //g.IO.MouseDelta = ImVec2(0,0);
  12218. }
  12219. if (viewport->Window)
  12220. {
  12221. ScaleWindow(viewport->Window, scale);
  12222. }
  12223. else
  12224. {
  12225. for (int i = 0; i != g.Windows.Size; i++)
  12226. if (g.Windows[i]->Viewport == viewport)
  12227. ScaleWindow(g.Windows[i], scale);
  12228. }
  12229. }
  12230. void ImGui::ShowViewportThumbnails()
  12231. {
  12232. ImGuiContext& g = *GImGui;
  12233. ImGuiWindow* window = g.CurrentWindow;
  12234. float SCALE = 1.0f / 7.0f;
  12235. ImGui::NewLine(); // For labels
  12236. ImVec2 p = window->DC.CursorPos;
  12237. for (int n = 0; n < g.Viewports.Size; n++)
  12238. {
  12239. ImGuiViewportP* viewport = g.Viewports[n];
  12240. if (n > 0)
  12241. ImGui::SameLine();
  12242. ImRect bb(p + (viewport->Pos) * SCALE, p + (viewport->Pos + viewport->Size) * SCALE);
  12243. window->DrawList->AddRect(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border));
  12244. RenderViewportThumbnail(window->DrawList, bb, viewport->Pos, viewport->Size);
  12245. char buf[64];
  12246. ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f", viewport->Pos.x);
  12247. ImGui::RenderText(bb.Min + ImVec2(1, -g.FontSize), buf, NULL, false);
  12248. ImGui::Dummy(bb.GetSize());
  12249. }
  12250. }
  12251. void ImGui::ShowMetricsWindow(bool* p_open)
  12252. {
  12253. if (ImGui::Begin("ImGui Metrics", p_open))
  12254. {
  12255. ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
  12256. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  12257. ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
  12258. ImGui::Text("%d allocations", (int)GImAllocatorActiveAllocationsCount);
  12259. static bool show_clip_rects = true;
  12260. static bool show_window_begin_order = false;
  12261. ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_clip_rects);
  12262. ImGui::Checkbox("Show window begin order", &show_window_begin_order);
  12263. ImGui::Separator();
  12264. struct Funcs
  12265. {
  12266. static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
  12267. {
  12268. 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);
  12269. if (draw_list == ImGui::GetWindowDrawList())
  12270. {
  12271. ImGui::SameLine();
  12272. ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  12273. if (node_open) ImGui::TreePop();
  12274. return;
  12275. }
  12276. ImDrawList* overlay_draw_list = ImGui::GetOverlayDrawList(); // Render additional visuals into the top-most draw list
  12277. if (window && ImGui::IsItemHovered())
  12278. overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
  12279. if (!node_open)
  12280. return;
  12281. int elem_offset = 0;
  12282. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
  12283. {
  12284. if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
  12285. continue;
  12286. if (pcmd->UserCallback)
  12287. {
  12288. ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  12289. continue;
  12290. }
  12291. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  12292. bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  12293. if (show_clip_rects && ImGui::IsItemHovered())
  12294. {
  12295. ImRect clip_rect = pcmd->ClipRect;
  12296. ImRect vtxs_rect;
  12297. for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
  12298. vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
  12299. clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
  12300. vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
  12301. }
  12302. if (!pcmd_node_open)
  12303. continue;
  12304. // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
  12305. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  12306. while (clipper.Step())
  12307. for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
  12308. {
  12309. char buf[300];
  12310. char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
  12311. ImVec2 triangles_pos[3];
  12312. for (int n = 0; n < 3; n++, vtx_i++)
  12313. {
  12314. ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
  12315. triangles_pos[n] = v.pos;
  12316. buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  12317. }
  12318. ImGui::Selectable(buf, false);
  12319. if (ImGui::IsItemHovered())
  12320. {
  12321. ImDrawListFlags backup_flags = overlay_draw_list->Flags;
  12322. overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
  12323. overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
  12324. overlay_draw_list->Flags = backup_flags;
  12325. }
  12326. }
  12327. ImGui::TreePop();
  12328. }
  12329. ImGui::TreePop();
  12330. }
  12331. static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
  12332. {
  12333. if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
  12334. return;
  12335. for (int i = 0; i < windows.Size; i++)
  12336. Funcs::NodeWindow(windows[i], "Window");
  12337. ImGui::TreePop();
  12338. }
  12339. static void NodeWindow(ImGuiWindow* window, const char* label)
  12340. {
  12341. if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
  12342. return;
  12343. ImGuiWindowFlags flags = window->Flags;
  12344. NodeDrawList(window, window->DrawList, "DrawList");
  12345. ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
  12346. ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s..)", flags,
  12347. (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
  12348. (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "");
  12349. ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetScrollMaxX(window), window->Scroll.y, GetScrollMaxY(window));
  12350. ImGui::BulletText("Active: %d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
  12351. ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
  12352. ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
  12353. if (window->NavRectRel[0].IsInverted())
  12354. 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);
  12355. else
  12356. ImGui::BulletText("NavRectRel[0]: <None>");
  12357. ImGui::BulletText("Viewport: %d, ViewportId: 0x%08X", window->Viewport ? window->Viewport->Idx : -1, window->ViewportId);
  12358. if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
  12359. if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
  12360. if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
  12361. {
  12362. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  12363. {
  12364. const ImGuiColumnsSet* columns = &window->ColumnsStorage[n];
  12365. if (ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
  12366. {
  12367. ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX);
  12368. for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
  12369. ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm));
  12370. ImGui::TreePop();
  12371. }
  12372. }
  12373. ImGui::TreePop();
  12374. }
  12375. ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
  12376. ImGui::TreePop();
  12377. }
  12378. };
  12379. // Access private state, we are going to display the draw lists from last frame
  12380. ImGuiContext& g = *GImGui;
  12381. Funcs::NodeWindows(g.Windows, "Windows");
  12382. if (ImGui::TreeNode("Viewport", "Viewports (%d)", g.Viewports.Size))
  12383. {
  12384. ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
  12385. ImGui::ShowViewportThumbnails();
  12386. ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
  12387. for (int i = 0; i < g.Viewports.Size; i++)
  12388. {
  12389. ImGuiViewportP* viewport = g.Viewports[i];
  12390. ImGui::SetNextTreeNodeOpen(true, ImGuiCond_Once);
  12391. if (ImGui::TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Size: (%.0f,%.0f)", i, viewport->ID, viewport->Size.x, viewport->Size.y))
  12392. {
  12393. ImGuiWindowFlags flags = viewport->Flags;
  12394. ImGui::BulletText("Pos: (%.0f,%.0f), PlatformPos: (%.0f,%.0f)", viewport->Pos.x, viewport->Pos.y, viewport->PlatformPos.x, viewport->PlatformPos.y);
  12395. if (i > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Reset")) viewport->PlatformPos = ImVec2(0, 0); }
  12396. ImGui::BulletText("DpiScale: %.0f%%", viewport->DpiScale * 100.0f);
  12397. ImGui::BulletText("Flags: 0x%04X =%s%s%s%s", viewport->Flags,
  12398. (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
  12399. (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
  12400. (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "");
  12401. for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
  12402. for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
  12403. Funcs::NodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
  12404. ImGui::TreePop();
  12405. }
  12406. }
  12407. ImGui::TreePop();
  12408. }
  12409. if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size))
  12410. {
  12411. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  12412. {
  12413. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  12414. 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" : "");
  12415. }
  12416. ImGui::TreePop();
  12417. }
  12418. if (ImGui::TreeNode("Internal state"))
  12419. {
  12420. const char* input_source_names[] = { "None", "Mouse", "Nav", "NavGamepad", "NavKeyboard" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
  12421. ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  12422. ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
  12423. ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec)", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
  12424. ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), ActiveIdSource: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, input_source_names[g.ActiveIdSource]);
  12425. ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  12426. ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  12427. ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
  12428. ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
  12429. ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
  12430. ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
  12431. ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
  12432. ImGui::TreePop();
  12433. }
  12434. if (show_window_begin_order)
  12435. {
  12436. for (int n = 0; n < g.Windows.Size; n++)
  12437. {
  12438. ImGuiWindow* window = g.Windows[n];
  12439. if ((window->Flags & ImGuiWindowFlags_ChildWindow) || !window->WasActive)
  12440. continue;
  12441. char buf[32];
  12442. ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
  12443. float font_size = ImGui::GetFontSize() * 2;
  12444. g.OverlayDrawList.AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
  12445. g.OverlayDrawList.AddText(NULL, font_size, window->Pos, IM_COL32(255, 255, 255, 255), buf);
  12446. }
  12447. }
  12448. }
  12449. ImGui::End();
  12450. }
  12451. //-----------------------------------------------------------------------------
  12452. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  12453. // 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.
  12454. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  12455. #include "imgui_user.inl"
  12456. #endif
  12457. //-----------------------------------------------------------------------------