editor_node.cpp 308 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136
  1. /**************************************************************************/
  2. /* editor_node.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "editor_node.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/extension/gdextension_manager.h"
  33. #include "core/input/input.h"
  34. #include "core/io/config_file.h"
  35. #include "core/io/file_access.h"
  36. #include "core/io/image.h"
  37. #include "core/io/resource_loader.h"
  38. #include "core/io/resource_saver.h"
  39. #include "core/object/class_db.h"
  40. #include "core/os/keyboard.h"
  41. #include "core/os/os.h"
  42. #include "core/os/time.h"
  43. #include "core/string/print_string.h"
  44. #include "core/string/translation_server.h"
  45. #include "core/version.h"
  46. #include "editor/editor_string_names.h"
  47. #include "editor/plugins/editor_context_menu_plugin.h"
  48. #include "main/main.h"
  49. #include "scene/2d/node_2d.h"
  50. #include "scene/3d/bone_attachment_3d.h"
  51. #include "scene/animation/animation_tree.h"
  52. #include "scene/gui/color_picker.h"
  53. #include "scene/gui/dialogs.h"
  54. #include "scene/gui/file_dialog.h"
  55. #include "scene/gui/menu_bar.h"
  56. #include "scene/gui/menu_button.h"
  57. #include "scene/gui/panel.h"
  58. #include "scene/gui/popup.h"
  59. #include "scene/gui/rich_text_label.h"
  60. #include "scene/gui/split_container.h"
  61. #include "scene/gui/tab_container.h"
  62. #include "scene/main/window.h"
  63. #include "scene/property_utils.h"
  64. #include "scene/resources/image_texture.h"
  65. #include "scene/resources/packed_scene.h"
  66. #include "scene/resources/portable_compressed_texture.h"
  67. #include "scene/theme/theme_db.h"
  68. #include "servers/display_server.h"
  69. #include "servers/navigation_server_3d.h"
  70. #include "servers/physics_server_2d.h"
  71. #include "servers/rendering_server.h"
  72. #include "editor/audio_stream_preview.h"
  73. #include "editor/debugger/editor_debugger_node.h"
  74. #include "editor/debugger/script_editor_debugger.h"
  75. #include "editor/dependency_editor.h"
  76. #include "editor/editor_about.h"
  77. #include "editor/editor_audio_buses.h"
  78. #include "editor/editor_build_profile.h"
  79. #include "editor/editor_command_palette.h"
  80. #include "editor/editor_data.h"
  81. #include "editor/editor_dock_manager.h"
  82. #include "editor/editor_feature_profile.h"
  83. #include "editor/editor_folding.h"
  84. #include "editor/editor_help.h"
  85. #include "editor/editor_inspector.h"
  86. #include "editor/editor_interface.h"
  87. #include "editor/editor_layouts_dialog.h"
  88. #include "editor/editor_log.h"
  89. #include "editor/editor_main_screen.h"
  90. #include "editor/editor_native_shader_source_visualizer.h"
  91. #include "editor/editor_paths.h"
  92. #include "editor/editor_properties.h"
  93. #include "editor/editor_property_name_processor.h"
  94. #include "editor/editor_resource_picker.h"
  95. #include "editor/editor_resource_preview.h"
  96. #include "editor/editor_settings.h"
  97. #include "editor/editor_settings_dialog.h"
  98. #include "editor/editor_translation_parser.h"
  99. #include "editor/editor_undo_redo_manager.h"
  100. #include "editor/export/editor_export.h"
  101. #include "editor/export/export_template_manager.h"
  102. #include "editor/export/project_export.h"
  103. #include "editor/fbx_importer_manager.h"
  104. #include "editor/filesystem_dock.h"
  105. #include "editor/gui/editor_bottom_panel.h"
  106. #include "editor/gui/editor_file_dialog.h"
  107. #include "editor/gui/editor_quick_open_dialog.h"
  108. #include "editor/gui/editor_run_bar.h"
  109. #include "editor/gui/editor_scene_tabs.h"
  110. #include "editor/gui/editor_title_bar.h"
  111. #include "editor/gui/editor_toaster.h"
  112. #include "editor/history_dock.h"
  113. #include "editor/import/3d/editor_import_collada.h"
  114. #include "editor/import/3d/resource_importer_obj.h"
  115. #include "editor/import/3d/resource_importer_scene.h"
  116. #include "editor/import/3d/scene_import_settings.h"
  117. #include "editor/import/audio_stream_import_settings.h"
  118. #include "editor/import/dynamic_font_import_settings.h"
  119. #include "editor/import/resource_importer_bitmask.h"
  120. #include "editor/import/resource_importer_bmfont.h"
  121. #include "editor/import/resource_importer_csv_translation.h"
  122. #include "editor/import/resource_importer_dynamic_font.h"
  123. #include "editor/import/resource_importer_image.h"
  124. #include "editor/import/resource_importer_imagefont.h"
  125. #include "editor/import/resource_importer_layered_texture.h"
  126. #include "editor/import/resource_importer_shader_file.h"
  127. #include "editor/import/resource_importer_texture.h"
  128. #include "editor/import/resource_importer_texture_atlas.h"
  129. #include "editor/import/resource_importer_wav.h"
  130. #include "editor/import_dock.h"
  131. #include "editor/inspector_dock.h"
  132. #include "editor/multi_node_edit.h"
  133. #include "editor/node_dock.h"
  134. #include "editor/plugins/animation_player_editor_plugin.h"
  135. #include "editor/plugins/asset_library_editor_plugin.h"
  136. #include "editor/plugins/canvas_item_editor_plugin.h"
  137. #include "editor/plugins/debugger_editor_plugin.h"
  138. #include "editor/plugins/dedicated_server_export_plugin.h"
  139. #include "editor/plugins/editor_plugin.h"
  140. #include "editor/plugins/editor_preview_plugins.h"
  141. #include "editor/plugins/editor_resource_conversion_plugin.h"
  142. #include "editor/plugins/game_view_plugin.h"
  143. #include "editor/plugins/gdextension_export_plugin.h"
  144. #include "editor/plugins/material_editor_plugin.h"
  145. #include "editor/plugins/mesh_library_editor_plugin.h"
  146. #include "editor/plugins/node_3d_editor_plugin.h"
  147. #include "editor/plugins/packed_scene_translation_parser_plugin.h"
  148. #include "editor/plugins/particle_process_material_editor_plugin.h"
  149. #include "editor/plugins/plugin_config_dialog.h"
  150. #include "editor/plugins/root_motion_editor_plugin.h"
  151. #include "editor/plugins/script_text_editor.h"
  152. #include "editor/plugins/text_editor.h"
  153. #include "editor/plugins/version_control_editor_plugin.h"
  154. #include "editor/plugins/visual_shader_editor_plugin.h"
  155. #include "editor/progress_dialog.h"
  156. #include "editor/project_settings_editor.h"
  157. #include "editor/register_exporters.h"
  158. #include "editor/scene_tree_dock.h"
  159. #include "editor/surface_upgrade_tool.h"
  160. #include "editor/themes/editor_scale.h"
  161. #include "editor/themes/editor_theme_manager.h"
  162. #include "editor/window_wrapper.h"
  163. #include <stdlib.h>
  164. #include "modules/modules_enabled.gen.h" // For gdscript, mono.
  165. EditorNode *EditorNode::singleton = nullptr;
  166. static const String EDITOR_NODE_CONFIG_SECTION = "EditorNode";
  167. static const String REMOVE_ANDROID_BUILD_TEMPLATE_MESSAGE = "The Android build template is already installed in this project and it won't be overwritten.\nRemove the \"%s\" directory manually before attempting this operation again.";
  168. static const String INSTALL_ANDROID_BUILD_TEMPLATE_MESSAGE = "This will set up your project for gradle Android builds by installing the source template to \"%s\".\nNote that in order to make gradle builds instead of using pre-built APKs, the \"Use Gradle Build\" option should be enabled in the Android export preset.";
  169. bool EditorProgress::step(const String &p_state, int p_step, bool p_force_refresh) {
  170. if (!force_background && Thread::is_main_thread()) {
  171. return EditorNode::progress_task_step(task, p_state, p_step, p_force_refresh);
  172. } else {
  173. EditorNode::progress_task_step_bg(task, p_step);
  174. return false;
  175. }
  176. }
  177. EditorProgress::EditorProgress(const String &p_task, const String &p_label, int p_amount, bool p_can_cancel, bool p_force_background) {
  178. if (!p_force_background && Thread::is_main_thread()) {
  179. EditorNode::progress_add_task(p_task, p_label, p_amount, p_can_cancel);
  180. } else {
  181. EditorNode::progress_add_task_bg(p_task, p_label, p_amount);
  182. }
  183. task = p_task;
  184. force_background = p_force_background;
  185. }
  186. EditorProgress::~EditorProgress() {
  187. if (!force_background && Thread::is_main_thread()) {
  188. EditorNode::progress_end_task(task);
  189. } else {
  190. EditorNode::progress_end_task_bg(task);
  191. }
  192. }
  193. void EditorNode::disambiguate_filenames(const Vector<String> p_full_paths, Vector<String> &r_filenames) {
  194. ERR_FAIL_COND_MSG(p_full_paths.size() != r_filenames.size(), vformat("disambiguate_filenames requires two string vectors of same length (%d != %d).", p_full_paths.size(), r_filenames.size()));
  195. // Keep track of a list of "index sets," i.e. sets of indices
  196. // within disambiguated_scene_names which contain the same name.
  197. Vector<RBSet<int>> index_sets;
  198. HashMap<String, int> scene_name_to_set_index;
  199. for (int i = 0; i < r_filenames.size(); i++) {
  200. const String &scene_name = r_filenames[i];
  201. if (!scene_name_to_set_index.has(scene_name)) {
  202. index_sets.append(RBSet<int>());
  203. scene_name_to_set_index.insert(r_filenames[i], index_sets.size() - 1);
  204. }
  205. index_sets.write[scene_name_to_set_index[scene_name]].insert(i);
  206. }
  207. // For each index set with a size > 1, we need to disambiguate.
  208. for (int i = 0; i < index_sets.size(); i++) {
  209. RBSet<int> iset = index_sets[i];
  210. while (iset.size() > 1) {
  211. // Append the parent folder to each scene name.
  212. for (const int &E : iset) {
  213. int set_idx = E;
  214. String scene_name = r_filenames[set_idx];
  215. String full_path = p_full_paths[set_idx];
  216. // Get rid of file extensions and res:// prefixes.
  217. scene_name = scene_name.get_basename();
  218. if (full_path.begins_with("res://")) {
  219. full_path = full_path.substr(6);
  220. }
  221. full_path = full_path.get_basename();
  222. // Normalize trailing slashes when normalizing directory names.
  223. scene_name = scene_name.trim_suffix("/");
  224. full_path = full_path.trim_suffix("/");
  225. int scene_name_size = scene_name.size();
  226. int full_path_size = full_path.size();
  227. int difference = full_path_size - scene_name_size;
  228. // Find just the parent folder of the current path and append it.
  229. // If the current name is foo.tscn, and the full path is /some/folder/foo.tscn
  230. // then slash_idx is the second '/', so that we select just "folder", and
  231. // append that to yield "folder/foo.tscn".
  232. if (difference > 0) {
  233. String parent = full_path.substr(0, difference);
  234. int slash_idx = parent.rfind_char('/');
  235. slash_idx = parent.rfind_char('/', slash_idx - 1);
  236. parent = (slash_idx >= 0 && parent.length() > 1) ? parent.substr(slash_idx + 1) : parent;
  237. r_filenames.write[set_idx] = parent + r_filenames[set_idx];
  238. }
  239. }
  240. // Loop back through scene names and remove non-ambiguous names.
  241. bool can_proceed = false;
  242. RBSet<int>::Element *E = iset.front();
  243. while (E) {
  244. String scene_name = r_filenames[E->get()];
  245. bool duplicate_found = false;
  246. for (const int &F : iset) {
  247. if (E->get() == F) {
  248. continue;
  249. }
  250. const String &other_scene_name = r_filenames[F];
  251. if (other_scene_name == scene_name) {
  252. duplicate_found = true;
  253. break;
  254. }
  255. }
  256. RBSet<int>::Element *to_erase = duplicate_found ? nullptr : E;
  257. // We need to check that we could actually append anymore names
  258. // if we wanted to for disambiguation. If we can't, then we have
  259. // to abort even with ambiguous names. We clean the full path
  260. // and the scene name first to remove extensions so that this
  261. // comparison actually works.
  262. String path = p_full_paths[E->get()];
  263. // Get rid of file extensions and res:// prefixes.
  264. scene_name = scene_name.get_basename();
  265. if (path.begins_with("res://")) {
  266. path = path.substr(6);
  267. }
  268. path = path.get_basename();
  269. // Normalize trailing slashes when normalizing directory names.
  270. scene_name = scene_name.trim_suffix("/");
  271. path = path.trim_suffix("/");
  272. // We can proceed if the full path is longer than the scene name,
  273. // meaning that there is at least one more parent folder we can
  274. // tack onto the name.
  275. can_proceed = can_proceed || (path.size() - scene_name.size()) >= 1;
  276. E = E->next();
  277. if (to_erase) {
  278. iset.erase(to_erase);
  279. }
  280. }
  281. if (!can_proceed) {
  282. break;
  283. }
  284. }
  285. }
  286. }
  287. void EditorNode::_version_control_menu_option(int p_idx) {
  288. switch (vcs_actions_menu->get_item_id(p_idx)) {
  289. case RUN_VCS_METADATA: {
  290. VersionControlEditorPlugin::get_singleton()->popup_vcs_metadata_dialog();
  291. } break;
  292. case RUN_VCS_SETTINGS: {
  293. VersionControlEditorPlugin::get_singleton()->popup_vcs_set_up_dialog(gui_base);
  294. } break;
  295. }
  296. }
  297. void EditorNode::_update_title() {
  298. const String appname = GLOBAL_GET("application/config/name");
  299. String title = (appname.is_empty() ? TTR("Unnamed Project") : appname);
  300. const String edited = editor_data.get_edited_scene_root() ? editor_data.get_edited_scene_root()->get_scene_file_path() : String();
  301. if (!edited.is_empty()) {
  302. // Display the edited scene name before the program name so that it can be seen in the OS task bar.
  303. title = vformat("%s - %s", edited.get_file(), title);
  304. }
  305. if (unsaved_cache) {
  306. // Display the "modified" mark before anything else so that it can always be seen in the OS task bar.
  307. title = vformat("(*) %s", title);
  308. }
  309. DisplayServer::get_singleton()->window_set_title(title + String(" - ") + VERSION_NAME);
  310. if (project_title) {
  311. project_title->set_text(title);
  312. }
  313. }
  314. void EditorNode::shortcut_input(const Ref<InputEvent> &p_event) {
  315. ERR_FAIL_COND(p_event.is_null());
  316. Ref<InputEventKey> k = p_event;
  317. if ((k.is_valid() && k->is_pressed() && !k->is_echo()) || Object::cast_to<InputEventShortcut>(*p_event)) {
  318. bool is_handled = true;
  319. if (ED_IS_SHORTCUT("editor/filter_files", p_event)) {
  320. FileSystemDock::get_singleton()->focus_on_filter();
  321. } else if (ED_IS_SHORTCUT("editor/editor_2d", p_event)) {
  322. editor_main_screen->select(EditorMainScreen::EDITOR_2D);
  323. } else if (ED_IS_SHORTCUT("editor/editor_3d", p_event)) {
  324. editor_main_screen->select(EditorMainScreen::EDITOR_3D);
  325. } else if (ED_IS_SHORTCUT("editor/editor_script", p_event)) {
  326. editor_main_screen->select(EditorMainScreen::EDITOR_SCRIPT);
  327. } else if (ED_IS_SHORTCUT("editor/editor_game", p_event)) {
  328. editor_main_screen->select(EditorMainScreen::EDITOR_GAME);
  329. } else if (ED_IS_SHORTCUT("editor/editor_help", p_event)) {
  330. emit_signal(SNAME("request_help_search"), "");
  331. } else if (ED_IS_SHORTCUT("editor/editor_assetlib", p_event) && AssetLibraryEditorPlugin::is_available()) {
  332. editor_main_screen->select(EditorMainScreen::EDITOR_ASSETLIB);
  333. } else if (ED_IS_SHORTCUT("editor/editor_next", p_event)) {
  334. editor_main_screen->select_next();
  335. } else if (ED_IS_SHORTCUT("editor/editor_prev", p_event)) {
  336. editor_main_screen->select_prev();
  337. } else if (ED_IS_SHORTCUT("editor/command_palette", p_event)) {
  338. _open_command_palette();
  339. } else if (ED_IS_SHORTCUT("editor/toggle_last_opened_bottom_panel", p_event)) {
  340. bottom_panel->toggle_last_opened_bottom_panel();
  341. } else {
  342. is_handled = false;
  343. }
  344. if (is_handled) {
  345. get_tree()->get_root()->set_input_as_handled();
  346. }
  347. }
  348. }
  349. void EditorNode::_update_vsync_mode() {
  350. const DisplayServer::VSyncMode window_vsync_mode = DisplayServer::VSyncMode(int(EDITOR_GET("interface/editor/vsync_mode")));
  351. DisplayServer::get_singleton()->window_set_vsync_mode(window_vsync_mode);
  352. }
  353. void EditorNode::_update_from_settings() {
  354. _update_title();
  355. int current_filter = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_filter");
  356. if (current_filter != scene_root->get_default_canvas_item_texture_filter()) {
  357. Viewport::DefaultCanvasItemTextureFilter tf = (Viewport::DefaultCanvasItemTextureFilter)current_filter;
  358. scene_root->set_default_canvas_item_texture_filter(tf);
  359. }
  360. int current_repeat = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_repeat");
  361. if (current_repeat != scene_root->get_default_canvas_item_texture_repeat()) {
  362. Viewport::DefaultCanvasItemTextureRepeat tr = (Viewport::DefaultCanvasItemTextureRepeat)current_repeat;
  363. scene_root->set_default_canvas_item_texture_repeat(tr);
  364. }
  365. RS::DOFBokehShape dof_shape = RS::DOFBokehShape(int(GLOBAL_GET("rendering/camera/depth_of_field/depth_of_field_bokeh_shape")));
  366. RS::get_singleton()->camera_attributes_set_dof_blur_bokeh_shape(dof_shape);
  367. RS::DOFBlurQuality dof_quality = RS::DOFBlurQuality(int(GLOBAL_GET("rendering/camera/depth_of_field/depth_of_field_bokeh_quality")));
  368. bool dof_jitter = GLOBAL_GET("rendering/camera/depth_of_field/depth_of_field_use_jitter");
  369. RS::get_singleton()->camera_attributes_set_dof_blur_quality(dof_quality, dof_jitter);
  370. RS::get_singleton()->environment_set_ssao_quality(RS::EnvironmentSSAOQuality(int(GLOBAL_GET("rendering/environment/ssao/quality"))), GLOBAL_GET("rendering/environment/ssao/half_size"), GLOBAL_GET("rendering/environment/ssao/adaptive_target"), GLOBAL_GET("rendering/environment/ssao/blur_passes"), GLOBAL_GET("rendering/environment/ssao/fadeout_from"), GLOBAL_GET("rendering/environment/ssao/fadeout_to"));
  371. RS::get_singleton()->screen_space_roughness_limiter_set_active(GLOBAL_GET("rendering/anti_aliasing/screen_space_roughness_limiter/enabled"), GLOBAL_GET("rendering/anti_aliasing/screen_space_roughness_limiter/amount"), GLOBAL_GET("rendering/anti_aliasing/screen_space_roughness_limiter/limit"));
  372. bool glow_bicubic = int(GLOBAL_GET("rendering/environment/glow/upscale_mode")) > 0;
  373. RS::get_singleton()->environment_set_ssil_quality(RS::EnvironmentSSILQuality(int(GLOBAL_GET("rendering/environment/ssil/quality"))), GLOBAL_GET("rendering/environment/ssil/half_size"), GLOBAL_GET("rendering/environment/ssil/adaptive_target"), GLOBAL_GET("rendering/environment/ssil/blur_passes"), GLOBAL_GET("rendering/environment/ssil/fadeout_from"), GLOBAL_GET("rendering/environment/ssil/fadeout_to"));
  374. RS::get_singleton()->environment_glow_set_use_bicubic_upscale(glow_bicubic);
  375. RS::EnvironmentSSRRoughnessQuality ssr_roughness_quality = RS::EnvironmentSSRRoughnessQuality(int(GLOBAL_GET("rendering/environment/screen_space_reflection/roughness_quality")));
  376. RS::get_singleton()->environment_set_ssr_roughness_quality(ssr_roughness_quality);
  377. RS::SubSurfaceScatteringQuality sss_quality = RS::SubSurfaceScatteringQuality(int(GLOBAL_GET("rendering/environment/subsurface_scattering/subsurface_scattering_quality")));
  378. RS::get_singleton()->sub_surface_scattering_set_quality(sss_quality);
  379. float sss_scale = GLOBAL_GET("rendering/environment/subsurface_scattering/subsurface_scattering_scale");
  380. float sss_depth_scale = GLOBAL_GET("rendering/environment/subsurface_scattering/subsurface_scattering_depth_scale");
  381. RS::get_singleton()->sub_surface_scattering_set_scale(sss_scale, sss_depth_scale);
  382. uint32_t directional_shadow_size = GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/size");
  383. uint32_t directional_shadow_16_bits = GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/16_bits");
  384. RS::get_singleton()->directional_shadow_atlas_set_size(directional_shadow_size, directional_shadow_16_bits);
  385. RS::ShadowQuality shadows_quality = RS::ShadowQuality(int(GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality")));
  386. RS::get_singleton()->positional_soft_shadow_filter_set_quality(shadows_quality);
  387. RS::ShadowQuality directional_shadow_quality = RS::ShadowQuality(int(GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality")));
  388. RS::get_singleton()->directional_soft_shadow_filter_set_quality(directional_shadow_quality);
  389. float probe_update_speed = GLOBAL_GET("rendering/lightmapping/probe_capture/update_speed");
  390. RS::get_singleton()->lightmap_set_probe_capture_update_speed(probe_update_speed);
  391. RS::EnvironmentSDFGIFramesToConverge frames_to_converge = RS::EnvironmentSDFGIFramesToConverge(int(GLOBAL_GET("rendering/global_illumination/sdfgi/frames_to_converge")));
  392. RS::get_singleton()->environment_set_sdfgi_frames_to_converge(frames_to_converge);
  393. RS::EnvironmentSDFGIRayCount ray_count = RS::EnvironmentSDFGIRayCount(int(GLOBAL_GET("rendering/global_illumination/sdfgi/probe_ray_count")));
  394. RS::get_singleton()->environment_set_sdfgi_ray_count(ray_count);
  395. RS::VoxelGIQuality voxel_gi_quality = RS::VoxelGIQuality(int(GLOBAL_GET("rendering/global_illumination/voxel_gi/quality")));
  396. RS::get_singleton()->voxel_gi_set_quality(voxel_gi_quality);
  397. RS::get_singleton()->environment_set_volumetric_fog_volume_size(GLOBAL_GET("rendering/environment/volumetric_fog/volume_size"), GLOBAL_GET("rendering/environment/volumetric_fog/volume_depth"));
  398. RS::get_singleton()->environment_set_volumetric_fog_filter_active(bool(GLOBAL_GET("rendering/environment/volumetric_fog/use_filter")));
  399. RS::get_singleton()->canvas_set_shadow_texture_size(GLOBAL_GET("rendering/2d/shadow_atlas/size"));
  400. bool use_half_res_gi = GLOBAL_GET("rendering/global_illumination/gi/use_half_resolution");
  401. RS::get_singleton()->gi_set_use_half_resolution(use_half_res_gi);
  402. bool snap_2d_transforms = GLOBAL_GET("rendering/2d/snap/snap_2d_transforms_to_pixel");
  403. scene_root->set_snap_2d_transforms_to_pixel(snap_2d_transforms);
  404. bool snap_2d_vertices = GLOBAL_GET("rendering/2d/snap/snap_2d_vertices_to_pixel");
  405. scene_root->set_snap_2d_vertices_to_pixel(snap_2d_vertices);
  406. Viewport::SDFOversize sdf_oversize = Viewport::SDFOversize(int(GLOBAL_GET("rendering/2d/sdf/oversize")));
  407. scene_root->set_sdf_oversize(sdf_oversize);
  408. Viewport::SDFScale sdf_scale = Viewport::SDFScale(int(GLOBAL_GET("rendering/2d/sdf/scale")));
  409. scene_root->set_sdf_scale(sdf_scale);
  410. Viewport::MSAA msaa = Viewport::MSAA(int(GLOBAL_GET("rendering/anti_aliasing/quality/msaa_2d")));
  411. scene_root->set_msaa_2d(msaa);
  412. bool use_hdr_2d = GLOBAL_GET("rendering/viewport/hdr_2d");
  413. scene_root->set_use_hdr_2d(use_hdr_2d);
  414. float mesh_lod_threshold = GLOBAL_GET("rendering/mesh_lod/lod_change/threshold_pixels");
  415. scene_root->set_mesh_lod_threshold(mesh_lod_threshold);
  416. RS::get_singleton()->decals_set_filter(RS::DecalFilter(int(GLOBAL_GET("rendering/textures/decals/filter"))));
  417. RS::get_singleton()->light_projectors_set_filter(RS::LightProjectorFilter(int(GLOBAL_GET("rendering/textures/light_projectors/filter"))));
  418. RS::get_singleton()->lightmaps_set_bicubic_filter(GLOBAL_GET("rendering/lightmapping/lightmap_gi/use_bicubic_filter"));
  419. SceneTree *tree = get_tree();
  420. tree->set_debug_collisions_color(GLOBAL_GET("debug/shapes/collision/shape_color"));
  421. tree->set_debug_collision_contact_color(GLOBAL_GET("debug/shapes/collision/contact_color"));
  422. ResourceImporterTexture::get_singleton()->update_imports();
  423. #ifdef DEBUG_ENABLED
  424. NavigationServer3D::get_singleton()->set_debug_navigation_edge_connection_color(GLOBAL_GET("debug/shapes/navigation/edge_connection_color"));
  425. NavigationServer3D::get_singleton()->set_debug_navigation_geometry_edge_color(GLOBAL_GET("debug/shapes/navigation/geometry_edge_color"));
  426. NavigationServer3D::get_singleton()->set_debug_navigation_geometry_face_color(GLOBAL_GET("debug/shapes/navigation/geometry_face_color"));
  427. NavigationServer3D::get_singleton()->set_debug_navigation_geometry_edge_disabled_color(GLOBAL_GET("debug/shapes/navigation/geometry_edge_disabled_color"));
  428. NavigationServer3D::get_singleton()->set_debug_navigation_geometry_face_disabled_color(GLOBAL_GET("debug/shapes/navigation/geometry_face_disabled_color"));
  429. NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_connections(GLOBAL_GET("debug/shapes/navigation/enable_edge_connections"));
  430. NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_connections_xray(GLOBAL_GET("debug/shapes/navigation/enable_edge_connections_xray"));
  431. NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_lines(GLOBAL_GET("debug/shapes/navigation/enable_edge_lines"));
  432. NavigationServer3D::get_singleton()->set_debug_navigation_enable_edge_lines_xray(GLOBAL_GET("debug/shapes/navigation/enable_edge_lines_xray"));
  433. NavigationServer3D::get_singleton()->set_debug_navigation_enable_geometry_face_random_color(GLOBAL_GET("debug/shapes/navigation/enable_geometry_face_random_color"));
  434. #endif // DEBUG_ENABLED
  435. }
  436. void EditorNode::_gdextensions_reloaded() {
  437. // In case the developer is inspecting an object that will be changed by the reload.
  438. InspectorDock::get_inspector_singleton()->update_tree();
  439. // Reload script editor to revalidate GDScript if classes are added or removed.
  440. ScriptEditor::get_singleton()->reload_scripts(true);
  441. // Regenerate documentation.
  442. EditorHelp::generate_doc();
  443. }
  444. void EditorNode::_update_theme(bool p_skip_creation) {
  445. if (!p_skip_creation) {
  446. theme = EditorThemeManager::generate_theme(theme);
  447. DisplayServer::set_early_window_clear_color_override(true, theme->get_color(SNAME("background"), EditorStringName(Editor)));
  448. }
  449. Vector<Ref<Theme>> editor_themes;
  450. editor_themes.push_back(theme);
  451. editor_themes.push_back(ThemeDB::get_singleton()->get_default_theme());
  452. ThemeContext *node_tc = ThemeDB::get_singleton()->get_theme_context(this);
  453. if (node_tc) {
  454. node_tc->set_themes(editor_themes);
  455. } else {
  456. ThemeDB::get_singleton()->create_theme_context(this, editor_themes);
  457. }
  458. Window *window = get_window();
  459. if (window) {
  460. ThemeContext *window_tc = ThemeDB::get_singleton()->get_theme_context(window);
  461. if (window_tc) {
  462. window_tc->set_themes(editor_themes);
  463. } else {
  464. ThemeDB::get_singleton()->create_theme_context(window, editor_themes);
  465. }
  466. }
  467. if (CanvasItemEditor::get_singleton()->get_theme_preview() == CanvasItemEditor::THEME_PREVIEW_EDITOR) {
  468. update_preview_themes(CanvasItemEditor::THEME_PREVIEW_EDITOR);
  469. }
  470. // Update styles.
  471. {
  472. gui_base->add_theme_style_override(SceneStringName(panel), theme->get_stylebox(SNAME("Background"), EditorStringName(EditorStyles)));
  473. main_vbox->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT, Control::PRESET_MODE_MINSIZE, theme->get_constant(SNAME("window_border_margin"), EditorStringName(Editor)));
  474. main_vbox->add_theme_constant_override("separation", theme->get_constant(SNAME("top_bar_separation"), EditorStringName(Editor)));
  475. editor_main_screen->add_theme_style_override(SceneStringName(panel), theme->get_stylebox(SNAME("Content"), EditorStringName(EditorStyles)));
  476. bottom_panel->add_theme_style_override(SceneStringName(panel), theme->get_stylebox(SNAME("BottomPanel"), EditorStringName(EditorStyles)));
  477. distraction_free->set_button_icon(theme->get_icon(SNAME("DistractionFree"), EditorStringName(EditorIcons)));
  478. distraction_free->add_theme_style_override(SceneStringName(pressed), theme->get_stylebox(CoreStringName(normal), "FlatMenuButton"));
  479. help_menu->set_item_icon(help_menu->get_item_index(HELP_SEARCH), theme->get_icon(SNAME("HelpSearch"), EditorStringName(EditorIcons)));
  480. help_menu->set_item_icon(help_menu->get_item_index(HELP_COPY_SYSTEM_INFO), theme->get_icon(SNAME("ActionCopy"), EditorStringName(EditorIcons)));
  481. help_menu->set_item_icon(help_menu->get_item_index(HELP_ABOUT), theme->get_icon(SNAME("Godot"), EditorStringName(EditorIcons)));
  482. help_menu->set_item_icon(help_menu->get_item_index(HELP_SUPPORT_GODOT_DEVELOPMENT), theme->get_icon(SNAME("Heart"), EditorStringName(EditorIcons)));
  483. if (EditorDebuggerNode::get_singleton()->is_visible()) {
  484. bottom_panel->add_theme_style_override(SceneStringName(panel), theme->get_stylebox(SNAME("BottomPanelDebuggerOverride"), EditorStringName(EditorStyles)));
  485. }
  486. _update_renderer_color();
  487. }
  488. editor_dock_manager->update_tab_styles();
  489. editor_dock_manager->set_tab_icon_max_width(theme->get_constant(SNAME("class_icon_size"), EditorStringName(Editor)));
  490. }
  491. void EditorNode::update_preview_themes(int p_mode) {
  492. if (!scene_root->is_inside_tree()) {
  493. return; // Too early.
  494. }
  495. Vector<Ref<Theme>> preview_themes;
  496. switch (p_mode) {
  497. case CanvasItemEditor::THEME_PREVIEW_PROJECT:
  498. preview_themes.push_back(ThemeDB::get_singleton()->get_project_theme());
  499. break;
  500. case CanvasItemEditor::THEME_PREVIEW_EDITOR:
  501. preview_themes.push_back(get_editor_theme());
  502. break;
  503. default:
  504. break;
  505. }
  506. preview_themes.push_back(ThemeDB::get_singleton()->get_default_theme());
  507. ThemeContext *preview_context = ThemeDB::get_singleton()->get_theme_context(scene_root);
  508. if (preview_context) {
  509. preview_context->set_themes(preview_themes);
  510. } else {
  511. ThemeDB::get_singleton()->create_theme_context(scene_root, preview_themes);
  512. }
  513. }
  514. void EditorNode::_notification(int p_what) {
  515. switch (p_what) {
  516. case NOTIFICATION_POSTINITIALIZE: {
  517. EditorHelp::generate_doc();
  518. #if defined(MODULE_GDSCRIPT_ENABLED) || defined(MODULE_MONO_ENABLED)
  519. EditorHelpHighlighter::create_singleton();
  520. #endif
  521. } break;
  522. case NOTIFICATION_PROCESS: {
  523. if (opening_prev && !confirmation->is_visible()) {
  524. opening_prev = false;
  525. }
  526. bool global_unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(EditorUndoRedoManager::GLOBAL_HISTORY);
  527. bool scene_or_global_unsaved = global_unsaved || EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_current_edited_scene_history_id());
  528. if (unsaved_cache != scene_or_global_unsaved) {
  529. unsaved_cache = scene_or_global_unsaved;
  530. _update_title();
  531. }
  532. if (editor_data.is_scene_changed(-1)) {
  533. scene_tabs->update_scene_tabs();
  534. }
  535. // Update the animation frame of the update spinner.
  536. uint64_t frame = Engine::get_singleton()->get_frames_drawn();
  537. uint64_t tick = OS::get_singleton()->get_ticks_msec();
  538. if (frame != update_spinner_step_frame && (tick - update_spinner_step_msec) > (1000 / 8)) {
  539. update_spinner_step++;
  540. if (update_spinner_step >= 8) {
  541. update_spinner_step = 0;
  542. }
  543. update_spinner_step_msec = tick;
  544. update_spinner_step_frame = frame + 1;
  545. // Update the icon itself only when the spinner is visible.
  546. if (_should_display_update_spinner()) {
  547. update_spinner->set_button_icon(theme->get_icon("Progress" + itos(update_spinner_step + 1), EditorStringName(EditorIcons)));
  548. }
  549. }
  550. editor_selection->update();
  551. ResourceImporterTexture::get_singleton()->update_imports();
  552. if (requested_first_scan) {
  553. requested_first_scan = false;
  554. OS::get_singleton()->benchmark_begin_measure("Editor", "First Scan");
  555. if (run_surface_upgrade_tool) {
  556. run_surface_upgrade_tool = false;
  557. SurfaceUpgradeTool::get_singleton()->connect("upgrade_finished", callable_mp(EditorFileSystem::get_singleton(), &EditorFileSystem::scan), CONNECT_ONE_SHOT);
  558. SurfaceUpgradeTool::get_singleton()->finish_upgrade();
  559. } else {
  560. EditorFileSystem::get_singleton()->scan();
  561. }
  562. }
  563. } break;
  564. case NOTIFICATION_ENTER_TREE: {
  565. get_tree()->set_disable_node_threading(true); // No node threading while running editor.
  566. Engine::get_singleton()->set_editor_hint(true);
  567. Window *window = get_window();
  568. if (window) {
  569. // Handle macOS fullscreen and extend-to-title changes.
  570. window->connect("titlebar_changed", callable_mp(this, &EditorNode::_titlebar_resized));
  571. }
  572. // Theme has already been created in the constructor, so we can skip that step.
  573. _update_theme(true);
  574. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(int(EDITOR_GET("interface/editor/low_processor_mode_sleep_usec")));
  575. get_tree()->get_root()->set_as_audio_listener_3d(false);
  576. get_tree()->get_root()->set_as_audio_listener_2d(false);
  577. get_tree()->get_root()->set_snap_2d_transforms_to_pixel(false);
  578. get_tree()->get_root()->set_snap_2d_vertices_to_pixel(false);
  579. get_tree()->set_auto_accept_quit(false);
  580. #ifdef ANDROID_ENABLED
  581. get_tree()->set_quit_on_go_back(false);
  582. #endif
  583. get_tree()->get_root()->connect("files_dropped", callable_mp(this, &EditorNode::_dropped_files));
  584. command_palette->register_shortcuts_as_command();
  585. callable_mp(this, &EditorNode::_begin_first_scan).call_deferred();
  586. last_dark_mode_state = DisplayServer::get_singleton()->is_dark_mode();
  587. last_system_accent_color = DisplayServer::get_singleton()->get_accent_color();
  588. last_system_base_color = DisplayServer::get_singleton()->get_base_color();
  589. DisplayServer::get_singleton()->set_system_theme_change_callback(callable_mp(this, &EditorNode::_check_system_theme_changed));
  590. get_viewport()->connect("size_changed", callable_mp(this, &EditorNode::_viewport_resized));
  591. /* DO NOT LOAD SCENES HERE, WAIT FOR FILE SCANNING AND REIMPORT TO COMPLETE */
  592. } break;
  593. case NOTIFICATION_EXIT_TREE: {
  594. singleton->active_plugins.clear();
  595. if (progress_dialog) {
  596. progress_dialog->queue_free();
  597. }
  598. if (load_error_dialog) {
  599. load_error_dialog->queue_free();
  600. }
  601. if (execute_output_dialog) {
  602. execute_output_dialog->queue_free();
  603. }
  604. if (warning) {
  605. warning->queue_free();
  606. }
  607. if (accept) {
  608. accept->queue_free();
  609. }
  610. if (save_accept) {
  611. save_accept->queue_free();
  612. }
  613. editor_data.save_editor_external_data();
  614. FileAccess::set_file_close_fail_notify_callback(nullptr);
  615. log->deinit(); // Do not get messages anymore.
  616. editor_data.clear_edited_scenes();
  617. get_viewport()->disconnect("size_changed", callable_mp(this, &EditorNode::_viewport_resized));
  618. } break;
  619. case NOTIFICATION_READY: {
  620. started_timestamp = Time::get_singleton()->get_unix_time_from_system();
  621. RenderingServer::get_singleton()->viewport_set_disable_2d(get_scene_root()->get_viewport_rid(), true);
  622. RenderingServer::get_singleton()->viewport_set_environment_mode(get_viewport()->get_viewport_rid(), RenderingServer::VIEWPORT_ENVIRONMENT_DISABLED);
  623. DisplayServer::get_singleton()->screen_set_keep_on(EDITOR_GET("interface/editor/keep_screen_on"));
  624. feature_profile_manager->notify_changed();
  625. // Save the project after opening to mark it as last modified, except in headless mode.
  626. if (DisplayServer::get_singleton()->window_can_draw()) {
  627. ProjectSettings::get_singleton()->save();
  628. }
  629. _titlebar_resized();
  630. // Set up a theme context for the 2D preview viewport using the stored preview theme.
  631. CanvasItemEditor::ThemePreviewMode theme_preview_mode = (CanvasItemEditor::ThemePreviewMode)(int)EditorSettings::get_singleton()->get_project_metadata("2d_editor", "theme_preview", CanvasItemEditor::THEME_PREVIEW_PROJECT);
  632. update_preview_themes(theme_preview_mode);
  633. /* DO NOT LOAD SCENES HERE, WAIT FOR FILE SCANNING AND REIMPORT TO COMPLETE */
  634. } break;
  635. case NOTIFICATION_APPLICATION_FOCUS_IN: {
  636. // Restore the original FPS cap after focusing back on the editor.
  637. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(int(EDITOR_GET("interface/editor/low_processor_mode_sleep_usec")));
  638. EditorFileSystem::get_singleton()->scan_changes();
  639. _scan_external_changes();
  640. GDExtensionManager *gdextension_manager = GDExtensionManager::get_singleton();
  641. callable_mp(gdextension_manager, &GDExtensionManager::reload_extensions).call_deferred();
  642. } break;
  643. case NOTIFICATION_APPLICATION_FOCUS_OUT: {
  644. // Save on focus loss before applying the FPS limit to avoid slowing down the saving process.
  645. if (EDITOR_GET("interface/editor/save_on_focus_loss")) {
  646. _menu_option_confirm(FILE_SAVE_SCENE_SILENTLY, false);
  647. }
  648. // Set a low FPS cap to decrease CPU/GPU usage while the editor is unfocused.
  649. if (unfocused_low_processor_usage_mode_enabled) {
  650. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(int(EDITOR_GET("interface/editor/unfocused_low_processor_mode_sleep_usec")));
  651. }
  652. } break;
  653. case NOTIFICATION_WM_ABOUT: {
  654. show_about();
  655. } break;
  656. case NOTIFICATION_WM_CLOSE_REQUEST: {
  657. _menu_option_confirm(FILE_QUIT, false);
  658. } break;
  659. case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
  660. if (EditorSettings::get_singleton()->check_changed_settings_in_group("filesystem/file_dialog")) {
  661. FileDialog::set_default_show_hidden_files(EDITOR_GET("filesystem/file_dialog/show_hidden_files"));
  662. EditorFileDialog::set_default_show_hidden_files(EDITOR_GET("filesystem/file_dialog/show_hidden_files"));
  663. EditorFileDialog::set_default_display_mode((EditorFileDialog::DisplayMode)EDITOR_GET("filesystem/file_dialog/display_mode").operator int());
  664. }
  665. if (EDITOR_GET("interface/editor/import_resources_when_unfocused")) {
  666. scan_changes_timer->start();
  667. } else {
  668. scan_changes_timer->stop();
  669. }
  670. follow_system_theme = EDITOR_GET("interface/theme/follow_system_theme");
  671. use_system_accent_color = EDITOR_GET("interface/theme/use_system_accent_color");
  672. if (EditorThemeManager::is_generated_theme_outdated()) {
  673. _update_theme();
  674. _build_icon_type_cache();
  675. recent_scenes->reset_size();
  676. }
  677. if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor/dock_tab_style")) {
  678. editor_dock_manager->update_tab_styles();
  679. }
  680. if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/scene_tabs")) {
  681. scene_tabs->update_scene_tabs();
  682. }
  683. if (EditorSettings::get_singleton()->check_changed_settings_in_group("docks/filesystem")) {
  684. HashSet<String> updated_textfile_extensions;
  685. HashSet<String> updated_other_file_extensions;
  686. bool extensions_match = true;
  687. const Vector<String> textfile_ext = ((String)(EDITOR_GET("docks/filesystem/textfile_extensions"))).split(",", false);
  688. for (const String &E : textfile_ext) {
  689. updated_textfile_extensions.insert(E);
  690. if (extensions_match && !textfile_extensions.has(E)) {
  691. extensions_match = false;
  692. }
  693. }
  694. const Vector<String> other_file_ext = ((String)(EDITOR_GET("docks/filesystem/other_file_extensions"))).split(",", false);
  695. for (const String &E : other_file_ext) {
  696. updated_other_file_extensions.insert(E);
  697. if (extensions_match && !other_file_extensions.has(E)) {
  698. extensions_match = false;
  699. }
  700. }
  701. if (!extensions_match || updated_textfile_extensions.size() < textfile_extensions.size() || updated_other_file_extensions.size() < other_file_extensions.size()) {
  702. textfile_extensions = updated_textfile_extensions;
  703. other_file_extensions = updated_other_file_extensions;
  704. EditorFileSystem::get_singleton()->scan();
  705. }
  706. }
  707. if (EditorSettings::get_singleton()->check_changed_settings_in_group("interface/editor")) {
  708. _update_update_spinner();
  709. _update_vsync_mode();
  710. DisplayServer::get_singleton()->screen_set_keep_on(EDITOR_GET("interface/editor/keep_screen_on"));
  711. }
  712. #if defined(MODULE_GDSCRIPT_ENABLED) || defined(MODULE_MONO_ENABLED)
  713. if (EditorSettings::get_singleton()->check_changed_settings_in_group("text_editor/theme/highlighting")) {
  714. EditorHelpHighlighter::get_singleton()->reset_cache();
  715. }
  716. #endif
  717. } break;
  718. }
  719. }
  720. void EditorNode::_update_update_spinner() {
  721. update_spinner->set_visible(!RenderingServer::get_singleton()->canvas_item_get_debug_redraw() && _should_display_update_spinner());
  722. const bool update_continuously = EDITOR_GET("interface/editor/update_continuously");
  723. PopupMenu *update_popup = update_spinner->get_popup();
  724. update_popup->set_item_checked(update_popup->get_item_index(SETTINGS_UPDATE_CONTINUOUSLY), update_continuously);
  725. update_popup->set_item_checked(update_popup->get_item_index(SETTINGS_UPDATE_WHEN_CHANGED), !update_continuously);
  726. if (update_continuously) {
  727. update_spinner->set_tooltip_text(TTR("Spins when the editor window redraws.\nUpdate Continuously is enabled, which can increase power usage. Click to disable it."));
  728. // Use a different color for the update spinner when Update Continuously is enabled,
  729. // as this feature should only be enabled for troubleshooting purposes.
  730. // Make the icon modulate color overbright because icons are not completely white on a dark theme.
  731. // On a light theme, icons are dark, so we need to modulate them with an even brighter color.
  732. const bool dark_theme = EditorThemeManager::is_dark_theme();
  733. update_spinner->set_self_modulate(theme->get_color(SNAME("error_color"), EditorStringName(Editor)) * (dark_theme ? Color(1.1, 1.1, 1.1) : Color(4.25, 4.25, 4.25)));
  734. } else {
  735. update_spinner->set_tooltip_text(TTR("Spins when the editor window redraws."));
  736. update_spinner->set_self_modulate(Color(1, 1, 1));
  737. }
  738. OS::get_singleton()->set_low_processor_usage_mode(!update_continuously);
  739. }
  740. void EditorNode::init_plugins() {
  741. _initializing_plugins = true;
  742. Vector<String> addons;
  743. if (ProjectSettings::get_singleton()->has_setting("editor_plugins/enabled")) {
  744. addons = GLOBAL_GET("editor_plugins/enabled");
  745. }
  746. for (const String &addon : addons) {
  747. set_addon_plugin_enabled(addon, true);
  748. }
  749. _initializing_plugins = false;
  750. if (!pending_addons.is_empty()) {
  751. EditorFileSystem::get_singleton()->connect("script_classes_updated", callable_mp(this, &EditorNode::_enable_pending_addons), CONNECT_ONE_SHOT);
  752. }
  753. }
  754. void EditorNode::_on_plugin_ready(Object *p_script, const String &p_activate_name) {
  755. Ref<Script> scr = Object::cast_to<Script>(p_script);
  756. if (scr.is_null()) {
  757. return;
  758. }
  759. project_settings_editor->update_plugins();
  760. project_settings_editor->hide();
  761. push_item(scr.operator->());
  762. if (p_activate_name.length()) {
  763. set_addon_plugin_enabled(p_activate_name, true);
  764. }
  765. }
  766. void EditorNode::_remove_plugin_from_enabled(const String &p_name) {
  767. ProjectSettings *ps = ProjectSettings::get_singleton();
  768. PackedStringArray enabled_plugins = ps->get("editor_plugins/enabled");
  769. for (int i = 0; i < enabled_plugins.size(); ++i) {
  770. if (enabled_plugins.get(i) == p_name) {
  771. enabled_plugins.remove_at(i);
  772. break;
  773. }
  774. }
  775. ps->set("editor_plugins/enabled", enabled_plugins);
  776. }
  777. void EditorNode::_plugin_over_edit(EditorPlugin *p_plugin, Object *p_object) {
  778. if (p_object) {
  779. editor_plugins_over->add_plugin(p_plugin);
  780. p_plugin->make_visible(true);
  781. p_plugin->edit(p_object);
  782. } else {
  783. editor_plugins_over->remove_plugin(p_plugin);
  784. p_plugin->make_visible(false);
  785. p_plugin->edit(nullptr);
  786. }
  787. }
  788. void EditorNode::_plugin_over_self_own(EditorPlugin *p_plugin) {
  789. active_plugins[p_plugin->get_instance_id()].insert(p_plugin);
  790. }
  791. void EditorNode::_resources_changed(const Vector<String> &p_resources) {
  792. List<Ref<Resource>> changed;
  793. int rc = p_resources.size();
  794. for (int i = 0; i < rc; i++) {
  795. Ref<Resource> res = ResourceCache::get_ref(p_resources.get(i));
  796. if (res.is_null()) {
  797. continue;
  798. }
  799. if (!res->editor_can_reload_from_file()) {
  800. continue;
  801. }
  802. if (!res->get_path().is_resource_file() && !res->get_path().is_absolute_path()) {
  803. continue;
  804. }
  805. if (!FileAccess::exists(res->get_path())) {
  806. continue;
  807. }
  808. if (!res->get_import_path().is_empty()) {
  809. // This is an imported resource, will be reloaded if reimported via the _resources_reimported() callback.
  810. continue;
  811. }
  812. changed.push_back(res);
  813. }
  814. if (changed.size()) {
  815. for (Ref<Resource> &res : changed) {
  816. res->reload_from_file();
  817. }
  818. }
  819. }
  820. void EditorNode::_fs_changed() {
  821. for (FileDialog *E : file_dialogs) {
  822. E->invalidate();
  823. }
  824. for (EditorFileDialog *E : editor_file_dialogs) {
  825. E->invalidate();
  826. }
  827. _mark_unsaved_scenes();
  828. // FIXME: Move this to a cleaner location, it's hacky to do this in _fs_changed.
  829. String export_error;
  830. Error err = OK;
  831. // It's important to wait for the first scan to finish; otherwise, scripts or resources might not be imported.
  832. if (!export_defer.preset.is_empty() && !EditorFileSystem::get_singleton()->is_scanning()) {
  833. String preset_name = export_defer.preset;
  834. // Ensures export_project does not loop infinitely, because notifications may
  835. // come during the export.
  836. export_defer.preset = "";
  837. Ref<EditorExportPreset> export_preset;
  838. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); ++i) {
  839. export_preset = EditorExport::get_singleton()->get_export_preset(i);
  840. if (export_preset->get_name() == preset_name) {
  841. break;
  842. }
  843. export_preset.unref();
  844. }
  845. if (export_preset.is_null()) {
  846. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  847. if (da->file_exists("res://export_presets.cfg")) {
  848. err = FAILED;
  849. export_error = vformat(
  850. "Invalid export preset name: %s.\nThe following presets were detected in this project's `export_presets.cfg`:\n\n",
  851. preset_name);
  852. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); ++i) {
  853. // Write the preset name between double quotes since it needs to be written between quotes on the command line if it contains spaces.
  854. export_error += vformat(" \"%s\"\n", EditorExport::get_singleton()->get_export_preset(i)->get_name());
  855. }
  856. } else {
  857. err = FAILED;
  858. export_error = "This project doesn't have an `export_presets.cfg` file at its root.\nCreate an export preset from the \"Project > Export\" dialog and try again.";
  859. }
  860. } else {
  861. Ref<EditorExportPlatform> platform = export_preset->get_platform();
  862. const String export_path = export_defer.path.is_empty() ? export_preset->get_export_path() : export_defer.path;
  863. if (export_path.is_empty()) {
  864. err = FAILED;
  865. export_error = vformat("Export preset \"%s\" doesn't have a default export path, and none was specified.", preset_name);
  866. } else if (platform.is_null()) {
  867. err = FAILED;
  868. export_error = vformat("Export preset \"%s\" doesn't have a matching platform.", preset_name);
  869. } else {
  870. export_preset->update_value_overrides();
  871. if (export_defer.pack_only) { // Only export .pck or .zip data pack.
  872. if (export_path.ends_with(".zip")) {
  873. if (export_defer.patch) {
  874. err = platform->export_zip_patch(export_preset, export_defer.debug, export_path, export_defer.patches);
  875. } else {
  876. err = platform->export_zip(export_preset, export_defer.debug, export_path);
  877. }
  878. } else if (export_path.ends_with(".pck")) {
  879. if (export_defer.patch) {
  880. err = platform->export_pack_patch(export_preset, export_defer.debug, export_path, export_defer.patches);
  881. } else {
  882. err = platform->export_pack(export_preset, export_defer.debug, export_path);
  883. }
  884. } else {
  885. ERR_PRINT(vformat("Export path \"%s\" doesn't end with a supported extension.", export_path));
  886. err = FAILED;
  887. }
  888. } else { // Normal project export.
  889. String config_error;
  890. bool missing_templates;
  891. if (export_defer.android_build_template) {
  892. export_template_manager->install_android_template(export_preset);
  893. }
  894. if (!platform->can_export(export_preset, config_error, missing_templates, export_defer.debug)) {
  895. ERR_PRINT(vformat("Cannot export project with preset \"%s\" due to configuration errors:\n%s", preset_name, config_error));
  896. err = missing_templates ? ERR_FILE_NOT_FOUND : ERR_UNCONFIGURED;
  897. } else {
  898. platform->clear_messages();
  899. err = platform->export_project(export_preset, export_defer.debug, export_path);
  900. }
  901. }
  902. if (err != OK) {
  903. export_error = vformat("Project export for preset \"%s\" failed.", preset_name);
  904. } else if (platform->get_worst_message_type() >= EditorExportPlatform::EXPORT_MESSAGE_WARNING) {
  905. export_error = vformat("Project export for preset \"%s\" completed with warnings.", preset_name);
  906. }
  907. }
  908. }
  909. if (err != OK) {
  910. ERR_PRINT(export_error);
  911. _exit_editor(EXIT_FAILURE);
  912. return;
  913. }
  914. if (!export_error.is_empty()) {
  915. WARN_PRINT(export_error);
  916. }
  917. _exit_editor(EXIT_SUCCESS);
  918. }
  919. }
  920. void EditorNode::_resources_reimporting(const Vector<String> &p_resources) {
  921. // This will copy all the modified properties of the nodes into 'scenes_modification_table'
  922. // before they are actually reimported. It's important to do this before the reimportation
  923. // because if a mesh is present in an inherited scene, the resource will be modified in
  924. // the inherited scene. Then, get_modified_properties_for_node will return the mesh property,
  925. // which will trigger a recopy of the previous mesh, preventing the reload.
  926. scenes_modification_table.clear();
  927. scenes_reimported.clear();
  928. resources_reimported.clear();
  929. EditorFileSystem *editor_file_system = EditorFileSystem::get_singleton();
  930. for (const String &res_path : p_resources) {
  931. // It's faster to use EditorFileSystem::get_file_type than fetching the resource type from disk.
  932. // This makes a big difference when reimporting many resources.
  933. String file_type = editor_file_system->get_file_type(res_path);
  934. if (file_type.is_empty()) {
  935. file_type = ResourceLoader::get_resource_type(res_path);
  936. }
  937. if (file_type == "PackedScene") {
  938. scenes_reimported.push_back(res_path);
  939. } else {
  940. resources_reimported.push_back(res_path);
  941. }
  942. }
  943. if (scenes_reimported.size() > 0) {
  944. preload_reimporting_with_path_in_edited_scenes(scenes_reimported);
  945. }
  946. }
  947. void EditorNode::_resources_reimported(const Vector<String> &p_resources) {
  948. int current_tab = scene_tabs->get_current_tab();
  949. for (const String &res_path : resources_reimported) {
  950. if (!ResourceCache::has(res_path)) {
  951. // Not loaded, no need to reload.
  952. continue;
  953. }
  954. // Reload normally.
  955. Ref<Resource> resource = ResourceCache::get_ref(res_path);
  956. if (resource.is_valid()) {
  957. resource->reload_from_file();
  958. }
  959. }
  960. // Editor may crash when related animation is playing while re-importing GLTF scene, stop it in advance.
  961. AnimationPlayer *ap = AnimationPlayerEditor::get_singleton()->get_player();
  962. if (ap && scenes_reimported.size() > 0) {
  963. ap->stop(true);
  964. }
  965. for (const String &E : scenes_reimported) {
  966. reload_scene(E);
  967. }
  968. reload_instances_with_path_in_edited_scenes();
  969. scenes_modification_table.clear();
  970. scenes_reimported.clear();
  971. resources_reimported.clear();
  972. _set_current_scene_nocheck(current_tab);
  973. }
  974. void EditorNode::_sources_changed(bool p_exist) {
  975. if (waiting_for_first_scan) {
  976. waiting_for_first_scan = false;
  977. OS::get_singleton()->benchmark_end_measure("Editor", "First Scan");
  978. // Reload the global shader variables, but this time
  979. // loading textures, as they are now properly imported.
  980. RenderingServer::get_singleton()->global_shader_parameters_load_settings(true);
  981. _load_editor_layout();
  982. if (!defer_load_scene.is_empty()) {
  983. OS::get_singleton()->benchmark_begin_measure("Editor", "Load Scene");
  984. load_scene(defer_load_scene);
  985. defer_load_scene = "";
  986. OS::get_singleton()->benchmark_end_measure("Editor", "Load Scene");
  987. OS::get_singleton()->benchmark_dump();
  988. }
  989. if (SurfaceUpgradeTool::get_singleton()->is_show_requested()) {
  990. SurfaceUpgradeTool::get_singleton()->show_popup();
  991. }
  992. // Start preview thread now that it's safe.
  993. if (!singleton->cmdline_export_mode) {
  994. EditorResourcePreview::get_singleton()->start();
  995. }
  996. }
  997. }
  998. void EditorNode::_scan_external_changes() {
  999. disk_changed_list->clear();
  1000. TreeItem *r = disk_changed_list->create_item();
  1001. disk_changed_list->set_hide_root(true);
  1002. bool need_reload = false;
  1003. // Check if any edited scene has changed.
  1004. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  1005. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1006. if (editor_data.get_scene_path(i) == "" || !da->file_exists(editor_data.get_scene_path(i))) {
  1007. continue;
  1008. }
  1009. uint64_t last_date = editor_data.get_scene_modified_time(i);
  1010. uint64_t date = FileAccess::get_modified_time(editor_data.get_scene_path(i));
  1011. if (date > last_date) {
  1012. TreeItem *ti = disk_changed_list->create_item(r);
  1013. ti->set_text(0, editor_data.get_scene_path(i).get_file());
  1014. need_reload = true;
  1015. }
  1016. }
  1017. String project_settings_path = ProjectSettings::get_singleton()->get_resource_path().path_join("project.godot");
  1018. if (FileAccess::get_modified_time(project_settings_path) > ProjectSettings::get_singleton()->get_last_saved_time()) {
  1019. TreeItem *ti = disk_changed_list->create_item(r);
  1020. ti->set_text(0, "project.godot");
  1021. need_reload = true;
  1022. }
  1023. if (need_reload) {
  1024. callable_mp((Window *)disk_changed, &Window::popup_centered_ratio).call_deferred(0.3);
  1025. }
  1026. }
  1027. void EditorNode::_resave_scenes(String p_str) {
  1028. save_all_scenes();
  1029. ProjectSettings::get_singleton()->save();
  1030. disk_changed->hide();
  1031. }
  1032. void EditorNode::_reload_modified_scenes() {
  1033. int current_idx = editor_data.get_edited_scene();
  1034. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  1035. if (editor_data.get_scene_path(i) == "") {
  1036. continue;
  1037. }
  1038. uint64_t last_date = editor_data.get_scene_modified_time(i);
  1039. uint64_t date = FileAccess::get_modified_time(editor_data.get_scene_path(i));
  1040. if (date > last_date) {
  1041. String filename = editor_data.get_scene_path(i);
  1042. editor_data.set_edited_scene(i);
  1043. _remove_edited_scene(false);
  1044. Error err = load_scene(filename, false, false, false, true);
  1045. if (err != OK) {
  1046. ERR_PRINT(vformat("Failed to load scene: %s", filename));
  1047. }
  1048. editor_data.move_edited_scene_to_index(i);
  1049. }
  1050. }
  1051. _set_current_scene(current_idx);
  1052. scene_tabs->update_scene_tabs();
  1053. disk_changed->hide();
  1054. }
  1055. void EditorNode::_reload_project_settings() {
  1056. ProjectSettings::get_singleton()->setup(ProjectSettings::get_singleton()->get_resource_path(), String(), true, true);
  1057. }
  1058. void EditorNode::_vp_resized() {
  1059. }
  1060. void EditorNode::_viewport_resized() {
  1061. Window *w = get_window();
  1062. if (w) {
  1063. was_window_windowed_last = w->get_mode() == Window::MODE_WINDOWED;
  1064. }
  1065. }
  1066. void EditorNode::_titlebar_resized() {
  1067. DisplayServer::get_singleton()->window_set_window_buttons_offset(Vector2i(title_bar->get_global_position().y + title_bar->get_size().y / 2, title_bar->get_global_position().y + title_bar->get_size().y / 2), DisplayServer::MAIN_WINDOW_ID);
  1068. const Vector3i &margin = DisplayServer::get_singleton()->window_get_safe_title_margins(DisplayServer::MAIN_WINDOW_ID);
  1069. if (left_menu_spacer) {
  1070. int w = (gui_base->is_layout_rtl()) ? margin.y : margin.x;
  1071. left_menu_spacer->set_custom_minimum_size(Size2(w, 0));
  1072. }
  1073. if (right_menu_spacer) {
  1074. int w = (gui_base->is_layout_rtl()) ? margin.x : margin.y;
  1075. right_menu_spacer->set_custom_minimum_size(Size2(w, 0));
  1076. }
  1077. if (title_bar) {
  1078. title_bar->set_custom_minimum_size(Size2(0, margin.z - title_bar->get_global_position().y));
  1079. }
  1080. }
  1081. void EditorNode::_update_undo_redo_allowed() {
  1082. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  1083. file_menu->set_item_disabled(file_menu->get_item_index(EDIT_UNDO), !undo_redo->has_undo());
  1084. file_menu->set_item_disabled(file_menu->get_item_index(EDIT_REDO), !undo_redo->has_redo());
  1085. }
  1086. void EditorNode::_node_renamed() {
  1087. if (InspectorDock::get_inspector_singleton()) {
  1088. InspectorDock::get_inspector_singleton()->update_tree();
  1089. }
  1090. }
  1091. void EditorNode::_open_command_palette() {
  1092. command_palette->open_popup();
  1093. }
  1094. Error EditorNode::load_resource(const String &p_resource, bool p_ignore_broken_deps) {
  1095. dependency_errors.clear();
  1096. Error err;
  1097. Ref<Resource> res;
  1098. if (ResourceLoader::exists(p_resource, "")) {
  1099. res = ResourceLoader::load(p_resource, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
  1100. } else if (textfile_extensions.has(p_resource.get_extension())) {
  1101. res = ScriptEditor::get_singleton()->open_file(p_resource);
  1102. } else if (other_file_extensions.has(p_resource.get_extension())) {
  1103. OS::get_singleton()->shell_open(ProjectSettings::get_singleton()->globalize_path(p_resource));
  1104. return OK;
  1105. }
  1106. ERR_FAIL_COND_V(!res.is_valid(), ERR_CANT_OPEN);
  1107. if (!p_ignore_broken_deps && dependency_errors.has(p_resource)) {
  1108. Vector<String> errors;
  1109. for (const String &E : dependency_errors[p_resource]) {
  1110. errors.push_back(E);
  1111. }
  1112. dependency_error->show(DependencyErrorDialog::MODE_RESOURCE, p_resource, errors);
  1113. dependency_errors.erase(p_resource);
  1114. return ERR_FILE_MISSING_DEPENDENCIES;
  1115. }
  1116. InspectorDock::get_singleton()->edit_resource(res);
  1117. return OK;
  1118. }
  1119. void EditorNode::edit_node(Node *p_node) {
  1120. push_item(p_node);
  1121. }
  1122. void EditorNode::edit_resource(const Ref<Resource> &p_resource) {
  1123. InspectorDock::get_singleton()->edit_resource(p_resource);
  1124. }
  1125. void EditorNode::save_resource_in_path(const Ref<Resource> &p_resource, const String &p_path) {
  1126. editor_data.apply_changes_in_editors();
  1127. if (saving_resources_in_path.has(p_resource)) {
  1128. return;
  1129. }
  1130. saving_resources_in_path.insert(p_resource);
  1131. int flg = 0;
  1132. if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) {
  1133. flg |= ResourceSaver::FLAG_COMPRESS;
  1134. }
  1135. String path = ProjectSettings::get_singleton()->localize_path(p_path);
  1136. Error err = ResourceSaver::save(p_resource, path, flg | ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS);
  1137. if (err != OK) {
  1138. if (ResourceLoader::is_imported(p_resource->get_path())) {
  1139. show_accept(TTR("Imported resources can't be saved."), TTR("OK"));
  1140. } else {
  1141. show_accept(TTR("Error saving resource!"), TTR("OK"));
  1142. }
  1143. saving_resources_in_path.erase(p_resource);
  1144. return;
  1145. }
  1146. ((Resource *)p_resource.ptr())->set_path(path);
  1147. saving_resources_in_path.erase(p_resource);
  1148. _resource_saved(p_resource, path);
  1149. emit_signal(SNAME("resource_saved"), p_resource);
  1150. editor_data.notify_resource_saved(p_resource);
  1151. }
  1152. void EditorNode::save_resource(const Ref<Resource> &p_resource) {
  1153. // If built-in resource, save the scene instead.
  1154. if (p_resource->is_built_in()) {
  1155. const String scene_path = p_resource->get_path().get_slice("::", 0);
  1156. if (!scene_path.is_empty()) {
  1157. if (ResourceLoader::exists(scene_path) && ResourceLoader::get_resource_type(scene_path) == "PackedScene") {
  1158. save_scene_if_open(scene_path);
  1159. } else {
  1160. // Not a packed scene, so save it as regular resource.
  1161. Ref<Resource> parent_resource = ResourceCache::get_ref(scene_path);
  1162. ERR_FAIL_COND_MSG(parent_resource.is_null(), "Parent resource not loaded, can't save.");
  1163. save_resource(parent_resource);
  1164. }
  1165. return;
  1166. }
  1167. }
  1168. // If the resource has been imported, ask the user to use a different path in order to save it.
  1169. String path = p_resource->get_path();
  1170. if (path.is_resource_file() && !FileAccess::exists(path + ".import")) {
  1171. save_resource_in_path(p_resource, p_resource->get_path());
  1172. } else {
  1173. save_resource_as(p_resource);
  1174. }
  1175. }
  1176. void EditorNode::save_resource_as(const Ref<Resource> &p_resource, const String &p_at_path) {
  1177. {
  1178. String path = p_resource->get_path();
  1179. if (!path.is_resource_file()) {
  1180. int srpos = path.find("::");
  1181. if (srpos != -1) {
  1182. String base = path.substr(0, srpos);
  1183. if (!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base) {
  1184. show_warning(TTR("This resource can't be saved because it does not belong to the edited scene. Make it unique first."));
  1185. return;
  1186. }
  1187. }
  1188. } else if (FileAccess::exists(path + ".import")) {
  1189. show_warning(TTR("This resource can't be saved because it was imported from another file. Make it unique first."));
  1190. return;
  1191. }
  1192. }
  1193. file->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
  1194. saving_resource = p_resource;
  1195. current_menu_option = RESOURCE_SAVE_AS;
  1196. List<String> extensions;
  1197. Ref<PackedScene> sd = memnew(PackedScene);
  1198. ResourceSaver::get_recognized_extensions(p_resource, &extensions);
  1199. file->clear_filters();
  1200. List<String> preferred;
  1201. for (const String &E : extensions) {
  1202. if (p_resource->is_class("Script") && (E == "tres" || E == "res")) {
  1203. // This serves no purpose and confused people.
  1204. continue;
  1205. }
  1206. file->add_filter("*." + E, E.to_upper());
  1207. preferred.push_back(E);
  1208. }
  1209. // Lowest priority extension.
  1210. List<String>::Element *res_element = preferred.find("res");
  1211. if (res_element) {
  1212. preferred.move_to_back(res_element);
  1213. }
  1214. // Highest priority extension.
  1215. List<String>::Element *tres_element = preferred.find("tres");
  1216. if (tres_element) {
  1217. preferred.move_to_front(tres_element);
  1218. }
  1219. if (!p_at_path.is_empty()) {
  1220. file->set_current_dir(p_at_path);
  1221. if (p_resource->get_path().is_resource_file()) {
  1222. file->set_current_file(p_resource->get_path().get_file());
  1223. } else {
  1224. if (!preferred.is_empty()) {
  1225. String resource_name_snake_case = p_resource->get_class().to_snake_case();
  1226. file->set_current_file("new_" + resource_name_snake_case + "." + preferred.front()->get().to_lower());
  1227. } else {
  1228. file->set_current_file(String());
  1229. }
  1230. }
  1231. } else if (!p_resource->get_path().is_empty()) {
  1232. file->set_current_path(p_resource->get_path());
  1233. if (!extensions.is_empty()) {
  1234. const String ext = p_resource->get_path().get_extension().to_lower();
  1235. if (extensions.find(ext) == nullptr) {
  1236. file->set_current_path(p_resource->get_path().replacen("." + ext, "." + extensions.front()->get()));
  1237. }
  1238. }
  1239. } else if (!preferred.is_empty()) {
  1240. const String resource_name_snake_case = p_resource->get_class().to_snake_case();
  1241. const String existing = "new_" + resource_name_snake_case + "." + preferred.front()->get().to_lower();
  1242. file->set_current_path(existing);
  1243. }
  1244. file->set_title(TTR("Save Resource As..."));
  1245. file->popup_file_dialog();
  1246. }
  1247. void EditorNode::ensure_uid_file(const String &p_new_resource_path) {
  1248. if (ResourceLoader::exists(p_new_resource_path) && !ResourceLoader::has_custom_uid_support(p_new_resource_path) && !FileAccess::exists(p_new_resource_path + ".uid")) {
  1249. Ref<FileAccess> f = FileAccess::open(p_new_resource_path + ".uid", FileAccess::WRITE);
  1250. if (f.is_valid()) {
  1251. const ResourceUID::ID id = ResourceUID::get_singleton()->create_id();
  1252. f->store_line(ResourceUID::get_singleton()->id_to_text(id));
  1253. }
  1254. }
  1255. }
  1256. void EditorNode::_menu_option(int p_option) {
  1257. _menu_option_confirm(p_option, false);
  1258. }
  1259. void EditorNode::_menu_confirm_current() {
  1260. _menu_option_confirm(current_menu_option, true);
  1261. }
  1262. void EditorNode::trigger_menu_option(int p_option, bool p_confirmed) {
  1263. _menu_option_confirm(p_option, p_confirmed);
  1264. }
  1265. void EditorNode::_dialog_display_save_error(String p_file, Error p_error) {
  1266. if (p_error) {
  1267. switch (p_error) {
  1268. case ERR_FILE_CANT_WRITE: {
  1269. show_accept(TTR("Can't open file for writing:") + " " + p_file.get_extension(), TTR("OK"));
  1270. } break;
  1271. case ERR_FILE_UNRECOGNIZED: {
  1272. show_accept(TTR("Requested file format unknown:") + " " + p_file.get_extension(), TTR("OK"));
  1273. } break;
  1274. default: {
  1275. show_accept(TTR("Error while saving."), TTR("OK"));
  1276. } break;
  1277. }
  1278. }
  1279. }
  1280. void EditorNode::_dialog_display_load_error(String p_file, Error p_error) {
  1281. if (p_error) {
  1282. switch (p_error) {
  1283. case ERR_CANT_OPEN: {
  1284. show_accept(vformat(TTR("Can't open file '%s'. The file could have been moved or deleted."), p_file.get_file()), TTR("OK"));
  1285. } break;
  1286. case ERR_PARSE_ERROR: {
  1287. show_accept(vformat(TTR("Error while parsing file '%s'."), p_file.get_file()), TTR("OK"));
  1288. } break;
  1289. case ERR_FILE_CORRUPT: {
  1290. show_accept(vformat(TTR("Scene file '%s' appears to be invalid/corrupt."), p_file.get_file()), TTR("OK"));
  1291. } break;
  1292. case ERR_FILE_NOT_FOUND: {
  1293. show_accept(vformat(TTR("Missing file '%s' or one of its dependencies."), p_file.get_file()), TTR("OK"));
  1294. } break;
  1295. case ERR_FILE_UNRECOGNIZED: {
  1296. show_accept(vformat(TTR("File '%s' is saved in a format that is newer than the formats supported by this version of Godot, so it can't be opened."), p_file.get_file()), TTR("OK"));
  1297. } break;
  1298. default: {
  1299. show_accept(vformat(TTR("Error while loading file '%s'."), p_file.get_file()), TTR("OK"));
  1300. } break;
  1301. }
  1302. }
  1303. }
  1304. void EditorNode::_load_editor_plugin_states_from_config(const Ref<ConfigFile> &p_config_file) {
  1305. Node *scene = editor_data.get_edited_scene_root();
  1306. if (!scene) {
  1307. return;
  1308. }
  1309. List<String> esl;
  1310. p_config_file->get_section_keys("editor_states", &esl);
  1311. Dictionary md;
  1312. for (const String &E : esl) {
  1313. Variant st = p_config_file->get_value("editor_states", E);
  1314. if (st.get_type() != Variant::NIL) {
  1315. md[E] = st;
  1316. }
  1317. }
  1318. editor_data.set_editor_plugin_states(md);
  1319. }
  1320. void EditorNode::_save_editor_states(const String &p_file, int p_idx) {
  1321. Node *scene = editor_data.get_edited_scene_root(p_idx);
  1322. if (!scene) {
  1323. return;
  1324. }
  1325. String path = EditorPaths::get_singleton()->get_project_settings_dir().path_join(p_file.get_file() + "-editstate-" + p_file.md5_text() + ".cfg");
  1326. Ref<ConfigFile> cf;
  1327. cf.instantiate();
  1328. Dictionary md;
  1329. if (p_idx < 0 || editor_data.get_edited_scene() == p_idx) {
  1330. md = editor_data.get_editor_plugin_states();
  1331. } else {
  1332. md = editor_data.get_scene_editor_states(p_idx);
  1333. }
  1334. List<Variant> keys;
  1335. md.get_key_list(&keys);
  1336. for (const Variant &E : keys) {
  1337. cf->set_value("editor_states", E, md[E]);
  1338. }
  1339. // Save the currently selected nodes.
  1340. List<Node *> selection = editor_selection->get_full_selected_node_list();
  1341. TypedArray<NodePath> selection_paths;
  1342. for (Node *selected_node : selection) {
  1343. selection_paths.push_back(selected_node->get_path());
  1344. }
  1345. cf->set_value("editor_states", "selected_nodes", selection_paths);
  1346. Error err = cf->save(path);
  1347. ERR_FAIL_COND_MSG(err != OK, "Cannot save config file to '" + path + "'.");
  1348. }
  1349. bool EditorNode::_find_and_save_resource(Ref<Resource> p_res, HashMap<Ref<Resource>, bool> &processed, int32_t flags) {
  1350. if (p_res.is_null()) {
  1351. return false;
  1352. }
  1353. if (processed.has(p_res)) {
  1354. return processed[p_res];
  1355. }
  1356. bool changed = p_res->is_edited();
  1357. p_res->set_edited(false);
  1358. bool subchanged = _find_and_save_edited_subresources(p_res.ptr(), processed, flags);
  1359. if (p_res->get_path().is_resource_file()) {
  1360. if (changed || subchanged) {
  1361. ResourceSaver::save(p_res, p_res->get_path(), flags);
  1362. }
  1363. processed[p_res] = false; // Because it's a file.
  1364. return false;
  1365. } else {
  1366. processed[p_res] = changed;
  1367. return changed;
  1368. }
  1369. }
  1370. bool EditorNode::_find_and_save_edited_subresources(Object *obj, HashMap<Ref<Resource>, bool> &processed, int32_t flags) {
  1371. bool ret_changed = false;
  1372. List<PropertyInfo> pi;
  1373. obj->get_property_list(&pi);
  1374. for (const PropertyInfo &E : pi) {
  1375. if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
  1376. continue;
  1377. }
  1378. switch (E.type) {
  1379. case Variant::OBJECT: {
  1380. Ref<Resource> res = obj->get(E.name);
  1381. if (_find_and_save_resource(res, processed, flags)) {
  1382. ret_changed = true;
  1383. }
  1384. } break;
  1385. case Variant::ARRAY: {
  1386. Array varray = obj->get(E.name);
  1387. int len = varray.size();
  1388. for (int i = 0; i < len; i++) {
  1389. const Variant &v = varray.get(i);
  1390. Ref<Resource> res = v;
  1391. if (_find_and_save_resource(res, processed, flags)) {
  1392. ret_changed = true;
  1393. }
  1394. }
  1395. } break;
  1396. case Variant::DICTIONARY: {
  1397. Dictionary d = obj->get(E.name);
  1398. List<Variant> keys;
  1399. d.get_key_list(&keys);
  1400. for (const Variant &F : keys) {
  1401. Variant v = d[F];
  1402. Ref<Resource> res = v;
  1403. if (_find_and_save_resource(res, processed, flags)) {
  1404. ret_changed = true;
  1405. }
  1406. }
  1407. } break;
  1408. default: {
  1409. }
  1410. }
  1411. }
  1412. return ret_changed;
  1413. }
  1414. void EditorNode::_save_edited_subresources(Node *scene, HashMap<Ref<Resource>, bool> &processed, int32_t flags) {
  1415. _find_and_save_edited_subresources(scene, processed, flags);
  1416. for (int i = 0; i < scene->get_child_count(); i++) {
  1417. Node *n = scene->get_child(i);
  1418. if (n->get_owner() != editor_data.get_edited_scene_root()) {
  1419. continue;
  1420. }
  1421. _save_edited_subresources(n, processed, flags);
  1422. }
  1423. }
  1424. void EditorNode::_find_node_types(Node *p_node, int &count_2d, int &count_3d) {
  1425. if (p_node->is_class("Viewport") || (p_node != editor_data.get_edited_scene_root() && p_node->get_owner() != editor_data.get_edited_scene_root())) {
  1426. return;
  1427. }
  1428. if (p_node->is_class("CanvasItem")) {
  1429. count_2d++;
  1430. } else if (p_node->is_class("Node3D")) {
  1431. count_3d++;
  1432. }
  1433. for (int i = 0; i < p_node->get_child_count(); i++) {
  1434. _find_node_types(p_node->get_child(i), count_2d, count_3d);
  1435. }
  1436. }
  1437. void EditorNode::_save_scene_with_preview(String p_file, int p_idx) {
  1438. save_scene_progress = memnew(EditorProgress("save", TTR("Saving Scene"), 4));
  1439. if (editor_data.get_edited_scene_root() != nullptr) {
  1440. save_scene_progress->step(TTR("Analyzing"), 0);
  1441. int c2d = 0;
  1442. int c3d = 0;
  1443. _find_node_types(editor_data.get_edited_scene_root(), c2d, c3d);
  1444. save_scene_progress->step(TTR("Creating Thumbnail"), 1);
  1445. // Current view?
  1446. Ref<Image> img;
  1447. // If neither 3D or 2D nodes are present, make a 1x1 black texture.
  1448. // We cannot fallback on the 2D editor, because it may not have been used yet,
  1449. // which would result in an invalid texture.
  1450. if (c3d == 0 && c2d == 0) {
  1451. img.instantiate();
  1452. img->initialize_data(1, 1, false, Image::FORMAT_RGB8);
  1453. } else if (c3d < c2d) {
  1454. Ref<ViewportTexture> viewport_texture = scene_root->get_texture();
  1455. if (viewport_texture->get_width() > 0 && viewport_texture->get_height() > 0) {
  1456. img = viewport_texture->get_image();
  1457. }
  1458. } else {
  1459. // The 3D editor may be disabled as a feature, but scenes can still be opened.
  1460. // This check prevents the preview from regenerating in case those scenes are then saved.
  1461. // The preview will be generated if no feature profile is set (as the 3D editor is enabled by default).
  1462. Ref<EditorFeatureProfile> profile = feature_profile_manager->get_current_profile();
  1463. if (!profile.is_valid() || !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_3D)) {
  1464. img = Node3DEditor::get_singleton()->get_editor_viewport(0)->get_viewport_node()->get_texture()->get_image();
  1465. }
  1466. }
  1467. if (img.is_valid() && img->get_width() > 0 && img->get_height() > 0) {
  1468. img = img->duplicate();
  1469. save_scene_progress->step(TTR("Creating Thumbnail"), 3);
  1470. int preview_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
  1471. preview_size *= EDSCALE;
  1472. // Consider a square region.
  1473. int vp_size = MIN(img->get_width(), img->get_height());
  1474. int x = (img->get_width() - vp_size) / 2;
  1475. int y = (img->get_height() - vp_size) / 2;
  1476. if (vp_size < preview_size) {
  1477. // Just square it.
  1478. img->crop_from_point(x, y, vp_size, vp_size);
  1479. } else {
  1480. int ratio = vp_size / preview_size;
  1481. int size = preview_size * MAX(1, ratio / 2);
  1482. x = (img->get_width() - size) / 2;
  1483. y = (img->get_height() - size) / 2;
  1484. img->crop_from_point(x, y, size, size);
  1485. img->resize(preview_size, preview_size, Image::INTERPOLATE_LANCZOS);
  1486. }
  1487. img->convert(Image::FORMAT_RGB8);
  1488. // Save thumbnail directly, as thumbnailer may not update due to actual scene not changing md5.
  1489. String temp_path = EditorPaths::get_singleton()->get_cache_dir();
  1490. String cache_base = ProjectSettings::get_singleton()->globalize_path(p_file).md5_text();
  1491. cache_base = temp_path.path_join("resthumb-" + cache_base);
  1492. // Does not have it, try to load a cached thumbnail.
  1493. post_process_preview(img);
  1494. img->save_png(cache_base + ".png");
  1495. }
  1496. }
  1497. save_scene_progress->step(TTR("Saving Scene"), 4);
  1498. _save_scene(p_file, p_idx);
  1499. if (!singleton->cmdline_export_mode) {
  1500. EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
  1501. }
  1502. _close_save_scene_progress();
  1503. }
  1504. void EditorNode::_close_save_scene_progress() {
  1505. memdelete_notnull(save_scene_progress);
  1506. save_scene_progress = nullptr;
  1507. }
  1508. bool EditorNode::_validate_scene_recursive(const String &p_filename, Node *p_node) {
  1509. for (int i = 0; i < p_node->get_child_count(); i++) {
  1510. Node *child = p_node->get_child(i);
  1511. if (child->get_scene_file_path() == p_filename) {
  1512. return true;
  1513. }
  1514. if (_validate_scene_recursive(p_filename, child)) {
  1515. return true;
  1516. }
  1517. }
  1518. return false;
  1519. }
  1520. int EditorNode::_save_external_resources(bool p_also_save_external_data) {
  1521. // Save external resources and its subresources if any was modified.
  1522. int flg = 0;
  1523. if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) {
  1524. flg |= ResourceSaver::FLAG_COMPRESS;
  1525. }
  1526. flg |= ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
  1527. HashSet<String> edited_resources;
  1528. int saved = 0;
  1529. List<Ref<Resource>> cached;
  1530. ResourceCache::get_cached_resources(&cached);
  1531. for (Ref<Resource> res : cached) {
  1532. if (!res->is_edited()) {
  1533. continue;
  1534. }
  1535. String path = res->get_path();
  1536. if (path.begins_with("res://")) {
  1537. int subres_pos = path.find("::");
  1538. if (subres_pos == -1) {
  1539. // Actual resource.
  1540. edited_resources.insert(path);
  1541. } else {
  1542. edited_resources.insert(path.substr(0, subres_pos));
  1543. }
  1544. }
  1545. res->set_edited(false);
  1546. }
  1547. for (const String &E : edited_resources) {
  1548. Ref<Resource> res = ResourceCache::get_ref(E);
  1549. if (!res.is_valid()) {
  1550. continue; // Maybe it was erased in a thread, who knows.
  1551. }
  1552. Ref<PackedScene> ps = res;
  1553. if (ps.is_valid()) {
  1554. continue; // Do not save PackedScenes, this will mess up the editor.
  1555. }
  1556. ResourceSaver::save(res, res->get_path(), flg);
  1557. saved++;
  1558. }
  1559. if (p_also_save_external_data) {
  1560. for (int i = 0; i < editor_data.get_editor_plugin_count(); i++) {
  1561. EditorPlugin *plugin = editor_data.get_editor_plugin(i);
  1562. if (!plugin->get_unsaved_status().is_empty()) {
  1563. plugin->save_external_data();
  1564. saved++;
  1565. }
  1566. }
  1567. }
  1568. EditorUndoRedoManager::get_singleton()->set_history_as_saved(EditorUndoRedoManager::GLOBAL_HISTORY);
  1569. return saved;
  1570. }
  1571. static void _reset_animation_mixers(Node *p_node, List<Pair<AnimationMixer *, Ref<AnimatedValuesBackup>>> *r_anim_backups) {
  1572. for (int i = 0; i < p_node->get_child_count(); i++) {
  1573. AnimationMixer *mixer = Object::cast_to<AnimationMixer>(p_node->get_child(i));
  1574. if (mixer && mixer->is_active() && mixer->is_reset_on_save_enabled() && mixer->can_apply_reset()) {
  1575. AnimationTree *tree = Object::cast_to<AnimationTree>(p_node->get_child(i));
  1576. if (tree) {
  1577. AnimationPlayer *player = Object::cast_to<AnimationPlayer>(tree->get_node_or_null(tree->get_animation_player()));
  1578. if (player && player->is_active() && player->is_reset_on_save_enabled() && player->can_apply_reset()) {
  1579. continue; // Avoid to process reset/restore many times.
  1580. }
  1581. }
  1582. Ref<AnimatedValuesBackup> backup = mixer->apply_reset();
  1583. if (backup.is_valid()) {
  1584. Pair<AnimationMixer *, Ref<AnimatedValuesBackup>> pair;
  1585. pair.first = mixer;
  1586. pair.second = backup;
  1587. r_anim_backups->push_back(pair);
  1588. }
  1589. }
  1590. _reset_animation_mixers(p_node->get_child(i), r_anim_backups);
  1591. }
  1592. }
  1593. void EditorNode::_save_scene(String p_file, int idx) {
  1594. ERR_FAIL_COND_MSG(!saving_scene.is_empty() && saving_scene == p_file, "Scene saved while already being saved!");
  1595. Node *scene = editor_data.get_edited_scene_root(idx);
  1596. if (!scene) {
  1597. show_accept(TTR("This operation can't be done without a tree root."), TTR("OK"));
  1598. return;
  1599. }
  1600. if (!scene->get_scene_file_path().is_empty() && _validate_scene_recursive(scene->get_scene_file_path(), scene)) {
  1601. show_accept(TTR("This scene can't be saved because there is a cyclic instance inclusion.\nPlease resolve it and then attempt to save again."), TTR("OK"));
  1602. return;
  1603. }
  1604. scene->propagate_notification(NOTIFICATION_EDITOR_PRE_SAVE);
  1605. editor_data.apply_changes_in_editors();
  1606. List<Pair<AnimationMixer *, Ref<AnimatedValuesBackup>>> anim_backups;
  1607. _reset_animation_mixers(scene, &anim_backups);
  1608. save_default_environment();
  1609. _save_editor_states(p_file, idx);
  1610. Ref<PackedScene> sdata;
  1611. if (ResourceCache::has(p_file)) {
  1612. // Something may be referencing this resource and we are good with that.
  1613. // We must update it, but also let the previous scene state go, as
  1614. // old version still work for referencing changes in instantiated or inherited scenes.
  1615. sdata = ResourceCache::get_ref(p_file);
  1616. if (sdata.is_valid()) {
  1617. sdata->recreate_state();
  1618. } else {
  1619. sdata.instantiate();
  1620. }
  1621. } else {
  1622. sdata.instantiate();
  1623. }
  1624. Error err = sdata->pack(scene);
  1625. if (err != OK) {
  1626. show_accept(TTR("Couldn't save scene. Likely dependencies (instances or inheritance) couldn't be satisfied."), TTR("OK"));
  1627. return;
  1628. }
  1629. int flg = 0;
  1630. if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) {
  1631. flg |= ResourceSaver::FLAG_COMPRESS;
  1632. }
  1633. flg |= ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
  1634. err = ResourceSaver::save(sdata, p_file, flg);
  1635. // This needs to be emitted before saving external resources.
  1636. emit_signal(SNAME("scene_saved"), p_file);
  1637. editor_data.notify_scene_saved(p_file);
  1638. _save_external_resources();
  1639. saving_scene = p_file; // Some editors may save scenes of built-in resources as external data, so avoid saving this scene again.
  1640. editor_data.save_editor_external_data();
  1641. saving_scene = "";
  1642. for (Pair<AnimationMixer *, Ref<AnimatedValuesBackup>> &E : anim_backups) {
  1643. E.first->restore(E.second);
  1644. }
  1645. if (err == OK) {
  1646. scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(p_file));
  1647. editor_data.set_scene_as_saved(idx);
  1648. editor_data.set_scene_modified_time(idx, FileAccess::get_modified_time(p_file));
  1649. editor_folding.save_scene_folding(scene, p_file);
  1650. _update_title();
  1651. scene_tabs->update_scene_tabs();
  1652. } else {
  1653. _dialog_display_save_error(p_file, err);
  1654. }
  1655. scene->propagate_notification(NOTIFICATION_EDITOR_POST_SAVE);
  1656. }
  1657. void EditorNode::save_all_scenes() {
  1658. project_run_bar->stop_playing();
  1659. _save_all_scenes();
  1660. }
  1661. void EditorNode::save_scene_if_open(const String &p_scene_path) {
  1662. int idx = editor_data.get_edited_scene_from_path(p_scene_path);
  1663. if (idx >= 0) {
  1664. _save_scene(p_scene_path, idx);
  1665. }
  1666. }
  1667. void EditorNode::save_scene_list(const HashSet<String> &p_scene_paths) {
  1668. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  1669. Node *scene = editor_data.get_edited_scene_root(i);
  1670. if (scene && p_scene_paths.has(scene->get_scene_file_path())) {
  1671. _save_scene(scene->get_scene_file_path(), i);
  1672. }
  1673. }
  1674. }
  1675. void EditorNode::save_before_run() {
  1676. current_menu_option = FILE_SAVE_AND_RUN;
  1677. _menu_option_confirm(FILE_SAVE_AS_SCENE, true);
  1678. file->set_title(TTR("Save scene before running..."));
  1679. }
  1680. void EditorNode::try_autosave() {
  1681. if (!bool(EDITOR_GET("run/auto_save/save_before_running"))) {
  1682. return;
  1683. }
  1684. if (unsaved_cache) {
  1685. Node *scene = editor_data.get_edited_scene_root();
  1686. if (scene && !scene->get_scene_file_path().is_empty()) { // Only autosave if there is a scene and if it has a path.
  1687. _save_scene_with_preview(scene->get_scene_file_path());
  1688. }
  1689. }
  1690. _menu_option(FILE_SAVE_ALL_SCENES);
  1691. editor_data.save_editor_external_data();
  1692. }
  1693. void EditorNode::restart_editor(bool p_goto_project_manager) {
  1694. exiting = true;
  1695. if (project_run_bar->is_playing()) {
  1696. project_run_bar->stop_playing();
  1697. }
  1698. String to_reopen;
  1699. if (!p_goto_project_manager && get_tree()->get_edited_scene_root()) {
  1700. to_reopen = get_tree()->get_edited_scene_root()->get_scene_file_path();
  1701. }
  1702. _exit_editor(EXIT_SUCCESS);
  1703. List<String> args;
  1704. for (const String &a : Main::get_forwardable_cli_arguments(Main::CLI_SCOPE_TOOL)) {
  1705. args.push_back(a);
  1706. }
  1707. if (p_goto_project_manager) {
  1708. args.push_back("--project-manager");
  1709. } else {
  1710. args.push_back("--path");
  1711. args.push_back(ProjectSettings::get_singleton()->get_resource_path());
  1712. args.push_back("-e");
  1713. }
  1714. if (!to_reopen.is_empty()) {
  1715. args.push_back(to_reopen);
  1716. }
  1717. OS::get_singleton()->set_restart_on_exit(true, args);
  1718. }
  1719. void EditorNode::_save_all_scenes() {
  1720. bool all_saved = true;
  1721. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  1722. Node *scene = editor_data.get_edited_scene_root(i);
  1723. if (scene) {
  1724. if (!scene->get_scene_file_path().is_empty() && DirAccess::exists(scene->get_scene_file_path().get_base_dir())) {
  1725. if (i != editor_data.get_edited_scene()) {
  1726. _save_scene(scene->get_scene_file_path(), i);
  1727. } else {
  1728. _save_scene_with_preview(scene->get_scene_file_path());
  1729. }
  1730. } else if (!scene->get_scene_file_path().is_empty()) {
  1731. all_saved = false;
  1732. }
  1733. }
  1734. }
  1735. if (!all_saved) {
  1736. show_warning(TTR("Could not save one or more scenes!"), TTR("Save All Scenes"));
  1737. }
  1738. save_default_environment();
  1739. }
  1740. void EditorNode::_mark_unsaved_scenes() {
  1741. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  1742. Node *node = editor_data.get_edited_scene_root(i);
  1743. if (!node) {
  1744. continue;
  1745. }
  1746. String path = node->get_scene_file_path();
  1747. if (!path.is_empty() && !FileAccess::exists(path)) {
  1748. // Mark scene tab as unsaved if the file is gone.
  1749. EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(editor_data.get_scene_history_id(i));
  1750. }
  1751. }
  1752. _update_title();
  1753. scene_tabs->update_scene_tabs();
  1754. }
  1755. void EditorNode::_dialog_action(String p_file) {
  1756. switch (current_menu_option) {
  1757. case FILE_NEW_INHERITED_SCENE: {
  1758. Node *scene = editor_data.get_edited_scene_root();
  1759. // If the previous scene is rootless, just close it in favor of the new one.
  1760. if (!scene) {
  1761. _menu_option_confirm(FILE_CLOSE, true);
  1762. }
  1763. load_scene(p_file, false, true);
  1764. } break;
  1765. case FILE_OPEN_SCENE: {
  1766. load_scene(p_file);
  1767. } break;
  1768. case SETTINGS_PICK_MAIN_SCENE: {
  1769. ProjectSettings::get_singleton()->set("application/run/main_scene", ResourceUID::path_to_uid(p_file));
  1770. ProjectSettings::get_singleton()->save();
  1771. // TODO: Would be nice to show the project manager opened with the highlighted field.
  1772. project_run_bar->play_main_scene((bool)pick_main_scene->get_meta("from_native", false));
  1773. } break;
  1774. case FILE_CLOSE:
  1775. case SCENE_TAB_CLOSE:
  1776. case FILE_SAVE_SCENE:
  1777. case FILE_SAVE_AS_SCENE: {
  1778. int scene_idx = (current_menu_option == FILE_SAVE_SCENE || current_menu_option == FILE_SAVE_AS_SCENE) ? -1 : tab_closing_idx;
  1779. if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
  1780. bool same_open_scene = false;
  1781. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  1782. if (editor_data.get_scene_path(i) == p_file && i != scene_idx) {
  1783. same_open_scene = true;
  1784. }
  1785. }
  1786. if (same_open_scene) {
  1787. show_warning(TTR("Can't overwrite scene that is still open!"));
  1788. return;
  1789. }
  1790. save_default_environment();
  1791. _save_scene_with_preview(p_file, scene_idx);
  1792. _add_to_recent_scenes(p_file);
  1793. save_editor_layout_delayed();
  1794. if (scene_idx != -1) {
  1795. _discard_changes();
  1796. } else {
  1797. // Update the path of the edited scene to ensure later do/undo action history matches.
  1798. editor_data.set_scene_path(editor_data.get_edited_scene(), p_file);
  1799. }
  1800. }
  1801. } break;
  1802. case FILE_SAVE_AND_RUN: {
  1803. if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
  1804. save_default_environment();
  1805. _save_scene_with_preview(p_file);
  1806. project_run_bar->play_custom_scene(p_file);
  1807. }
  1808. } break;
  1809. case FILE_SAVE_AND_RUN_MAIN_SCENE: {
  1810. ProjectSettings::get_singleton()->set("application/run/main_scene", ResourceUID::path_to_uid(p_file));
  1811. ProjectSettings::get_singleton()->save();
  1812. if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
  1813. save_default_environment();
  1814. _save_scene_with_preview(p_file);
  1815. project_run_bar->play_main_scene((bool)pick_main_scene->get_meta("from_native", false));
  1816. }
  1817. } break;
  1818. case FILE_EXPORT_MESH_LIBRARY: {
  1819. const Dictionary &fd_options = file_export_lib->get_selected_options();
  1820. bool merge_with_existing_library = fd_options.get(TTR("Merge With Existing"), true);
  1821. bool apply_mesh_instance_transforms = fd_options.get(TTR("Apply MeshInstance Transforms"), false);
  1822. Ref<MeshLibrary> ml;
  1823. if (merge_with_existing_library && FileAccess::exists(p_file)) {
  1824. ml = ResourceLoader::load(p_file, "MeshLibrary");
  1825. if (ml.is_null()) {
  1826. show_accept(TTR("Can't load MeshLibrary for merging!"), TTR("OK"));
  1827. return;
  1828. }
  1829. }
  1830. if (ml.is_null()) {
  1831. ml.instantiate();
  1832. }
  1833. MeshLibraryEditor::update_library_file(editor_data.get_edited_scene_root(), ml, merge_with_existing_library, apply_mesh_instance_transforms);
  1834. Error err = ResourceSaver::save(ml, p_file);
  1835. if (err) {
  1836. show_accept(TTR("Error saving MeshLibrary!"), TTR("OK"));
  1837. return;
  1838. } else if (ResourceCache::has(p_file)) {
  1839. // Make sure MeshLibrary is updated in the editor.
  1840. ResourceLoader::load(p_file)->reload_from_file();
  1841. }
  1842. } break;
  1843. case RESOURCE_SAVE:
  1844. case RESOURCE_SAVE_AS: {
  1845. ERR_FAIL_COND(saving_resource.is_null());
  1846. save_resource_in_path(saving_resource, p_file);
  1847. if (current_menu_option == RESOURCE_SAVE_AS) {
  1848. // Create .uid file when making new Resource.
  1849. ensure_uid_file(p_file);
  1850. }
  1851. saving_resource = Ref<Resource>();
  1852. ObjectID current_id = editor_history.get_current();
  1853. Object *current_obj = current_id.is_valid() ? ObjectDB::get_instance(current_id) : nullptr;
  1854. ERR_FAIL_NULL(current_obj);
  1855. current_obj->notify_property_list_changed();
  1856. } break;
  1857. case SETTINGS_LAYOUT_SAVE: {
  1858. if (p_file.is_empty()) {
  1859. return;
  1860. }
  1861. Ref<ConfigFile> config;
  1862. config.instantiate();
  1863. Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
  1864. if (err == ERR_FILE_CANT_OPEN || err == ERR_FILE_NOT_FOUND) {
  1865. config.instantiate();
  1866. } else if (err != OK) {
  1867. show_warning(TTR("An error occurred while trying to save the editor layout.\nMake sure the editor's user data path is writable."));
  1868. return;
  1869. }
  1870. editor_dock_manager->save_docks_to_config(config, p_file);
  1871. config->save(EditorSettings::get_singleton()->get_editor_layouts_config());
  1872. layout_dialog->hide();
  1873. _update_layouts_menu();
  1874. if (p_file == "Default") {
  1875. show_warning(TTR("Default editor layout overridden.\nTo restore the Default layout to its base settings, use the Delete Layout option and delete the Default layout."));
  1876. }
  1877. } break;
  1878. case SETTINGS_LAYOUT_DELETE: {
  1879. Ref<ConfigFile> config;
  1880. config.instantiate();
  1881. Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
  1882. if (err != OK || !config->has_section(p_file)) {
  1883. show_warning(TTR("Layout name not found!"));
  1884. return;
  1885. }
  1886. // Erase key values.
  1887. List<String> keys;
  1888. config->get_section_keys(p_file, &keys);
  1889. for (const String &key : keys) {
  1890. config->set_value(p_file, key, Variant());
  1891. }
  1892. config->save(EditorSettings::get_singleton()->get_editor_layouts_config());
  1893. layout_dialog->hide();
  1894. _update_layouts_menu();
  1895. if (p_file == "Default") {
  1896. show_warning(TTR("Restored the Default layout to its base settings."));
  1897. }
  1898. } break;
  1899. default: {
  1900. // Save scene?
  1901. if (file->get_file_mode() == EditorFileDialog::FILE_MODE_SAVE_FILE) {
  1902. _save_scene_with_preview(p_file);
  1903. }
  1904. } break;
  1905. }
  1906. }
  1907. bool EditorNode::_is_class_editor_disabled_by_feature_profile(const StringName &p_class) {
  1908. Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
  1909. if (profile.is_null()) {
  1910. return false;
  1911. }
  1912. StringName class_name = p_class;
  1913. while (class_name != StringName()) {
  1914. if (profile->is_class_disabled(class_name)) {
  1915. return true;
  1916. }
  1917. if (profile->is_class_editor_disabled(class_name)) {
  1918. return true;
  1919. }
  1920. class_name = ClassDB::get_parent_class(class_name);
  1921. }
  1922. return false;
  1923. }
  1924. void EditorNode::edit_item(Object *p_object, Object *p_editing_owner) {
  1925. ERR_FAIL_NULL(p_editing_owner);
  1926. // Editing for this type of object may be disabled by user's feature profile.
  1927. if (!p_object || _is_class_editor_disabled_by_feature_profile(p_object->get_class())) {
  1928. // Nothing to edit, clean up the owner context and return.
  1929. hide_unused_editors(p_editing_owner);
  1930. return;
  1931. }
  1932. // Get a list of editor plugins that can handle this type of object.
  1933. Vector<EditorPlugin *> available_plugins = editor_data.get_handling_sub_editors(p_object);
  1934. if (available_plugins.is_empty()) {
  1935. // None, clean up the owner context and return.
  1936. hide_unused_editors(p_editing_owner);
  1937. return;
  1938. }
  1939. ObjectID owner_id = p_editing_owner->get_instance_id();
  1940. // Remove editor plugins no longer used by this editing owner. Keep the ones that can
  1941. // still be reused by the new edited object.
  1942. List<EditorPlugin *> to_remove;
  1943. for (EditorPlugin *plugin : active_plugins[owner_id]) {
  1944. if (!available_plugins.has(plugin)) {
  1945. to_remove.push_back(plugin);
  1946. if (plugin->can_auto_hide()) {
  1947. _plugin_over_edit(plugin, nullptr);
  1948. } else {
  1949. // If plugin can't be hidden, make it own itself and become responsible for closing.
  1950. _plugin_over_self_own(plugin);
  1951. }
  1952. }
  1953. }
  1954. for (EditorPlugin *plugin : to_remove) {
  1955. active_plugins[owner_id].erase(plugin);
  1956. }
  1957. LocalVector<EditorPlugin *> to_over_edit;
  1958. // Send the edited object to the plugins.
  1959. for (EditorPlugin *plugin : available_plugins) {
  1960. if (active_plugins[owner_id].has(plugin)) {
  1961. // Plugin was already active, just change the object and ensure it's visible.
  1962. plugin->make_visible(true);
  1963. plugin->edit(p_object);
  1964. continue;
  1965. }
  1966. if (active_plugins.has(plugin->get_instance_id())) {
  1967. // Plugin is already active, but as self-owning, so it needs a separate check.
  1968. plugin->make_visible(true);
  1969. plugin->edit(p_object);
  1970. continue;
  1971. }
  1972. // If plugin is already associated with another owner, remove it from there first.
  1973. for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : active_plugins) {
  1974. if (kv.key != owner_id) {
  1975. EditorPropertyResource *epres = Object::cast_to<EditorPropertyResource>(ObjectDB::get_instance(kv.key));
  1976. if (epres && kv.value.has(plugin)) {
  1977. // If it's resource property editing the same resource type, fold it.
  1978. epres->fold_resource();
  1979. }
  1980. kv.value.erase(plugin);
  1981. }
  1982. }
  1983. // Activate previously inactive plugin and edit the object.
  1984. active_plugins[owner_id].insert(plugin);
  1985. // TODO: Call the function directly once a proper priority system is implemented.
  1986. to_over_edit.push_back(plugin);
  1987. }
  1988. for (EditorPlugin *plugin : to_over_edit) {
  1989. _plugin_over_edit(plugin, p_object);
  1990. }
  1991. }
  1992. void EditorNode::push_node_item(Node *p_node) {
  1993. if (p_node || Object::cast_to<Node>(InspectorDock::get_inspector_singleton()->get_edited_object()) || Object::cast_to<MultiNodeEdit>(InspectorDock::get_inspector_singleton()->get_edited_object())) {
  1994. // Don't push null if the currently edited object is not a Node.
  1995. push_item(p_node);
  1996. }
  1997. }
  1998. void EditorNode::push_item(Object *p_object, const String &p_property, bool p_inspector_only) {
  1999. if (!p_object) {
  2000. InspectorDock::get_inspector_singleton()->edit(nullptr);
  2001. NodeDock::get_singleton()->set_node(nullptr);
  2002. SceneTreeDock::get_singleton()->set_selected(nullptr);
  2003. InspectorDock::get_singleton()->update(nullptr);
  2004. hide_unused_editors();
  2005. return;
  2006. }
  2007. _add_to_history(p_object, p_property, p_inspector_only);
  2008. _edit_current();
  2009. }
  2010. void EditorNode::edit_previous_item() {
  2011. if (editor_history.previous()) {
  2012. _edit_current();
  2013. }
  2014. }
  2015. void EditorNode::push_item_no_inspector(Object *p_object) {
  2016. _add_to_history(p_object, "", false);
  2017. _edit_current(false, true);
  2018. }
  2019. void EditorNode::save_default_environment() {
  2020. Ref<Environment> fallback = get_tree()->get_root()->get_world_3d()->get_fallback_environment();
  2021. if (fallback.is_valid() && fallback->get_path().is_resource_file()) {
  2022. HashMap<Ref<Resource>, bool> processed;
  2023. _find_and_save_edited_subresources(fallback.ptr(), processed, 0);
  2024. save_resource_in_path(fallback, fallback->get_path());
  2025. }
  2026. }
  2027. void EditorNode::hide_unused_editors(const Object *p_editing_owner) {
  2028. if (p_editing_owner) {
  2029. const ObjectID id = p_editing_owner->get_instance_id();
  2030. for (EditorPlugin *plugin : active_plugins[id]) {
  2031. if (plugin->can_auto_hide()) {
  2032. _plugin_over_edit(plugin, nullptr);
  2033. } else {
  2034. _plugin_over_self_own(plugin);
  2035. }
  2036. }
  2037. active_plugins.erase(id);
  2038. } else {
  2039. // If no editing owner is provided, this method will go over all owners and check if they are valid.
  2040. // This is to sweep properties that were removed from the inspector.
  2041. List<ObjectID> to_remove;
  2042. for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : active_plugins) {
  2043. Object *context = ObjectDB::get_instance(kv.key);
  2044. if (context) {
  2045. // In case of self-owning plugins, they are disabled here if they can auto hide.
  2046. const EditorPlugin *self_owning = Object::cast_to<EditorPlugin>(context);
  2047. if (self_owning && self_owning->can_auto_hide()) {
  2048. context = nullptr;
  2049. }
  2050. }
  2051. if (!context || context->call(SNAME("_should_stop_editing"))) {
  2052. to_remove.push_back(kv.key);
  2053. for (EditorPlugin *plugin : kv.value) {
  2054. if (plugin->can_auto_hide()) {
  2055. _plugin_over_edit(plugin, nullptr);
  2056. } else {
  2057. _plugin_over_self_own(plugin);
  2058. }
  2059. }
  2060. }
  2061. }
  2062. for (const ObjectID &id : to_remove) {
  2063. active_plugins.erase(id);
  2064. }
  2065. }
  2066. }
  2067. static bool overrides_external_editor(Object *p_object) {
  2068. Script *script = Object::cast_to<Script>(p_object);
  2069. if (!script) {
  2070. return false;
  2071. }
  2072. return script->get_language()->overrides_external_editor();
  2073. }
  2074. void EditorNode::_add_to_history(const Object *p_object, const String &p_property, bool p_inspector_only) {
  2075. ObjectID id = p_object->get_instance_id();
  2076. ObjectID history_id = editor_history.get_current();
  2077. if (id != history_id) {
  2078. const MultiNodeEdit *multi_node_edit = Object::cast_to<const MultiNodeEdit>(p_object);
  2079. const MultiNodeEdit *history_multi_node_edit = Object::cast_to<const MultiNodeEdit>(ObjectDB::get_instance(history_id));
  2080. if (multi_node_edit && history_multi_node_edit && multi_node_edit->is_same_selection(history_multi_node_edit)) {
  2081. return;
  2082. }
  2083. if (p_inspector_only) {
  2084. editor_history.add_object(id, String(), true);
  2085. } else if (p_property.is_empty()) {
  2086. editor_history.add_object(id);
  2087. } else {
  2088. editor_history.add_object(id, p_property);
  2089. }
  2090. }
  2091. }
  2092. void EditorNode::_edit_current(bool p_skip_foreign, bool p_skip_inspector_update) {
  2093. ObjectID current_id = editor_history.get_current();
  2094. Object *current_obj = current_id.is_valid() ? ObjectDB::get_instance(current_id) : nullptr;
  2095. Ref<Resource> res = Object::cast_to<Resource>(current_obj);
  2096. if (p_skip_foreign && res.is_valid()) {
  2097. const int current_tab = scene_tabs->get_current_tab();
  2098. if (res->get_path().contains("::") && res->get_path().get_slice("::", 0) != editor_data.get_scene_path(current_tab)) {
  2099. // Trying to edit resource that belongs to another scene; abort.
  2100. current_obj = nullptr;
  2101. }
  2102. }
  2103. bool inspector_only = editor_history.is_current_inspector_only();
  2104. current = current_obj;
  2105. if (!current_obj) {
  2106. SceneTreeDock::get_singleton()->set_selected(nullptr);
  2107. InspectorDock::get_inspector_singleton()->edit(nullptr);
  2108. NodeDock::get_singleton()->set_node(nullptr);
  2109. InspectorDock::get_singleton()->update(nullptr);
  2110. hide_unused_editors();
  2111. return;
  2112. }
  2113. // Update the use folding setting and state.
  2114. bool disable_folding = bool(EDITOR_GET("interface/inspector/disable_folding")) || current_obj->is_class("EditorDebuggerRemoteObject");
  2115. if (InspectorDock::get_inspector_singleton()->is_using_folding() == disable_folding) {
  2116. InspectorDock::get_inspector_singleton()->set_use_folding(!disable_folding, false);
  2117. }
  2118. bool is_resource = current_obj->is_class("Resource");
  2119. bool is_node = current_obj->is_class("Node");
  2120. bool stay_in_script_editor_on_node_selected = bool(EDITOR_GET("text_editor/behavior/navigation/stay_in_script_editor_on_node_selected"));
  2121. bool skip_main_plugin = false;
  2122. String editable_info; // None by default.
  2123. bool info_is_warning = false;
  2124. if (current_obj->has_method("_is_read_only")) {
  2125. if (current_obj->call("_is_read_only")) {
  2126. editable_info = TTR("This object is marked as read-only, so it's not editable.");
  2127. }
  2128. }
  2129. if (is_resource) {
  2130. Resource *current_res = Object::cast_to<Resource>(current_obj);
  2131. ERR_FAIL_NULL(current_res);
  2132. if (!p_skip_inspector_update) {
  2133. InspectorDock::get_inspector_singleton()->edit(current_res);
  2134. SceneTreeDock::get_singleton()->set_selected(nullptr);
  2135. NodeDock::get_singleton()->set_node(nullptr);
  2136. InspectorDock::get_singleton()->update(nullptr);
  2137. ImportDock::get_singleton()->set_edit_path(current_res->get_path());
  2138. }
  2139. int subr_idx = current_res->get_path().find("::");
  2140. if (subr_idx != -1) {
  2141. String base_path = current_res->get_path().substr(0, subr_idx);
  2142. if (FileAccess::exists(base_path + ".import")) {
  2143. if (!base_path.is_resource_file()) {
  2144. if (get_edited_scene() && get_edited_scene()->get_scene_file_path() == base_path) {
  2145. info_is_warning = true;
  2146. }
  2147. }
  2148. editable_info = TTR("This resource belongs to a scene that was imported, so it's not editable.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
  2149. } else if ((!get_edited_scene() || get_edited_scene()->get_scene_file_path() != base_path) && ResourceLoader::get_resource_type(base_path) == "PackedScene") {
  2150. editable_info = TTR("This resource belongs to a scene that was instantiated or inherited.\nChanges to it must be made inside the original scene.");
  2151. }
  2152. } else if (current_res->get_path().is_resource_file()) {
  2153. if (FileAccess::exists(current_res->get_path() + ".import")) {
  2154. editable_info = TTR("This resource was imported, so it's not editable. Change its settings in the import panel and then re-import.");
  2155. }
  2156. }
  2157. } else if (is_node) {
  2158. Node *current_node = Object::cast_to<Node>(current_obj);
  2159. ERR_FAIL_NULL(current_node);
  2160. InspectorDock::get_inspector_singleton()->edit(current_node);
  2161. if (current_node->is_inside_tree()) {
  2162. NodeDock::get_singleton()->set_node(current_node);
  2163. SceneTreeDock::get_singleton()->set_selected(current_node);
  2164. SceneTreeDock::get_singleton()->set_selection({ current_node });
  2165. InspectorDock::get_singleton()->update(current_node);
  2166. if (!inspector_only && !skip_main_plugin) {
  2167. skip_main_plugin = stay_in_script_editor_on_node_selected && !ScriptEditor::get_singleton()->is_editor_floating() && ScriptEditor::get_singleton()->is_visible_in_tree();
  2168. }
  2169. } else {
  2170. NodeDock::get_singleton()->set_node(nullptr);
  2171. SceneTreeDock::get_singleton()->set_selected(nullptr);
  2172. InspectorDock::get_singleton()->update(nullptr);
  2173. }
  2174. if (get_edited_scene() && !get_edited_scene()->get_scene_file_path().is_empty()) {
  2175. String source_scene = get_edited_scene()->get_scene_file_path();
  2176. if (FileAccess::exists(source_scene + ".import")) {
  2177. editable_info = TTR("This scene was imported, so changes to it won't be kept.\nInstantiating or inheriting it will allow you to make changes to it.\nPlease read the documentation relevant to importing scenes to better understand this workflow.");
  2178. info_is_warning = true;
  2179. }
  2180. }
  2181. } else {
  2182. Node *selected_node = nullptr;
  2183. Vector<Node *> multi_nodes;
  2184. if (current_obj->is_class("MultiNodeEdit")) {
  2185. Node *scene = get_edited_scene();
  2186. if (scene) {
  2187. MultiNodeEdit *multi_node_edit = Object::cast_to<MultiNodeEdit>(current_obj);
  2188. int node_count = multi_node_edit->get_node_count();
  2189. if (node_count > 0) {
  2190. for (int node_index = 0; node_index < node_count; ++node_index) {
  2191. Node *node = scene->get_node(multi_node_edit->get_node(node_index));
  2192. if (node) {
  2193. multi_nodes.push_back(node);
  2194. }
  2195. }
  2196. if (!multi_nodes.is_empty()) {
  2197. // Pick the top-most node.
  2198. multi_nodes.sort_custom<Node::Comparator>();
  2199. selected_node = multi_nodes[0];
  2200. }
  2201. }
  2202. }
  2203. }
  2204. InspectorDock::get_inspector_singleton()->edit(current_obj);
  2205. NodeDock::get_singleton()->set_node(nullptr);
  2206. SceneTreeDock::get_singleton()->set_selected(selected_node);
  2207. SceneTreeDock::get_singleton()->set_selection(multi_nodes);
  2208. InspectorDock::get_singleton()->update(nullptr);
  2209. }
  2210. InspectorDock::get_singleton()->set_info(
  2211. info_is_warning ? TTR("Changes may be lost!") : TTR("This object is read-only."),
  2212. editable_info,
  2213. info_is_warning);
  2214. Object *editor_owner = (is_node || current_obj->is_class("MultiNodeEdit")) ? (Object *)SceneTreeDock::get_singleton() : is_resource ? (Object *)InspectorDock::get_inspector_singleton()
  2215. : (Object *)this;
  2216. // Take care of the main editor plugin.
  2217. if (!inspector_only) {
  2218. EditorPlugin *main_plugin = editor_data.get_handling_main_editor(current_obj);
  2219. int plugin_index = editor_main_screen->get_plugin_index(main_plugin);
  2220. if (main_plugin && plugin_index >= 0 && !editor_main_screen->is_button_enabled(plugin_index)) {
  2221. main_plugin = nullptr;
  2222. }
  2223. EditorPlugin *editor_plugin_screen = editor_main_screen->get_selected_plugin();
  2224. ObjectID editor_owner_id = editor_owner->get_instance_id();
  2225. if (main_plugin && !skip_main_plugin) {
  2226. // Special case if use of external editor is true.
  2227. Resource *current_res = Object::cast_to<Resource>(current_obj);
  2228. if (main_plugin->get_plugin_name() == "Script" && current_res && !current_res->is_built_in() && (bool(EDITOR_GET("text_editor/external/use_external_editor")) || overrides_external_editor(current_obj))) {
  2229. if (!changing_scene) {
  2230. main_plugin->edit(current_obj);
  2231. }
  2232. }
  2233. else if (main_plugin != editor_plugin_screen && (!ScriptEditor::get_singleton() || !ScriptEditor::get_singleton()->is_visible_in_tree() || ScriptEditor::get_singleton()->can_take_away_focus())) {
  2234. // Unedit previous plugin.
  2235. editor_plugin_screen->edit(nullptr);
  2236. active_plugins[editor_owner_id].erase(editor_plugin_screen);
  2237. // Update screen main_plugin.
  2238. editor_main_screen->select(plugin_index);
  2239. main_plugin->edit(current_obj);
  2240. } else {
  2241. editor_plugin_screen->edit(current_obj);
  2242. }
  2243. is_main_screen_editing = true;
  2244. } else if (!main_plugin && editor_plugin_screen && is_main_screen_editing) {
  2245. editor_plugin_screen->edit(nullptr);
  2246. is_main_screen_editing = false;
  2247. }
  2248. edit_item(current_obj, editor_owner);
  2249. }
  2250. InspectorDock::get_singleton()->update(current_obj);
  2251. }
  2252. void EditorNode::_android_build_source_selected(const String &p_file) {
  2253. export_template_manager->install_android_template_from_file(p_file, android_export_preset);
  2254. }
  2255. void EditorNode::_android_export_preset_selected(int p_index) {
  2256. if (p_index >= 0) {
  2257. android_export_preset = EditorExport::get_singleton()->get_export_preset(choose_android_export_profile->get_item_id(p_index));
  2258. } else {
  2259. android_export_preset.unref();
  2260. }
  2261. install_android_build_template_message->set_text(vformat(TTR(INSTALL_ANDROID_BUILD_TEMPLATE_MESSAGE), export_template_manager->get_android_build_directory(android_export_preset)));
  2262. }
  2263. void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
  2264. if (!p_confirmed) { // FIXME: this may be a hack.
  2265. current_menu_option = (MenuOptions)p_option;
  2266. }
  2267. switch (p_option) {
  2268. case FILE_NEW_SCENE: {
  2269. new_scene();
  2270. } break;
  2271. case FILE_NEW_INHERITED_SCENE:
  2272. case FILE_OPEN_SCENE: {
  2273. file->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  2274. List<String> extensions;
  2275. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
  2276. file->clear_filters();
  2277. for (const String &extension : extensions) {
  2278. file->add_filter("*." + extension, extension.to_upper());
  2279. }
  2280. Node *scene = editor_data.get_edited_scene_root();
  2281. if (scene) {
  2282. file->set_current_path(scene->get_scene_file_path());
  2283. };
  2284. file->set_title(p_option == FILE_OPEN_SCENE ? TTR("Open Scene") : TTR("Open Base Scene"));
  2285. file->popup_file_dialog();
  2286. } break;
  2287. case FILE_QUICK_OPEN: {
  2288. quick_open_dialog->popup_dialog({ "Resource" }, callable_mp(this, &EditorNode::_quick_opened));
  2289. } break;
  2290. case FILE_QUICK_OPEN_SCENE: {
  2291. quick_open_dialog->popup_dialog({ "PackedScene" }, callable_mp(this, &EditorNode::_quick_opened));
  2292. } break;
  2293. case FILE_QUICK_OPEN_SCRIPT: {
  2294. quick_open_dialog->popup_dialog({ "Script" }, callable_mp(this, &EditorNode::_quick_opened));
  2295. } break;
  2296. case FILE_OPEN_PREV: {
  2297. if (previous_scenes.is_empty()) {
  2298. break;
  2299. }
  2300. opening_prev = true;
  2301. open_request(previous_scenes.back()->get());
  2302. previous_scenes.pop_back();
  2303. } break;
  2304. case FILE_CLOSE_OTHERS: {
  2305. tab_closing_menu_option = -1;
  2306. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  2307. if (i == editor_data.get_edited_scene()) {
  2308. continue;
  2309. }
  2310. tabs_to_close.push_back(editor_data.get_scene_path(i));
  2311. }
  2312. _proceed_closing_scene_tabs();
  2313. } break;
  2314. case FILE_CLOSE_RIGHT: {
  2315. tab_closing_menu_option = -1;
  2316. for (int i = editor_data.get_edited_scene() + 1; i < editor_data.get_edited_scene_count(); i++) {
  2317. tabs_to_close.push_back(editor_data.get_scene_path(i));
  2318. }
  2319. _proceed_closing_scene_tabs();
  2320. } break;
  2321. case FILE_CLOSE_ALL: {
  2322. tab_closing_menu_option = -1;
  2323. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  2324. tabs_to_close.push_back(editor_data.get_scene_path(i));
  2325. }
  2326. _proceed_closing_scene_tabs();
  2327. } break;
  2328. case FILE_CLOSE: {
  2329. _scene_tab_closed(editor_data.get_edited_scene());
  2330. } break;
  2331. case FILE_SAVE_SCENE_SILENTLY: {
  2332. // Save scene without displaying progress dialog. Used to work around
  2333. // errors about parent node being busy setting up children
  2334. // when Save on Focus Loss kicks in.
  2335. Node *scene = editor_data.get_edited_scene_root();
  2336. if (scene && !scene->get_scene_file_path().is_empty() && DirAccess::exists(scene->get_scene_file_path().get_base_dir())) {
  2337. _save_scene(scene->get_scene_file_path());
  2338. save_editor_layout_delayed();
  2339. }
  2340. } break;
  2341. case SCENE_TAB_CLOSE:
  2342. case FILE_SAVE_SCENE: {
  2343. int scene_idx = (p_option == FILE_SAVE_SCENE) ? -1 : tab_closing_idx;
  2344. Node *scene = editor_data.get_edited_scene_root(scene_idx);
  2345. if (scene && !scene->get_scene_file_path().is_empty()) {
  2346. if (DirAccess::exists(scene->get_scene_file_path().get_base_dir())) {
  2347. if (scene_idx != editor_data.get_edited_scene()) {
  2348. _save_scene_with_preview(scene->get_scene_file_path(), scene_idx);
  2349. } else {
  2350. _save_scene_with_preview(scene->get_scene_file_path());
  2351. }
  2352. if (scene_idx != -1) {
  2353. _discard_changes();
  2354. }
  2355. save_editor_layout_delayed();
  2356. } else {
  2357. show_save_accept(vformat(TTR("%s no longer exists! Please specify a new save location."), scene->get_scene_file_path().get_base_dir()), TTR("OK"));
  2358. }
  2359. break;
  2360. }
  2361. [[fallthrough]];
  2362. }
  2363. case FILE_SAVE_AS_SCENE: {
  2364. int scene_idx = (p_option == FILE_SAVE_SCENE || p_option == FILE_SAVE_AS_SCENE) ? -1 : tab_closing_idx;
  2365. Node *scene = editor_data.get_edited_scene_root(scene_idx);
  2366. if (!scene) {
  2367. if (p_option == FILE_SAVE_SCENE) {
  2368. // Pressing Ctrl + S saves the current script if a scene is currently open, but it won't if the scene has no root node.
  2369. // Work around this by explicitly saving the script in this case (similar to pressing Ctrl + Alt + S).
  2370. ScriptEditor::get_singleton()->save_current_script();
  2371. }
  2372. const int saved = _save_external_resources(true);
  2373. if (saved > 0) {
  2374. EditorToaster::get_singleton()->popup_str(vformat(TTR("The current scene has no root node, but %d modified external resource(s) and/or plugin data were saved anyway."), saved), EditorToaster::SEVERITY_INFO);
  2375. } else if (p_option == FILE_SAVE_AS_SCENE) {
  2376. // Don't show this dialog when pressing Ctrl + S to avoid interfering with script saving.
  2377. show_accept(
  2378. TTR("A root node is required to save the scene. You can add a root node using the Scene tree dock."),
  2379. TTR("OK"));
  2380. }
  2381. break;
  2382. }
  2383. file->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
  2384. List<String> extensions;
  2385. Ref<PackedScene> sd = memnew(PackedScene);
  2386. ResourceSaver::get_recognized_extensions(sd, &extensions);
  2387. file->clear_filters();
  2388. for (const String &extension : extensions) {
  2389. file->add_filter("*." + extension, extension.to_upper());
  2390. }
  2391. if (!scene->get_scene_file_path().is_empty()) {
  2392. String path = scene->get_scene_file_path();
  2393. file->set_current_path(path);
  2394. if (extensions.size()) {
  2395. String ext = path.get_extension().to_lower();
  2396. if (extensions.find(ext) == nullptr) {
  2397. file->set_current_path(path.replacen("." + ext, "." + extensions.front()->get()));
  2398. }
  2399. }
  2400. } else if (extensions.size()) {
  2401. String root_name = scene->get_name();
  2402. root_name = EditorNode::adjust_scene_name_casing(root_name);
  2403. file->set_current_path(root_name + "." + extensions.front()->get().to_lower());
  2404. }
  2405. file->set_title(TTR("Save Scene As..."));
  2406. file->popup_file_dialog();
  2407. } break;
  2408. case FILE_SAVE_ALL_SCENES: {
  2409. _save_all_scenes();
  2410. } break;
  2411. case FILE_RUN_SCENE: {
  2412. project_run_bar->play_current_scene();
  2413. } break;
  2414. case FILE_EXPORT_PROJECT: {
  2415. project_export->popup_export();
  2416. } break;
  2417. case FILE_EXTERNAL_OPEN_SCENE: {
  2418. if (unsaved_cache && !p_confirmed) {
  2419. confirmation->set_ok_button_text(TTR("Open"));
  2420. confirmation->set_text(TTR("Current scene not saved. Open anyway?"));
  2421. confirmation->popup_centered();
  2422. break;
  2423. }
  2424. bool oprev = opening_prev;
  2425. Error err = load_scene(external_file);
  2426. if (err == OK && oprev) {
  2427. previous_scenes.pop_back();
  2428. opening_prev = false;
  2429. }
  2430. } break;
  2431. case EDIT_UNDO: {
  2432. if ((int)Input::get_singleton()->get_mouse_button_mask() & 0x7) {
  2433. log->add_message(TTR("Can't undo while mouse buttons are pressed."), EditorLog::MSG_TYPE_EDITOR);
  2434. } else {
  2435. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  2436. String action = undo_redo->get_current_action_name();
  2437. int id = undo_redo->get_current_action_history_id();
  2438. if (!undo_redo->undo()) {
  2439. log->add_message(TTR("Nothing to undo."), EditorLog::MSG_TYPE_EDITOR);
  2440. } else if (!action.is_empty()) {
  2441. switch (id) {
  2442. case EditorUndoRedoManager::GLOBAL_HISTORY:
  2443. log->add_message(vformat(TTR("Global Undo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
  2444. break;
  2445. case EditorUndoRedoManager::REMOTE_HISTORY:
  2446. log->add_message(vformat(TTR("Remote Undo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
  2447. break;
  2448. default:
  2449. log->add_message(vformat(TTR("Scene Undo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
  2450. }
  2451. }
  2452. }
  2453. } break;
  2454. case EDIT_REDO: {
  2455. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  2456. if ((int)Input::get_singleton()->get_mouse_button_mask() & 0x7) {
  2457. log->add_message(TTR("Can't redo while mouse buttons are pressed."), EditorLog::MSG_TYPE_EDITOR);
  2458. } else {
  2459. if (!undo_redo->redo()) {
  2460. log->add_message(TTR("Nothing to redo."), EditorLog::MSG_TYPE_EDITOR);
  2461. } else {
  2462. String action = undo_redo->get_current_action_name();
  2463. if (action.is_empty()) {
  2464. break;
  2465. }
  2466. switch (undo_redo->get_current_action_history_id()) {
  2467. case EditorUndoRedoManager::GLOBAL_HISTORY:
  2468. log->add_message(vformat(TTR("Global Redo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
  2469. break;
  2470. case EditorUndoRedoManager::REMOTE_HISTORY:
  2471. log->add_message(vformat(TTR("Remote Redo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
  2472. break;
  2473. default:
  2474. log->add_message(vformat(TTR("Scene Redo: %s"), action), EditorLog::MSG_TYPE_EDITOR);
  2475. }
  2476. }
  2477. }
  2478. } break;
  2479. case EDIT_RELOAD_SAVED_SCENE: {
  2480. Node *scene = get_edited_scene();
  2481. if (!scene) {
  2482. break;
  2483. }
  2484. String filename = scene->get_scene_file_path();
  2485. if (filename.is_empty()) {
  2486. show_warning(TTR("Can't reload a scene that was never saved."));
  2487. break;
  2488. }
  2489. if (unsaved_cache && !p_confirmed) {
  2490. confirmation->set_ok_button_text(TTR("Reload Saved Scene"));
  2491. confirmation->set_text(
  2492. TTR("The current scene has unsaved changes.\nReload the saved scene anyway? This action cannot be undone."));
  2493. confirmation->popup_centered();
  2494. break;
  2495. }
  2496. int cur_idx = editor_data.get_edited_scene();
  2497. _remove_edited_scene();
  2498. Error err = load_scene(filename);
  2499. if (err != OK) {
  2500. ERR_PRINT("Failed to load scene");
  2501. }
  2502. editor_data.move_edited_scene_to_index(cur_idx);
  2503. EditorUndoRedoManager::get_singleton()->clear_history(editor_data.get_current_edited_scene_history_id(), false);
  2504. scene_tabs->set_current_tab(cur_idx);
  2505. } break;
  2506. case FILE_SHOW_IN_FILESYSTEM: {
  2507. String path = editor_data.get_scene_path(editor_data.get_edited_scene());
  2508. if (!path.is_empty()) {
  2509. FileSystemDock::get_singleton()->navigate_to_path(path);
  2510. }
  2511. } break;
  2512. case RUN_SETTINGS: {
  2513. project_settings_editor->popup_project_settings();
  2514. } break;
  2515. case FILE_INSTALL_ANDROID_SOURCE: {
  2516. if (p_confirmed) {
  2517. if (export_template_manager->is_android_template_installed(android_export_preset)) {
  2518. remove_android_build_template->set_text(vformat(TTR(REMOVE_ANDROID_BUILD_TEMPLATE_MESSAGE), export_template_manager->get_android_build_directory(android_export_preset)));
  2519. remove_android_build_template->popup_centered();
  2520. } else if (!export_template_manager->can_install_android_template(android_export_preset)) {
  2521. gradle_build_manage_templates->popup_centered();
  2522. } else {
  2523. export_template_manager->install_android_template(android_export_preset);
  2524. }
  2525. } else {
  2526. bool has_custom_gradle_build = false;
  2527. choose_android_export_profile->clear();
  2528. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  2529. Ref<EditorExportPreset> export_preset = EditorExport::get_singleton()->get_export_preset(i);
  2530. if (export_preset->get_platform()->get_class_name() == "EditorExportPlatformAndroid" && (bool)export_preset->get("gradle_build/use_gradle_build")) {
  2531. choose_android_export_profile->add_item(export_preset->get_name(), i);
  2532. String gradle_build_directory = export_preset->get("gradle_build/gradle_build_directory");
  2533. String android_source_template = export_preset->get("gradle_build/android_source_template");
  2534. if (!android_source_template.is_empty() || (gradle_build_directory != "" && gradle_build_directory != "res://android")) {
  2535. has_custom_gradle_build = true;
  2536. }
  2537. }
  2538. }
  2539. _android_export_preset_selected(choose_android_export_profile->get_item_count() >= 1 ? 0 : -1);
  2540. if (choose_android_export_profile->get_item_count() > 1 && has_custom_gradle_build) {
  2541. // If there's multiple options and at least one of them uses a custom gradle build then prompt the user to choose.
  2542. choose_android_export_profile->show();
  2543. install_android_build_template->popup_centered();
  2544. } else {
  2545. choose_android_export_profile->hide();
  2546. if (export_template_manager->is_android_template_installed(android_export_preset)) {
  2547. remove_android_build_template->set_text(vformat(TTR(REMOVE_ANDROID_BUILD_TEMPLATE_MESSAGE), export_template_manager->get_android_build_directory(android_export_preset)));
  2548. remove_android_build_template->popup_centered();
  2549. } else if (export_template_manager->can_install_android_template(android_export_preset)) {
  2550. install_android_build_template->popup_centered();
  2551. } else {
  2552. gradle_build_manage_templates->popup_centered();
  2553. }
  2554. }
  2555. }
  2556. } break;
  2557. case RUN_USER_DATA_FOLDER: {
  2558. // Ensure_user_data_dir() to prevent the edge case: "Open User Data Folder" won't work after the project was renamed in ProjectSettingsEditor unless the project is saved.
  2559. OS::get_singleton()->ensure_user_data_dir();
  2560. OS::get_singleton()->shell_show_in_file_manager(OS::get_singleton()->get_user_data_dir(), true);
  2561. } break;
  2562. case FILE_EXPLORE_ANDROID_BUILD_TEMPLATES: {
  2563. OS::get_singleton()->shell_show_in_file_manager(ProjectSettings::get_singleton()->globalize_path(export_template_manager->get_android_build_directory(android_export_preset).get_base_dir()), true);
  2564. } break;
  2565. case FILE_QUIT:
  2566. case RUN_PROJECT_MANAGER:
  2567. case RELOAD_CURRENT_PROJECT: {
  2568. if (p_confirmed && plugin_to_save) {
  2569. plugin_to_save->save_external_data();
  2570. p_confirmed = false;
  2571. }
  2572. if (!p_confirmed) {
  2573. bool save_each = EDITOR_GET("interface/editor/save_each_scene_on_quit");
  2574. if (_next_unsaved_scene(!save_each) == -1) {
  2575. if (EditorUndoRedoManager::get_singleton()->is_history_unsaved(EditorUndoRedoManager::GLOBAL_HISTORY)) {
  2576. if (p_option == RELOAD_CURRENT_PROJECT) {
  2577. save_confirmation->set_ok_button_text(TTR("Save & Reload"));
  2578. save_confirmation->set_text(TTR("Save modified resources before reloading?"));
  2579. } else {
  2580. save_confirmation->set_ok_button_text(TTR("Save & Quit"));
  2581. save_confirmation->set_text(TTR("Save modified resources before closing?"));
  2582. }
  2583. save_confirmation->reset_size();
  2584. save_confirmation->popup_centered();
  2585. break;
  2586. }
  2587. plugin_to_save = nullptr;
  2588. for (int i = 0; i < editor_data.get_editor_plugin_count(); i++) {
  2589. const String unsaved_status = editor_data.get_editor_plugin(i)->get_unsaved_status();
  2590. if (!unsaved_status.is_empty()) {
  2591. if (p_option == RELOAD_CURRENT_PROJECT) {
  2592. save_confirmation->set_ok_button_text(TTR("Save & Reload"));
  2593. save_confirmation->set_text(unsaved_status);
  2594. } else {
  2595. save_confirmation->set_ok_button_text(TTR("Save & Quit"));
  2596. save_confirmation->set_text(unsaved_status);
  2597. }
  2598. save_confirmation->reset_size();
  2599. save_confirmation->popup_centered();
  2600. plugin_to_save = editor_data.get_editor_plugin(i);
  2601. break;
  2602. }
  2603. }
  2604. if (plugin_to_save) {
  2605. break;
  2606. }
  2607. _discard_changes();
  2608. break;
  2609. }
  2610. if (save_each) {
  2611. tab_closing_menu_option = current_menu_option;
  2612. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  2613. tabs_to_close.push_back(editor_data.get_scene_path(i));
  2614. }
  2615. _proceed_closing_scene_tabs();
  2616. } else {
  2617. String unsaved_scenes;
  2618. int i = _next_unsaved_scene(true, 0);
  2619. while (i != -1) {
  2620. unsaved_scenes += "\n " + editor_data.get_edited_scene_root(i)->get_scene_file_path();
  2621. i = _next_unsaved_scene(true, ++i);
  2622. }
  2623. if (p_option == RELOAD_CURRENT_PROJECT) {
  2624. save_confirmation->set_ok_button_text(TTR("Save & Reload"));
  2625. save_confirmation->set_text(TTR("Save changes to the following scene(s) before reloading?") + unsaved_scenes);
  2626. } else {
  2627. save_confirmation->set_ok_button_text(TTR("Save & Quit"));
  2628. save_confirmation->set_text((p_option == FILE_QUIT ? TTR("Save changes to the following scene(s) before quitting?") : TTR("Save changes to the following scene(s) before opening Project Manager?")) + unsaved_scenes);
  2629. }
  2630. save_confirmation->reset_size();
  2631. save_confirmation->popup_centered();
  2632. }
  2633. DisplayServer::get_singleton()->window_request_attention();
  2634. break;
  2635. }
  2636. _save_external_resources();
  2637. _discard_changes();
  2638. } break;
  2639. case SETTINGS_UPDATE_CONTINUOUSLY: {
  2640. EditorSettings::get_singleton()->set("interface/editor/update_continuously", true);
  2641. _update_update_spinner();
  2642. show_accept(TTR("This option is deprecated. Situations where refresh must be forced are now considered a bug. Please report."), TTR("OK"));
  2643. } break;
  2644. case SETTINGS_UPDATE_WHEN_CHANGED: {
  2645. EditorSettings::get_singleton()->set("interface/editor/update_continuously", false);
  2646. _update_update_spinner();
  2647. } break;
  2648. case SETTINGS_UPDATE_SPINNER_HIDE: {
  2649. EditorSettings::get_singleton()->set("interface/editor/show_update_spinner", 2); // Disabled
  2650. _update_update_spinner();
  2651. } break;
  2652. case SETTINGS_PREFERENCES: {
  2653. editor_settings_dialog->popup_edit_settings();
  2654. } break;
  2655. case SETTINGS_EDITOR_DATA_FOLDER: {
  2656. OS::get_singleton()->shell_show_in_file_manager(EditorPaths::get_singleton()->get_data_dir(), true);
  2657. } break;
  2658. case SETTINGS_EDITOR_CONFIG_FOLDER: {
  2659. OS::get_singleton()->shell_show_in_file_manager(EditorPaths::get_singleton()->get_config_dir(), true);
  2660. } break;
  2661. case SETTINGS_MANAGE_EXPORT_TEMPLATES: {
  2662. export_template_manager->popup_manager();
  2663. } break;
  2664. case SETTINGS_MANAGE_FBX_IMPORTER: {
  2665. #if !defined(ANDROID_ENABLED) && !defined(WEB_ENABLED)
  2666. fbx_importer_manager->show_dialog();
  2667. #endif
  2668. } break;
  2669. case SETTINGS_INSTALL_ANDROID_BUILD_TEMPLATE: {
  2670. gradle_build_manage_templates->hide();
  2671. file_android_build_source->popup_centered_ratio();
  2672. } break;
  2673. case SETTINGS_MANAGE_FEATURE_PROFILES: {
  2674. feature_profile_manager->popup_centered_clamped(Size2(900, 800) * EDSCALE, 0.8);
  2675. } break;
  2676. case SETTINGS_TOGGLE_FULLSCREEN: {
  2677. DisplayServer::WindowMode mode = DisplayServer::get_singleton()->window_get_mode();
  2678. if (mode == DisplayServer::WINDOW_MODE_FULLSCREEN || mode == DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2679. DisplayServer::get_singleton()->window_set_mode(prev_mode);
  2680. } else {
  2681. prev_mode = mode;
  2682. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_FULLSCREEN);
  2683. }
  2684. } break;
  2685. case EDITOR_SCREENSHOT: {
  2686. screenshot_timer->start();
  2687. } break;
  2688. case SETTINGS_PICK_MAIN_SCENE: {
  2689. file->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  2690. List<String> extensions;
  2691. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
  2692. file->clear_filters();
  2693. for (const String &extension : extensions) {
  2694. file->add_filter("*." + extension, extension.to_upper());
  2695. }
  2696. Node *scene = editor_data.get_edited_scene_root();
  2697. if (scene) {
  2698. file->set_current_path(scene->get_scene_file_path());
  2699. }
  2700. file->set_title(TTR("Pick a Main Scene"));
  2701. file->popup_file_dialog();
  2702. } break;
  2703. case HELP_SEARCH: {
  2704. emit_signal(SNAME("request_help_search"), "");
  2705. } break;
  2706. case HELP_COMMAND_PALETTE: {
  2707. command_palette->open_popup();
  2708. } break;
  2709. case HELP_DOCS: {
  2710. OS::get_singleton()->shell_open(VERSION_DOCS_URL "/");
  2711. } break;
  2712. case HELP_FORUM: {
  2713. OS::get_singleton()->shell_open("https://forum.godotengine.org/");
  2714. } break;
  2715. case HELP_REPORT_A_BUG: {
  2716. OS::get_singleton()->shell_open("https://github.com/godotengine/godot/issues");
  2717. } break;
  2718. case HELP_COPY_SYSTEM_INFO: {
  2719. String info = _get_system_info();
  2720. DisplayServer::get_singleton()->clipboard_set(info);
  2721. } break;
  2722. case HELP_SUGGEST_A_FEATURE: {
  2723. OS::get_singleton()->shell_open("https://github.com/godotengine/godot-proposals#readme");
  2724. } break;
  2725. case HELP_SEND_DOCS_FEEDBACK: {
  2726. OS::get_singleton()->shell_open("https://github.com/godotengine/godot-docs/issues");
  2727. } break;
  2728. case HELP_COMMUNITY: {
  2729. OS::get_singleton()->shell_open("https://godotengine.org/community");
  2730. } break;
  2731. case HELP_ABOUT: {
  2732. about->popup_centered(Size2(780, 500) * EDSCALE);
  2733. } break;
  2734. case HELP_SUPPORT_GODOT_DEVELOPMENT: {
  2735. OS::get_singleton()->shell_open("https://godotengine.org/donate");
  2736. } break;
  2737. case SET_RENDERER_NAME_SAVE_AND_RESTART: {
  2738. ProjectSettings::get_singleton()->set("rendering/renderer/rendering_method", renderer_request);
  2739. if (renderer_request == "mobile" || renderer_request == "gl_compatibility") {
  2740. // Also change the mobile override if changing to a compatible rendering method.
  2741. // This prevents visual discrepancies between desktop and mobile platforms.
  2742. ProjectSettings::get_singleton()->set("rendering/renderer/rendering_method.mobile", renderer_request);
  2743. } else if (renderer_request == "forward_plus") {
  2744. // Use the equivalent mobile rendering method. This prevents the rendering method from staying
  2745. // on its old choice if moving from `gl_compatibility` to `forward_plus`.
  2746. ProjectSettings::get_singleton()->set("rendering/renderer/rendering_method.mobile", "mobile");
  2747. }
  2748. ProjectSettings::get_singleton()->save();
  2749. save_all_scenes();
  2750. restart_editor();
  2751. } break;
  2752. }
  2753. }
  2754. String EditorNode::adjust_scene_name_casing(const String &p_root_name) {
  2755. switch (GLOBAL_GET("editor/naming/scene_name_casing").operator int()) {
  2756. case SCENE_NAME_CASING_AUTO:
  2757. // Use casing of the root node.
  2758. break;
  2759. case SCENE_NAME_CASING_PASCAL_CASE:
  2760. return p_root_name.replace("-", "_").to_pascal_case();
  2761. case SCENE_NAME_CASING_SNAKE_CASE:
  2762. return p_root_name.replace("-", "_").to_snake_case();
  2763. case SCENE_NAME_CASING_KEBAB_CASE:
  2764. return p_root_name.to_snake_case().replace("_", "-");
  2765. }
  2766. return p_root_name;
  2767. }
  2768. String EditorNode::adjust_script_name_casing(const String &p_file_name, ScriptLanguage::ScriptNameCasing p_auto_casing) {
  2769. int editor_casing = GLOBAL_GET("editor/naming/script_name_casing");
  2770. if (editor_casing == ScriptLanguage::SCRIPT_NAME_CASING_AUTO) {
  2771. // Use the script language's preferred casing.
  2772. editor_casing = p_auto_casing;
  2773. }
  2774. switch (editor_casing) {
  2775. case ScriptLanguage::SCRIPT_NAME_CASING_AUTO:
  2776. // Script language has no preference, so do not adjust.
  2777. break;
  2778. case ScriptLanguage::SCRIPT_NAME_CASING_PASCAL_CASE:
  2779. return p_file_name.replace("-", "_").to_pascal_case();
  2780. case ScriptLanguage::SCRIPT_NAME_CASING_SNAKE_CASE:
  2781. return p_file_name.replace("-", "_").to_snake_case();
  2782. case ScriptLanguage::SCRIPT_NAME_CASING_KEBAB_CASE:
  2783. return p_file_name.to_snake_case().replace("_", "-");
  2784. }
  2785. return p_file_name;
  2786. }
  2787. void EditorNode::_request_screenshot() {
  2788. _screenshot();
  2789. }
  2790. void EditorNode::_screenshot(bool p_use_utc) {
  2791. String name = "editor_screenshot_" + Time::get_singleton()->get_datetime_string_from_system(p_use_utc).replace(":", "") + ".png";
  2792. NodePath path = String("user://") + name;
  2793. _save_screenshot(path);
  2794. if (EDITOR_GET("interface/editor/automatically_open_screenshots")) {
  2795. OS::get_singleton()->shell_show_in_file_manager(ProjectSettings::get_singleton()->globalize_path(path), true);
  2796. }
  2797. }
  2798. void EditorNode::_save_screenshot(NodePath p_path) {
  2799. Control *main_screen_control = editor_main_screen->get_control();
  2800. ERR_FAIL_NULL_MSG(main_screen_control, "Cannot get the editor main screen control.");
  2801. Viewport *viewport = main_screen_control->get_viewport();
  2802. ERR_FAIL_NULL_MSG(viewport, "Cannot get a viewport from the editor main screen.");
  2803. Ref<ViewportTexture> texture = viewport->get_texture();
  2804. ERR_FAIL_COND_MSG(texture.is_null(), "Cannot get a viewport texture from the editor main screen.");
  2805. Ref<Image> img = texture->get_image();
  2806. ERR_FAIL_COND_MSG(img.is_null(), "Cannot get an image from a viewport texture of the editor main screen.");
  2807. Error error = img->save_png(p_path);
  2808. ERR_FAIL_COND_MSG(error != OK, "Cannot save screenshot to file '" + p_path + "'.");
  2809. }
  2810. void EditorNode::_check_system_theme_changed() {
  2811. DisplayServer *display_server = DisplayServer::get_singleton();
  2812. bool system_theme_changed = false;
  2813. if (follow_system_theme) {
  2814. if (display_server->get_base_color() != last_system_base_color) {
  2815. system_theme_changed = true;
  2816. last_system_base_color = display_server->get_base_color();
  2817. }
  2818. if (display_server->is_dark_mode_supported() && display_server->is_dark_mode() != last_dark_mode_state) {
  2819. system_theme_changed = true;
  2820. last_dark_mode_state = display_server->is_dark_mode();
  2821. }
  2822. }
  2823. if (use_system_accent_color) {
  2824. if (display_server->get_accent_color() != last_system_accent_color) {
  2825. system_theme_changed = true;
  2826. last_system_accent_color = display_server->get_accent_color();
  2827. }
  2828. }
  2829. if (system_theme_changed) {
  2830. _update_theme();
  2831. }
  2832. }
  2833. void EditorNode::_tool_menu_option(int p_idx) {
  2834. switch (tool_menu->get_item_id(p_idx)) {
  2835. case TOOLS_ORPHAN_RESOURCES: {
  2836. orphan_resources->show();
  2837. } break;
  2838. case TOOLS_BUILD_PROFILE_MANAGER: {
  2839. build_profile_manager->popup_centered_clamped(Size2(700, 800) * EDSCALE, 0.8);
  2840. } break;
  2841. case TOOLS_SURFACE_UPGRADE: {
  2842. surface_upgrade_dialog->popup_on_demand();
  2843. } break;
  2844. case TOOLS_CUSTOM: {
  2845. if (tool_menu->get_item_submenu(p_idx) == "") {
  2846. Callable callback = tool_menu->get_item_metadata(p_idx);
  2847. Callable::CallError ce;
  2848. Variant result;
  2849. callback.callp(nullptr, 0, result, ce);
  2850. if (ce.error != Callable::CallError::CALL_OK) {
  2851. String err = Variant::get_callable_error_text(callback, nullptr, 0, ce);
  2852. ERR_PRINT("Error calling function from tool menu: " + err);
  2853. }
  2854. } // Else it's a submenu so don't do anything.
  2855. } break;
  2856. }
  2857. }
  2858. void EditorNode::_export_as_menu_option(int p_idx) {
  2859. if (p_idx == 0) { // MeshLibrary
  2860. current_menu_option = FILE_EXPORT_MESH_LIBRARY;
  2861. if (!editor_data.get_edited_scene_root()) {
  2862. show_accept(TTR("This operation can't be done without a scene."), TTR("OK"));
  2863. return;
  2864. }
  2865. List<String> extensions;
  2866. Ref<MeshLibrary> ml(memnew(MeshLibrary));
  2867. ResourceSaver::get_recognized_extensions(ml, &extensions);
  2868. file_export_lib->clear_filters();
  2869. for (const String &E : extensions) {
  2870. file_export_lib->add_filter("*." + E);
  2871. }
  2872. file_export_lib->set_title(TTR("Export Mesh Library"));
  2873. file_export_lib->popup_file_dialog();
  2874. } else { // Custom menu options added by plugins
  2875. if (export_as_menu->get_item_submenu(p_idx).is_empty()) { // If not a submenu
  2876. Callable callback = export_as_menu->get_item_metadata(p_idx);
  2877. Callable::CallError ce;
  2878. Variant result;
  2879. callback.callp(nullptr, 0, result, ce);
  2880. if (ce.error != Callable::CallError::CALL_OK) {
  2881. String err = Variant::get_callable_error_text(callback, nullptr, 0, ce);
  2882. ERR_PRINT("Error calling function from export_as menu: " + err);
  2883. }
  2884. }
  2885. }
  2886. }
  2887. int EditorNode::_next_unsaved_scene(bool p_valid_filename, int p_start) {
  2888. for (int i = p_start; i < editor_data.get_edited_scene_count(); i++) {
  2889. if (!editor_data.get_edited_scene_root(i)) {
  2890. continue;
  2891. }
  2892. String scene_filename = editor_data.get_edited_scene_root(i)->get_scene_file_path();
  2893. if (p_valid_filename && scene_filename.is_empty()) {
  2894. continue;
  2895. }
  2896. bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(i));
  2897. if (unsaved) {
  2898. return i;
  2899. } else {
  2900. for (int j = 0; j < editor_data.get_editor_plugin_count(); j++) {
  2901. if (!editor_data.get_editor_plugin(j)->get_unsaved_status(scene_filename).is_empty()) {
  2902. return i;
  2903. }
  2904. }
  2905. }
  2906. }
  2907. return -1;
  2908. }
  2909. void EditorNode::_exit_editor(int p_exit_code) {
  2910. exiting = true;
  2911. resource_preview->stop(); // Stop early to avoid crashes.
  2912. _save_editor_layout();
  2913. // Dim the editor window while it's quitting to make it clearer that it's busy.
  2914. dim_editor(true);
  2915. // Unload addons before quitting to allow cleanup.
  2916. unload_editor_addons();
  2917. get_tree()->quit(p_exit_code);
  2918. }
  2919. void EditorNode::unload_editor_addons() {
  2920. for (const KeyValue<String, EditorPlugin *> &E : addon_name_to_plugin) {
  2921. print_verbose(vformat("Unloading addon: %s", E.key));
  2922. remove_editor_plugin(E.value, false);
  2923. memdelete(E.value);
  2924. }
  2925. addon_name_to_plugin.clear();
  2926. }
  2927. void EditorNode::_discard_changes(const String &p_str) {
  2928. switch (current_menu_option) {
  2929. case FILE_CLOSE:
  2930. case SCENE_TAB_CLOSE: {
  2931. Node *scene = editor_data.get_edited_scene_root(tab_closing_idx);
  2932. if (scene != nullptr) {
  2933. String scene_filename = scene->get_scene_file_path();
  2934. if (!scene_filename.is_empty()) {
  2935. previous_scenes.push_back(scene_filename);
  2936. }
  2937. }
  2938. // Don't close tabs when exiting the editor (required for "restore_scenes_on_load" setting).
  2939. if (!_is_closing_editor()) {
  2940. _remove_scene(tab_closing_idx);
  2941. scene_tabs->update_scene_tabs();
  2942. }
  2943. _proceed_closing_scene_tabs();
  2944. } break;
  2945. case FILE_QUIT: {
  2946. project_run_bar->stop_playing();
  2947. _exit_editor(EXIT_SUCCESS);
  2948. } break;
  2949. case RUN_PROJECT_MANAGER: {
  2950. restart_editor(true);
  2951. } break;
  2952. case RELOAD_CURRENT_PROJECT: {
  2953. restart_editor();
  2954. } break;
  2955. }
  2956. }
  2957. void EditorNode::_update_file_menu_opened() {
  2958. file_menu->set_item_disabled(file_menu->get_item_index(FILE_OPEN_PREV), previous_scenes.is_empty());
  2959. _update_undo_redo_allowed();
  2960. }
  2961. void EditorNode::_update_file_menu_closed() {
  2962. file_menu->set_item_disabled(file_menu->get_item_index(FILE_OPEN_PREV), false);
  2963. }
  2964. void EditorNode::_palette_quick_open_dialog() {
  2965. quick_open_color_palette->popup_dialog({ "ColorPalette" }, palette_file_selected_callback);
  2966. quick_open_color_palette->set_title(TTR("Quick Open Color Palette..."));
  2967. }
  2968. void EditorNode::replace_resources_in_object(Object *p_object, const Vector<Ref<Resource>> &p_source_resources, const Vector<Ref<Resource>> &p_target_resource) {
  2969. List<PropertyInfo> pi;
  2970. p_object->get_property_list(&pi);
  2971. for (const PropertyInfo &E : pi) {
  2972. if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
  2973. continue;
  2974. }
  2975. switch (E.type) {
  2976. case Variant::OBJECT: {
  2977. if (E.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  2978. const Variant &v = p_object->get(E.name);
  2979. Ref<Resource> res = v;
  2980. if (res.is_valid()) {
  2981. int res_idx = p_source_resources.find(res);
  2982. if (res_idx != -1) {
  2983. p_object->set(E.name, p_target_resource.get(res_idx));
  2984. } else {
  2985. replace_resources_in_object(v, p_source_resources, p_target_resource);
  2986. }
  2987. }
  2988. }
  2989. } break;
  2990. case Variant::ARRAY: {
  2991. Array varray = p_object->get(E.name);
  2992. int len = varray.size();
  2993. bool array_requires_updating = false;
  2994. for (int i = 0; i < len; i++) {
  2995. const Variant &v = varray.get(i);
  2996. Ref<Resource> res = v;
  2997. if (res.is_valid()) {
  2998. int res_idx = p_source_resources.find(res);
  2999. if (res_idx != -1) {
  3000. varray.set(i, p_target_resource.get(res_idx));
  3001. array_requires_updating = true;
  3002. } else {
  3003. replace_resources_in_object(v, p_source_resources, p_target_resource);
  3004. }
  3005. }
  3006. }
  3007. if (array_requires_updating) {
  3008. p_object->set(E.name, varray);
  3009. }
  3010. } break;
  3011. case Variant::DICTIONARY: {
  3012. Dictionary d = p_object->get(E.name);
  3013. List<Variant> keys;
  3014. bool dictionary_requires_updating = false;
  3015. d.get_key_list(&keys);
  3016. for (const Variant &F : keys) {
  3017. Variant v = d[F];
  3018. Ref<Resource> res = v;
  3019. if (res.is_valid()) {
  3020. int res_idx = p_source_resources.find(res);
  3021. if (res_idx != -1) {
  3022. d[F] = p_target_resource.get(res_idx);
  3023. dictionary_requires_updating = true;
  3024. } else {
  3025. replace_resources_in_object(v, p_source_resources, p_target_resource);
  3026. }
  3027. }
  3028. }
  3029. if (dictionary_requires_updating) {
  3030. p_object->set(E.name, d);
  3031. }
  3032. } break;
  3033. default: {
  3034. }
  3035. }
  3036. }
  3037. Node *n = Object::cast_to<Node>(p_object);
  3038. if (n) {
  3039. for (int i = 0; i < n->get_child_count(); i++) {
  3040. replace_resources_in_object(n->get_child(i), p_source_resources, p_target_resource);
  3041. }
  3042. }
  3043. }
  3044. void EditorNode::replace_resources_in_scenes(const Vector<Ref<Resource>> &p_source_resources, const Vector<Ref<Resource>> &p_target_resource) {
  3045. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  3046. Node *edited_scene_root = editor_data.get_edited_scene_root(i);
  3047. if (edited_scene_root) {
  3048. replace_resources_in_object(edited_scene_root, p_source_resources, p_target_resource);
  3049. }
  3050. }
  3051. }
  3052. void EditorNode::add_editor_plugin(EditorPlugin *p_editor, bool p_config_changed) {
  3053. if (p_editor->has_main_screen()) {
  3054. singleton->editor_main_screen->add_main_plugin(p_editor);
  3055. }
  3056. singleton->editor_data.add_editor_plugin(p_editor);
  3057. singleton->add_child(p_editor);
  3058. if (p_config_changed) {
  3059. p_editor->enable_plugin();
  3060. }
  3061. }
  3062. void EditorNode::remove_editor_plugin(EditorPlugin *p_editor, bool p_config_changed) {
  3063. if (p_editor->has_main_screen()) {
  3064. singleton->editor_main_screen->remove_main_plugin(p_editor);
  3065. }
  3066. p_editor->make_visible(false);
  3067. p_editor->clear();
  3068. if (p_config_changed) {
  3069. p_editor->disable_plugin();
  3070. }
  3071. singleton->editor_plugins_over->remove_plugin(p_editor);
  3072. singleton->editor_plugins_force_over->remove_plugin(p_editor);
  3073. singleton->editor_plugins_force_input_forwarding->remove_plugin(p_editor);
  3074. singleton->remove_child(p_editor);
  3075. singleton->editor_data.remove_editor_plugin(p_editor);
  3076. for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : singleton->active_plugins) {
  3077. kv.value.erase(p_editor);
  3078. }
  3079. }
  3080. void EditorNode::add_extension_editor_plugin(const StringName &p_class_name) {
  3081. ERR_FAIL_COND_MSG(!ClassDB::class_exists(p_class_name), vformat("No such editor plugin registered: %s", p_class_name));
  3082. ERR_FAIL_COND_MSG(!ClassDB::is_parent_class(p_class_name, SNAME("EditorPlugin")), vformat("Class is not an editor plugin: %s", p_class_name));
  3083. ERR_FAIL_COND_MSG(singleton->editor_data.has_extension_editor_plugin(p_class_name), vformat("Editor plugin already added for class: %s", p_class_name));
  3084. EditorPlugin *plugin = Object::cast_to<EditorPlugin>(ClassDB::instantiate(p_class_name));
  3085. singleton->editor_data.add_extension_editor_plugin(p_class_name, plugin);
  3086. add_editor_plugin(plugin);
  3087. }
  3088. void EditorNode::remove_extension_editor_plugin(const StringName &p_class_name) {
  3089. // If we're exiting, the editor plugins will get cleaned up anyway, so don't do anything.
  3090. if (!singleton || singleton->exiting) {
  3091. return;
  3092. }
  3093. ERR_FAIL_COND_MSG(!singleton->editor_data.has_extension_editor_plugin(p_class_name), vformat("No editor plugin added for class: %s", p_class_name));
  3094. EditorPlugin *plugin = singleton->editor_data.get_extension_editor_plugin(p_class_name);
  3095. remove_editor_plugin(plugin);
  3096. memdelete(plugin);
  3097. singleton->editor_data.remove_extension_editor_plugin(p_class_name);
  3098. }
  3099. void EditorNode::_update_addon_config() {
  3100. if (_initializing_plugins) {
  3101. return;
  3102. }
  3103. Vector<String> enabled_addons;
  3104. for (const KeyValue<String, EditorPlugin *> &E : addon_name_to_plugin) {
  3105. enabled_addons.push_back(E.key);
  3106. }
  3107. if (enabled_addons.size() == 0) {
  3108. ProjectSettings::get_singleton()->set("editor_plugins/enabled", Variant());
  3109. } else {
  3110. enabled_addons.sort();
  3111. ProjectSettings::get_singleton()->set("editor_plugins/enabled", enabled_addons);
  3112. }
  3113. project_settings_editor->queue_save();
  3114. }
  3115. void EditorNode::set_addon_plugin_enabled(const String &p_addon, bool p_enabled, bool p_config_changed) {
  3116. String addon_path = p_addon;
  3117. if (!addon_path.begins_with("res://")) {
  3118. addon_path = "res://addons/" + addon_path + "/plugin.cfg";
  3119. }
  3120. ERR_FAIL_COND(p_enabled && addon_name_to_plugin.has(addon_path));
  3121. ERR_FAIL_COND(!p_enabled && !addon_name_to_plugin.has(addon_path));
  3122. if (!p_enabled) {
  3123. EditorPlugin *addon = addon_name_to_plugin[addon_path];
  3124. remove_editor_plugin(addon, p_config_changed);
  3125. memdelete(addon);
  3126. addon_name_to_plugin.erase(addon_path);
  3127. _update_addon_config();
  3128. return;
  3129. }
  3130. Ref<ConfigFile> cf;
  3131. cf.instantiate();
  3132. if (!DirAccess::exists(addon_path.get_base_dir())) {
  3133. _remove_plugin_from_enabled(addon_path);
  3134. WARN_PRINT("Addon '" + addon_path + "' failed to load. No directory found. Removing from enabled plugins.");
  3135. return;
  3136. }
  3137. Error err = cf->load(addon_path);
  3138. if (err != OK) {
  3139. show_warning(vformat(TTR("Unable to enable addon plugin at: '%s' parsing of config failed."), addon_path));
  3140. return;
  3141. }
  3142. String plugin_version;
  3143. if (cf->has_section_key("plugin", "version")) {
  3144. plugin_version = cf->get_value("plugin", "version");
  3145. }
  3146. if (!cf->has_section_key("plugin", "script")) {
  3147. show_warning(vformat(TTR("Unable to find script field for addon plugin at: '%s'."), addon_path));
  3148. return;
  3149. }
  3150. String script_path = cf->get_value("plugin", "script");
  3151. Ref<Script> scr; // We need to save it for creating "ep" below.
  3152. // Only try to load the script if it has a name. Else, the plugin has no init script.
  3153. if (script_path.length() > 0) {
  3154. script_path = addon_path.get_base_dir().path_join(script_path);
  3155. scr = ResourceLoader::load(script_path, "Script", ResourceFormatLoader::CACHE_MODE_IGNORE);
  3156. if (scr.is_null()) {
  3157. show_warning(vformat(TTR("Unable to load addon script from path: '%s'."), script_path));
  3158. return;
  3159. }
  3160. // Errors in the script cause the base_type to be an empty StringName.
  3161. if (scr->get_instance_base_type() == StringName()) {
  3162. if (_initializing_plugins) {
  3163. // However, if it happens during initialization, waiting for file scan might help.
  3164. pending_addons.push_back(p_addon);
  3165. return;
  3166. }
  3167. show_warning(vformat(TTR("Unable to load addon script from path: '%s'. This might be due to a code error in that script.\nDisabling the addon at '%s' to prevent further errors."), script_path, addon_path));
  3168. _remove_plugin_from_enabled(addon_path);
  3169. return;
  3170. }
  3171. // Plugin init scripts must inherit from EditorPlugin and be tools.
  3172. if (!ClassDB::is_parent_class(scr->get_instance_base_type(), "EditorPlugin")) {
  3173. show_warning(vformat(TTR("Unable to load addon script from path: '%s'. Base type is not 'EditorPlugin'."), script_path));
  3174. return;
  3175. }
  3176. if (!scr->is_tool()) {
  3177. show_warning(vformat(TTR("Unable to load addon script from path: '%s'. Script is not in tool mode."), script_path));
  3178. return;
  3179. }
  3180. }
  3181. EditorPlugin *ep = memnew(EditorPlugin);
  3182. ep->set_script(scr);
  3183. ep->set_plugin_version(plugin_version);
  3184. addon_name_to_plugin[addon_path] = ep;
  3185. add_editor_plugin(ep, p_config_changed);
  3186. _update_addon_config();
  3187. }
  3188. bool EditorNode::is_addon_plugin_enabled(const String &p_addon) const {
  3189. if (p_addon.begins_with("res://")) {
  3190. return addon_name_to_plugin.has(p_addon);
  3191. }
  3192. return addon_name_to_plugin.has("res://addons/" + p_addon + "/plugin.cfg");
  3193. }
  3194. void EditorNode::_remove_edited_scene(bool p_change_tab) {
  3195. // When scene gets closed no node is edited anymore, so make sure the editors are notified before nodes are freed.
  3196. hide_unused_editors(SceneTreeDock::get_singleton());
  3197. int new_index = editor_data.get_edited_scene();
  3198. int old_index = new_index;
  3199. if (new_index > 0) {
  3200. new_index = new_index - 1;
  3201. } else if (editor_data.get_edited_scene_count() > 1) {
  3202. new_index = 1;
  3203. } else {
  3204. editor_data.add_edited_scene(-1);
  3205. new_index = 1;
  3206. }
  3207. if (p_change_tab) {
  3208. _set_current_scene(new_index);
  3209. }
  3210. editor_data.remove_scene(old_index);
  3211. _update_title();
  3212. scene_tabs->update_scene_tabs();
  3213. }
  3214. void EditorNode::_remove_scene(int index, bool p_change_tab) {
  3215. // Clear icon cache in case some scripts are no longer needed.
  3216. // FIXME: Ideally the cache should never be cleared and only updated on per-script basis, when an icon changes.
  3217. editor_data.clear_script_icon_cache();
  3218. if (editor_data.get_edited_scene() == index) {
  3219. // Scene to remove is current scene.
  3220. _remove_edited_scene(p_change_tab);
  3221. } else {
  3222. // Scene to remove is not active scene.
  3223. editor_data.remove_scene(index);
  3224. }
  3225. }
  3226. void EditorNode::set_edited_scene(Node *p_scene) {
  3227. set_edited_scene_root(p_scene, true);
  3228. }
  3229. void EditorNode::set_edited_scene_root(Node *p_scene, bool p_auto_add) {
  3230. Node *old_edited_scene_root = get_editor_data().get_edited_scene_root();
  3231. ERR_FAIL_COND_MSG(p_scene && p_scene != old_edited_scene_root && p_scene->get_parent(), "Non-null nodes that are set as edited scene should not have a parent node.");
  3232. if (p_auto_add && old_edited_scene_root && old_edited_scene_root->get_parent() == scene_root) {
  3233. scene_root->remove_child(old_edited_scene_root);
  3234. }
  3235. get_editor_data().set_edited_scene_root(p_scene);
  3236. if (Object::cast_to<Popup>(p_scene)) {
  3237. Object::cast_to<Popup>(p_scene)->show();
  3238. }
  3239. SceneTreeDock::get_singleton()->set_edited_scene(p_scene);
  3240. if (get_tree()) {
  3241. get_tree()->set_edited_scene_root(p_scene);
  3242. }
  3243. if (p_auto_add && p_scene) {
  3244. scene_root->add_child(p_scene, true);
  3245. }
  3246. }
  3247. Dictionary EditorNode::_get_main_scene_state() {
  3248. Dictionary state;
  3249. state["scene_tree_offset"] = SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->get_value();
  3250. state["property_edit_offset"] = InspectorDock::get_inspector_singleton()->get_scroll_offset();
  3251. state["node_filter"] = SceneTreeDock::get_singleton()->get_filter();
  3252. return state;
  3253. }
  3254. void EditorNode::_set_main_scene_state(Dictionary p_state, Node *p_for_scene) {
  3255. if (get_edited_scene() != p_for_scene && p_for_scene != nullptr) {
  3256. return; // Not for this scene.
  3257. }
  3258. changing_scene = false;
  3259. if (get_edited_scene()) {
  3260. int current_tab = editor_main_screen->get_selected_index();
  3261. if (current_tab < 2) {
  3262. // Switch between 2D and 3D if currently in 2D or 3D.
  3263. Node *selected_node = SceneTreeDock::get_singleton()->get_tree_editor()->get_selected();
  3264. if (!selected_node) {
  3265. selected_node = get_edited_scene();
  3266. }
  3267. if (Object::cast_to<CanvasItem>(selected_node)) {
  3268. editor_main_screen->select(EditorMainScreen::EDITOR_2D);
  3269. } else if (Object::cast_to<Node3D>(selected_node)) {
  3270. editor_main_screen->select(EditorMainScreen::EDITOR_3D);
  3271. }
  3272. }
  3273. }
  3274. if (p_state.has("scene_tree_offset")) {
  3275. SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->set_value(p_state["scene_tree_offset"]);
  3276. }
  3277. if (p_state.has("property_edit_offset")) {
  3278. InspectorDock::get_inspector_singleton()->set_scroll_offset(p_state["property_edit_offset"]);
  3279. }
  3280. if (p_state.has("node_filter")) {
  3281. SceneTreeDock::get_singleton()->set_filter(p_state["node_filter"]);
  3282. }
  3283. // This should only happen at the very end.
  3284. EditorDebuggerNode::get_singleton()->update_live_edit_root();
  3285. ScriptEditor::get_singleton()->set_scene_root_script(editor_data.get_scene_root_script(editor_data.get_edited_scene()));
  3286. editor_data.notify_edited_scene_changed();
  3287. emit_signal(SNAME("scene_changed"));
  3288. // Reset SDFGI after everything else so that any last-second scene modifications will be processed.
  3289. RenderingServer::get_singleton()->sdfgi_reset();
  3290. }
  3291. bool EditorNode::is_changing_scene() const {
  3292. return changing_scene;
  3293. }
  3294. void EditorNode::_set_current_scene(int p_idx) {
  3295. if (p_idx == editor_data.get_edited_scene()) {
  3296. return; // Pointless.
  3297. }
  3298. _set_current_scene_nocheck(p_idx);
  3299. }
  3300. void EditorNode::_set_current_scene_nocheck(int p_idx) {
  3301. // Save the folding in case the scene gets reloaded.
  3302. if (editor_data.get_scene_path(p_idx) != "" && editor_data.get_edited_scene_root(p_idx)) {
  3303. editor_folding.save_scene_folding(editor_data.get_edited_scene_root(p_idx), editor_data.get_scene_path(p_idx));
  3304. }
  3305. changing_scene = true;
  3306. editor_data.save_edited_scene_state(editor_selection, &editor_history, _get_main_scene_state());
  3307. Node *old_scene = get_editor_data().get_edited_scene_root();
  3308. editor_selection->clear();
  3309. editor_data.set_edited_scene(p_idx);
  3310. Node *new_scene = editor_data.get_edited_scene_root();
  3311. // Remove the scene only if it's a new scene, preventing performance issues when adding and removing scenes.
  3312. if (old_scene && new_scene != old_scene && old_scene->get_parent() == scene_root) {
  3313. scene_root->remove_child(old_scene);
  3314. }
  3315. if (Popup *p = Object::cast_to<Popup>(new_scene)) {
  3316. p->show();
  3317. }
  3318. SceneTreeDock::get_singleton()->set_edited_scene(new_scene);
  3319. if (get_tree()) {
  3320. get_tree()->set_edited_scene_root(new_scene);
  3321. }
  3322. if (new_scene) {
  3323. if (new_scene->get_parent() != scene_root) {
  3324. scene_root->add_child(new_scene, true);
  3325. }
  3326. }
  3327. if (editor_data.check_and_update_scene(p_idx)) {
  3328. if (!editor_data.get_scene_path(p_idx).is_empty()) {
  3329. editor_folding.load_scene_folding(editor_data.get_edited_scene_root(p_idx), editor_data.get_scene_path(p_idx));
  3330. }
  3331. EditorUndoRedoManager::get_singleton()->clear_history(editor_data.get_scene_history_id(p_idx), false);
  3332. }
  3333. Dictionary state = editor_data.restore_edited_scene_state(editor_selection, &editor_history);
  3334. _edit_current(true);
  3335. _update_title();
  3336. callable_mp(scene_tabs, &EditorSceneTabs::update_scene_tabs).call_deferred();
  3337. if (tabs_to_close.is_empty()) {
  3338. callable_mp(this, &EditorNode::_set_main_scene_state).call_deferred(state, get_edited_scene()); // Do after everything else is done setting up.
  3339. }
  3340. _update_undo_redo_allowed();
  3341. }
  3342. void EditorNode::setup_color_picker(ColorPicker *p_picker) {
  3343. p_picker->set_editor_settings(EditorSettings::get_singleton());
  3344. int default_color_mode = EditorSettings::get_singleton()->get_project_metadata("color_picker", "color_mode", EDITOR_GET("interface/inspector/default_color_picker_mode"));
  3345. int picker_shape = EditorSettings::get_singleton()->get_project_metadata("color_picker", "picker_shape", EDITOR_GET("interface/inspector/default_color_picker_shape"));
  3346. p_picker->set_color_mode((ColorPicker::ColorModeType)default_color_mode);
  3347. p_picker->set_picker_shape((ColorPicker::PickerShapeType)picker_shape);
  3348. p_picker->set_quick_open_callback(callable_mp(this, &EditorNode::_palette_quick_open_dialog));
  3349. p_picker->set_palette_saved_callback(callable_mp(EditorFileSystem::get_singleton(), &EditorFileSystem::update_file));
  3350. palette_file_selected_callback = callable_mp(p_picker, &ColorPicker::_quick_open_palette_file_selected);
  3351. }
  3352. bool EditorNode::is_scene_open(const String &p_path) {
  3353. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  3354. if (editor_data.get_scene_path(i) == p_path) {
  3355. return true;
  3356. }
  3357. }
  3358. return false;
  3359. }
  3360. bool EditorNode::is_multi_window_enabled() const {
  3361. return !SceneTree::get_singleton()->get_root()->is_embedding_subwindows() && !EDITOR_GET("interface/editor/single_window_mode") && EDITOR_GET("interface/multi_window/enable");
  3362. }
  3363. void EditorNode::fix_dependencies(const String &p_for_file) {
  3364. dependency_fixer->edit(p_for_file);
  3365. }
  3366. int EditorNode::new_scene() {
  3367. int idx = editor_data.add_edited_scene(-1);
  3368. _set_current_scene(idx); // Before trying to remove an empty scene, set the current tab index to the newly added tab index.
  3369. // Remove placeholder empty scene.
  3370. if (editor_data.get_edited_scene_count() > 1) {
  3371. for (int i = 0; i < editor_data.get_edited_scene_count() - 1; i++) {
  3372. bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(i));
  3373. if (!unsaved && editor_data.get_scene_path(i).is_empty() && editor_data.get_edited_scene_root(i) == nullptr) {
  3374. editor_data.remove_scene(i);
  3375. idx--;
  3376. }
  3377. }
  3378. }
  3379. editor_data.clear_editor_states();
  3380. scene_tabs->update_scene_tabs();
  3381. return idx;
  3382. }
  3383. Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_force_open_imported, bool p_silent_change_tab) {
  3384. if (!is_inside_tree()) {
  3385. defer_load_scene = p_scene;
  3386. return OK;
  3387. }
  3388. String lpath = ResourceUID::ensure_path(p_scene);
  3389. if (!p_set_inherited) {
  3390. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  3391. if (editor_data.get_scene_path(i) == lpath) {
  3392. _set_current_scene(i);
  3393. return OK;
  3394. }
  3395. }
  3396. if (!p_force_open_imported && FileAccess::exists(lpath + ".import")) {
  3397. open_imported->set_text(vformat(TTR("Scene '%s' was automatically imported, so it can't be modified.\nTo make changes to it, a new inherited scene can be created."), lpath.get_file()));
  3398. open_imported->popup_centered();
  3399. new_inherited_button->grab_focus();
  3400. open_import_request = lpath;
  3401. return OK;
  3402. }
  3403. }
  3404. lpath = ProjectSettings::get_singleton()->localize_path(lpath);
  3405. if (!lpath.begins_with("res://")) {
  3406. show_accept(TTR("Error loading scene, it must be inside the project path. Use 'Import' to open the scene, then save it inside the project path."), TTR("OK"));
  3407. opening_prev = false;
  3408. return ERR_FILE_NOT_FOUND;
  3409. }
  3410. int prev = editor_data.get_edited_scene();
  3411. int idx = prev;
  3412. if (prev == -1 || editor_data.get_edited_scene_root() || !editor_data.get_scene_path(prev).is_empty()) {
  3413. idx = editor_data.add_edited_scene(-1);
  3414. if (p_silent_change_tab) {
  3415. _set_current_scene_nocheck(idx);
  3416. } else {
  3417. _set_current_scene(idx);
  3418. }
  3419. } else {
  3420. EditorUndoRedoManager::get_singleton()->clear_history(editor_data.get_current_edited_scene_history_id(), false);
  3421. }
  3422. dependency_errors.clear();
  3423. Error err;
  3424. Ref<PackedScene> sdata = ResourceLoader::load(lpath, "", ResourceFormatLoader::CACHE_MODE_REPLACE, &err);
  3425. if (!p_ignore_broken_deps && dependency_errors.has(lpath)) {
  3426. current_menu_option = -1;
  3427. Vector<String> errors;
  3428. for (const String &E : dependency_errors[lpath]) {
  3429. errors.push_back(E);
  3430. }
  3431. dependency_error->show(DependencyErrorDialog::MODE_SCENE, lpath, errors);
  3432. opening_prev = false;
  3433. if (prev != -1 && prev != idx) {
  3434. _set_current_scene(prev);
  3435. editor_data.remove_scene(idx);
  3436. }
  3437. return ERR_FILE_MISSING_DEPENDENCIES;
  3438. }
  3439. if (!sdata.is_valid()) {
  3440. _dialog_display_load_error(lpath, err);
  3441. opening_prev = false;
  3442. if (prev != -1 && prev != idx) {
  3443. _set_current_scene(prev);
  3444. editor_data.remove_scene(idx);
  3445. }
  3446. return ERR_FILE_NOT_FOUND;
  3447. }
  3448. dependency_errors.erase(lpath); // At least not self path.
  3449. for (KeyValue<String, HashSet<String>> &E : dependency_errors) {
  3450. String txt = vformat(TTR("Scene '%s' has broken dependencies:"), E.key) + "\n";
  3451. for (const String &F : E.value) {
  3452. txt += "\t" + F + "\n";
  3453. }
  3454. add_io_error(txt);
  3455. }
  3456. if (ResourceCache::has(lpath)) {
  3457. // Used from somewhere else? No problem! Update state and replace sdata.
  3458. Ref<PackedScene> ps = ResourceCache::get_ref(lpath);
  3459. if (ps.is_valid()) {
  3460. ps->replace_state(sdata->get_state());
  3461. ps->set_last_modified_time(sdata->get_last_modified_time());
  3462. sdata = ps;
  3463. }
  3464. } else {
  3465. sdata->set_path(lpath, true); // Take over path.
  3466. }
  3467. Node *new_scene = sdata->instantiate(p_set_inherited ? PackedScene::GEN_EDIT_STATE_MAIN_INHERITED : PackedScene::GEN_EDIT_STATE_MAIN);
  3468. if (!new_scene) {
  3469. sdata.unref();
  3470. _dialog_display_load_error(lpath, ERR_FILE_CORRUPT);
  3471. opening_prev = false;
  3472. if (prev != -1 && prev != idx) {
  3473. _set_current_scene(prev);
  3474. editor_data.remove_scene(idx);
  3475. }
  3476. return ERR_FILE_CORRUPT;
  3477. }
  3478. if (p_set_inherited) {
  3479. Ref<SceneState> state = sdata->get_state();
  3480. state->set_path(lpath);
  3481. new_scene->set_scene_inherited_state(state);
  3482. new_scene->set_scene_file_path(String());
  3483. }
  3484. new_scene->set_scene_instance_state(Ref<SceneState>());
  3485. set_edited_scene(new_scene);
  3486. String config_file_path = EditorPaths::get_singleton()->get_project_settings_dir().path_join(lpath.get_file() + "-editstate-" + lpath.md5_text() + ".cfg");
  3487. Ref<ConfigFile> editor_state_cf;
  3488. editor_state_cf.instantiate();
  3489. Error editor_state_cf_err = editor_state_cf->load(config_file_path);
  3490. if (editor_state_cf_err == OK || editor_state_cf->has_section("editor_states")) {
  3491. _load_editor_plugin_states_from_config(editor_state_cf);
  3492. }
  3493. if (editor_folding.has_folding_data(lpath)) {
  3494. editor_folding.load_scene_folding(new_scene, lpath);
  3495. } else if (EDITOR_GET("interface/inspector/auto_unfold_foreign_scenes")) {
  3496. editor_folding.unfold_scene(new_scene);
  3497. editor_folding.save_scene_folding(new_scene, lpath);
  3498. }
  3499. opening_prev = false;
  3500. EditorDebuggerNode::get_singleton()->update_live_edit_root();
  3501. if (restoring_scenes) {
  3502. // Initialize history for restored scenes.
  3503. ObjectID id = new_scene->get_instance_id();
  3504. if (id != editor_history.get_current()) {
  3505. editor_history.add_object(id);
  3506. }
  3507. }
  3508. // Load the selected nodes.
  3509. if (editor_state_cf->has_section_key("editor_states", "selected_nodes")) {
  3510. TypedArray<NodePath> selected_node_list = editor_state_cf->get_value("editor_states", "selected_nodes", TypedArray<String>());
  3511. for (int i = 0; i < selected_node_list.size(); i++) {
  3512. Node *selected_node = new_scene->get_node_or_null(selected_node_list[i]);
  3513. if (selected_node) {
  3514. editor_selection->add_node(selected_node);
  3515. }
  3516. }
  3517. }
  3518. if (!restoring_scenes) {
  3519. save_editor_layout_delayed();
  3520. }
  3521. if (p_set_inherited) {
  3522. EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(editor_data.get_current_edited_scene_history_id());
  3523. }
  3524. _update_title();
  3525. scene_tabs->update_scene_tabs();
  3526. if (!restoring_scenes) {
  3527. _add_to_recent_scenes(lpath);
  3528. }
  3529. return OK;
  3530. }
  3531. HashMap<StringName, Variant> EditorNode::get_modified_properties_for_node(Node *p_node, bool p_node_references_only) {
  3532. HashMap<StringName, Variant> modified_property_map;
  3533. List<PropertyInfo> pinfo;
  3534. p_node->get_property_list(&pinfo);
  3535. for (const PropertyInfo &E : pinfo) {
  3536. if (E.usage & PROPERTY_USAGE_STORAGE) {
  3537. bool node_reference = (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE);
  3538. if (p_node_references_only && !node_reference) {
  3539. continue;
  3540. }
  3541. bool is_valid_revert = false;
  3542. Variant revert_value = EditorPropertyRevert::get_property_revert_value(p_node, E.name, &is_valid_revert);
  3543. Variant current_value = p_node->get(E.name);
  3544. if (is_valid_revert) {
  3545. if (PropertyUtils::is_property_value_different(p_node, current_value, revert_value)) {
  3546. // If this property is a direct node reference, save a NodePath instead to prevent corrupted references.
  3547. if (node_reference) {
  3548. Node *target_node = Object::cast_to<Node>(current_value);
  3549. if (target_node) {
  3550. modified_property_map[E.name] = p_node->get_path_to(target_node);
  3551. }
  3552. } else {
  3553. modified_property_map[E.name] = current_value;
  3554. }
  3555. }
  3556. }
  3557. }
  3558. }
  3559. return modified_property_map;
  3560. }
  3561. HashMap<StringName, Variant> EditorNode::get_modified_properties_reference_to_nodes(Node *p_node, List<Node *> &p_nodes_referenced_by) {
  3562. HashMap<StringName, Variant> modified_property_map;
  3563. List<PropertyInfo> pinfo;
  3564. p_node->get_property_list(&pinfo);
  3565. for (const PropertyInfo &E : pinfo) {
  3566. if (E.usage & PROPERTY_USAGE_STORAGE) {
  3567. if (E.type != Variant::OBJECT || E.hint != PROPERTY_HINT_NODE_TYPE) {
  3568. continue;
  3569. }
  3570. Variant current_value = p_node->get(E.name);
  3571. Node *target_node = Object::cast_to<Node>(current_value);
  3572. if (target_node && p_nodes_referenced_by.find(target_node)) {
  3573. modified_property_map[E.name] = p_node->get_path_to(target_node);
  3574. }
  3575. }
  3576. }
  3577. return modified_property_map;
  3578. }
  3579. void EditorNode::update_node_from_node_modification_entry(Node *p_node, ModificationNodeEntry &p_node_modification) {
  3580. if (p_node) {
  3581. // First, attempt to restore the script property since it may affect the get_property_list method.
  3582. Variant *script_property_table_entry = p_node_modification.property_table.getptr(CoreStringName(script));
  3583. if (script_property_table_entry) {
  3584. p_node->set_script(*script_property_table_entry);
  3585. }
  3586. // Get properties for this node.
  3587. List<PropertyInfo> pinfo;
  3588. p_node->get_property_list(&pinfo);
  3589. // Get names of all valid property names.
  3590. HashMap<StringName, bool> property_node_reference_table;
  3591. for (const PropertyInfo &E : pinfo) {
  3592. if (E.usage & PROPERTY_USAGE_STORAGE) {
  3593. if (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE) {
  3594. property_node_reference_table[E.name] = true;
  3595. } else {
  3596. property_node_reference_table[E.name] = false;
  3597. }
  3598. }
  3599. }
  3600. // Restore the modified properties for this node.
  3601. for (const KeyValue<StringName, Variant> &E : p_node_modification.property_table) {
  3602. bool *property_node_reference_table_entry = property_node_reference_table.getptr(E.key);
  3603. if (property_node_reference_table_entry) {
  3604. // If the property is a node reference, attempt to restore from the node path instead.
  3605. bool is_node_reference = *property_node_reference_table_entry;
  3606. if (is_node_reference) {
  3607. if (E.value.get_type() == Variant::NODE_PATH) {
  3608. p_node->set(E.key, p_node->get_node_or_null(E.value));
  3609. }
  3610. } else {
  3611. p_node->set(E.key, E.value);
  3612. }
  3613. }
  3614. }
  3615. // Restore the connections to other nodes.
  3616. for (const ConnectionWithNodePath &E : p_node_modification.connections_to) {
  3617. Connection conn = E.connection;
  3618. // Get the node the callable is targeting.
  3619. Node *target_node = Object::cast_to<Node>(conn.callable.get_object());
  3620. // If the callable object no longer exists or is marked for deletion,
  3621. // attempt to reaccquire the closest match by using the node path
  3622. // we saved earlier.
  3623. if (!target_node || !target_node->is_queued_for_deletion()) {
  3624. target_node = p_node->get_node_or_null(E.node_path);
  3625. }
  3626. if (target_node) {
  3627. // Reconstruct the callable.
  3628. Callable new_callable = Callable(target_node, conn.callable.get_method());
  3629. if (!p_node->is_connected(conn.signal.get_name(), new_callable)) {
  3630. ERR_FAIL_COND(p_node->connect(conn.signal.get_name(), new_callable, conn.flags) != OK);
  3631. }
  3632. }
  3633. }
  3634. // Restore the connections from other nodes.
  3635. for (const Connection &E : p_node_modification.connections_from) {
  3636. Connection conn = E;
  3637. bool valid = p_node->has_method(conn.callable.get_method()) || Ref<Script>(p_node->get_script()).is_null() || Ref<Script>(p_node->get_script())->has_method(conn.callable.get_method());
  3638. ERR_CONTINUE_MSG(!valid, vformat("Attempt to connect signal '%s.%s' to nonexistent method '%s.%s'.", conn.signal.get_object()->get_class(), conn.signal.get_name(), conn.callable.get_object()->get_class(), conn.callable.get_method()));
  3639. // Get the object which the signal is connected from.
  3640. Object *source_object = conn.signal.get_object();
  3641. if (source_object) {
  3642. ERR_FAIL_COND(source_object->connect(conn.signal.get_name(), Callable(p_node, conn.callable.get_method()), conn.flags) != OK);
  3643. }
  3644. }
  3645. // Re-add the groups.
  3646. for (const Node::GroupInfo &E : p_node_modification.groups) {
  3647. p_node->add_to_group(E.name, E.persistent);
  3648. }
  3649. }
  3650. }
  3651. bool EditorNode::is_additional_node_in_scene(Node *p_edited_scene, Node *p_reimported_root, Node *p_node) {
  3652. if (p_node == p_reimported_root) {
  3653. return false;
  3654. }
  3655. bool node_part_of_subscene = p_node != p_edited_scene &&
  3656. p_edited_scene->get_scene_inherited_state().is_valid() &&
  3657. p_edited_scene->get_scene_inherited_state()->find_node_by_path(p_edited_scene->get_path_to(p_node)) >= 0 &&
  3658. // It's important to process added nodes from the base scene in the inherited scene as
  3659. // additional nodes to ensure they do not disappear on reload.
  3660. // When p_reimported_root == p_edited_scene that means the edited scene
  3661. // is the reimported scene, in that case the node is in the root base scene,
  3662. // so it's not an addition, otherwise, the node would be added twice on reload.
  3663. (p_node->get_owner() != p_edited_scene || p_reimported_root == p_edited_scene);
  3664. if (node_part_of_subscene) {
  3665. return false;
  3666. }
  3667. // Loop through the owners until either we reach the root node or nullptr
  3668. Node *valid_node_owner = p_node->get_owner();
  3669. while (valid_node_owner) {
  3670. if (valid_node_owner == p_reimported_root) {
  3671. break;
  3672. }
  3673. valid_node_owner = valid_node_owner->get_owner();
  3674. }
  3675. // When the owner is the imported scene and the owner is also the edited scene,
  3676. // that means the node was added in the current edited scene.
  3677. // We can be sure here because if the node that the node does not come from
  3678. // the base scene because we checked just over with 'get_scene_inherited_state()->find_node_by_path'.
  3679. if (valid_node_owner == p_reimported_root && p_reimported_root != p_edited_scene) {
  3680. return false;
  3681. }
  3682. return true;
  3683. }
  3684. void EditorNode::get_scene_editor_data_for_node(Node *p_root, Node *p_node, HashMap<NodePath, SceneEditorDataEntry> &p_table) {
  3685. SceneEditorDataEntry new_entry;
  3686. new_entry.is_display_folded = p_node->is_displayed_folded();
  3687. if (p_root != p_node) {
  3688. new_entry.is_editable = p_root->is_editable_instance(p_node);
  3689. }
  3690. p_table.insert(p_root->get_path_to(p_node), new_entry);
  3691. for (int i = 0; i < p_node->get_child_count(); i++) {
  3692. get_scene_editor_data_for_node(p_root, p_node->get_child(i), p_table);
  3693. }
  3694. }
  3695. void EditorNode::get_preload_scene_modification_table(
  3696. Node *p_edited_scene,
  3697. Node *p_reimported_root,
  3698. Node *p_node, InstanceModificationsEntry &p_instance_modifications) {
  3699. if (is_additional_node_in_scene(p_edited_scene, p_reimported_root, p_node)) {
  3700. // Only save additional nodes which have an owner since this was causing issues transient ownerless nodes
  3701. // which get recreated upon scene tree entry.
  3702. // For now instead, assume all ownerless nodes are transient and will have to be recreated.
  3703. if (p_node->get_owner()) {
  3704. HashMap<StringName, Variant> modified_properties = get_modified_properties_for_node(p_node, true);
  3705. if (p_node->get_owner() == p_edited_scene) {
  3706. AdditiveNodeEntry new_additive_node_entry;
  3707. new_additive_node_entry.node = p_node;
  3708. new_additive_node_entry.parent = p_reimported_root->get_path_to(p_node->get_parent());
  3709. new_additive_node_entry.owner = p_node->get_owner();
  3710. new_additive_node_entry.index = p_node->get_index();
  3711. Node2D *node_2d = Object::cast_to<Node2D>(p_node);
  3712. if (node_2d) {
  3713. new_additive_node_entry.transform_2d = node_2d->get_transform();
  3714. }
  3715. Node3D *node_3d = Object::cast_to<Node3D>(p_node);
  3716. if (node_3d) {
  3717. new_additive_node_entry.transform_3d = node_3d->get_transform();
  3718. }
  3719. p_instance_modifications.addition_list.push_back(new_additive_node_entry);
  3720. }
  3721. if (!modified_properties.is_empty()) {
  3722. ModificationNodeEntry modification_node_entry;
  3723. modification_node_entry.property_table = modified_properties;
  3724. p_instance_modifications.modifications[p_reimported_root->get_path_to(p_node)] = modification_node_entry;
  3725. }
  3726. }
  3727. } else {
  3728. HashMap<StringName, Variant> modified_properties = get_modified_properties_for_node(p_node, false);
  3729. // Find all valid connections to other nodes.
  3730. List<Connection> connections_to;
  3731. p_node->get_all_signal_connections(&connections_to);
  3732. List<ConnectionWithNodePath> valid_connections_to;
  3733. for (const Connection &c : connections_to) {
  3734. Node *connection_target_node = Object::cast_to<Node>(c.callable.get_object());
  3735. if (connection_target_node) {
  3736. // TODO: add support for reinstating custom callables
  3737. if (!c.callable.is_custom()) {
  3738. ConnectionWithNodePath connection_to;
  3739. connection_to.connection = c;
  3740. connection_to.node_path = p_node->get_path_to(connection_target_node);
  3741. valid_connections_to.push_back(connection_to);
  3742. }
  3743. }
  3744. }
  3745. // Find all valid connections from other nodes.
  3746. List<Connection> connections_from;
  3747. p_node->get_signals_connected_to_this(&connections_from);
  3748. List<Connection> valid_connections_from;
  3749. for (const Connection &c : connections_from) {
  3750. Node *source_node = Object::cast_to<Node>(c.signal.get_object());
  3751. Node *valid_source_owner = nullptr;
  3752. if (source_node) {
  3753. valid_source_owner = source_node->get_owner();
  3754. while (valid_source_owner) {
  3755. if (valid_source_owner == p_reimported_root) {
  3756. break;
  3757. }
  3758. valid_source_owner = valid_source_owner->get_owner();
  3759. }
  3760. }
  3761. if (!source_node || valid_source_owner == nullptr) {
  3762. // TODO: add support for reinstating custom callables
  3763. if (!c.callable.is_custom()) {
  3764. valid_connections_from.push_back(c);
  3765. }
  3766. }
  3767. }
  3768. // Find all node groups.
  3769. List<Node::GroupInfo> groups;
  3770. p_node->get_groups(&groups);
  3771. if (!modified_properties.is_empty() || !valid_connections_to.is_empty() || !valid_connections_from.is_empty() || !groups.is_empty()) {
  3772. ModificationNodeEntry modification_node_entry;
  3773. modification_node_entry.property_table = modified_properties;
  3774. modification_node_entry.connections_to = valid_connections_to;
  3775. modification_node_entry.connections_from = valid_connections_from;
  3776. modification_node_entry.groups = groups;
  3777. p_instance_modifications.modifications[p_reimported_root->get_path_to(p_node)] = modification_node_entry;
  3778. }
  3779. }
  3780. for (int i = 0; i < p_node->get_child_count(); i++) {
  3781. get_preload_scene_modification_table(p_edited_scene, p_reimported_root, p_node->get_child(i), p_instance_modifications);
  3782. }
  3783. }
  3784. void EditorNode::get_preload_modifications_reference_to_nodes(
  3785. Node *p_root,
  3786. Node *p_node,
  3787. HashSet<Node *> &p_excluded_nodes,
  3788. List<Node *> &p_instance_list_with_children,
  3789. HashMap<NodePath, ModificationNodeEntry> &p_modification_table) {
  3790. if (!p_excluded_nodes.find(p_node)) {
  3791. HashMap<StringName, Variant> modified_properties = get_modified_properties_reference_to_nodes(p_node, p_instance_list_with_children);
  3792. if (!modified_properties.is_empty()) {
  3793. ModificationNodeEntry modification_node_entry;
  3794. modification_node_entry.property_table = modified_properties;
  3795. p_modification_table[p_root->get_path_to(p_node)] = modification_node_entry;
  3796. }
  3797. for (int i = 0; i < p_node->get_child_count(); i++) {
  3798. get_preload_modifications_reference_to_nodes(p_root, p_node->get_child(i), p_excluded_nodes, p_instance_list_with_children, p_modification_table);
  3799. }
  3800. }
  3801. }
  3802. void EditorNode::get_children_nodes(Node *p_node, List<Node *> &p_nodes) {
  3803. for (int i = 0; i < p_node->get_child_count(); i++) {
  3804. Node *child = p_node->get_child(i);
  3805. p_nodes.push_back(child);
  3806. get_children_nodes(child, p_nodes);
  3807. }
  3808. }
  3809. void EditorNode::replace_history_reimported_nodes(Node *p_original_root_node, Node *p_new_root_node, Node *p_node) {
  3810. NodePath scene_path_to_node = p_original_root_node->get_path_to(p_node);
  3811. Node *new_node = p_new_root_node->get_node_or_null(scene_path_to_node);
  3812. if (new_node) {
  3813. editor_history.replace_object(p_node->get_instance_id(), new_node->get_instance_id());
  3814. } else {
  3815. editor_history.replace_object(p_node->get_instance_id(), ObjectID());
  3816. }
  3817. for (int i = 0; i < p_node->get_child_count(); i++) {
  3818. replace_history_reimported_nodes(p_original_root_node, p_new_root_node, p_node->get_child(i));
  3819. }
  3820. }
  3821. void EditorNode::open_request(const String &p_path, bool p_set_inherited) {
  3822. if (!opening_prev) {
  3823. List<String>::Element *prev_scene_item = previous_scenes.find(p_path);
  3824. if (prev_scene_item != nullptr) {
  3825. prev_scene_item->erase();
  3826. }
  3827. }
  3828. load_scene(p_path, false, p_set_inherited); // As it will be opened in separate tab.
  3829. }
  3830. bool EditorNode::has_previous_scenes() const {
  3831. return !previous_scenes.is_empty();
  3832. }
  3833. void EditorNode::edit_foreign_resource(Ref<Resource> p_resource) {
  3834. load_scene(p_resource->get_path().get_slice("::", 0));
  3835. callable_mp(InspectorDock::get_singleton(), &InspectorDock::edit_resource).call_deferred(p_resource);
  3836. }
  3837. bool EditorNode::is_resource_read_only(Ref<Resource> p_resource, bool p_foreign_resources_are_writable) {
  3838. ERR_FAIL_COND_V(p_resource.is_null(), false);
  3839. String path = p_resource->get_path();
  3840. if (!path.is_resource_file()) {
  3841. // If the resource name contains '::', that means it is a subresource embedded in another resource.
  3842. int srpos = path.find("::");
  3843. if (srpos != -1) {
  3844. String base = path.substr(0, srpos);
  3845. // If the base resource is a packed scene, we treat it as read-only if it is not the currently edited scene.
  3846. if (ResourceLoader::get_resource_type(base) == "PackedScene") {
  3847. if (!get_tree()->get_edited_scene_root() || get_tree()->get_edited_scene_root()->get_scene_file_path() != base) {
  3848. // If we have not flagged foreign resources as writable or the base scene the resource is
  3849. // part was imported, it can be considered read-only.
  3850. if (!p_foreign_resources_are_writable || FileAccess::exists(base + ".import")) {
  3851. return true;
  3852. }
  3853. }
  3854. } else {
  3855. // If a corresponding .import file exists for the base file, we assume it to be imported and should therefore treated as read-only.
  3856. if (FileAccess::exists(base + ".import")) {
  3857. return true;
  3858. }
  3859. }
  3860. }
  3861. } else if (FileAccess::exists(path + ".import")) {
  3862. // The resource is not a subresource, but if it has an .import file, it's imported so treat it as read only.
  3863. return true;
  3864. }
  3865. return false;
  3866. }
  3867. void EditorNode::request_instantiate_scene(const String &p_path) {
  3868. SceneTreeDock::get_singleton()->instantiate(p_path);
  3869. }
  3870. void EditorNode::request_instantiate_scenes(const Vector<String> &p_files) {
  3871. SceneTreeDock::get_singleton()->instantiate_scenes(p_files);
  3872. }
  3873. String EditorNode::get_multiwindow_support_tooltip_text() const {
  3874. if (SceneTree::get_singleton()->get_root()->is_embedding_subwindows()) {
  3875. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_SUBWINDOWS)) {
  3876. return TTR("Multi-window support is not available because the `--single-window` command line argument was used to start the editor.");
  3877. } else {
  3878. return TTR("Multi-window support is not available because the current platform doesn't support multiple windows.");
  3879. }
  3880. } else if (EDITOR_GET("interface/editor/single_window_mode")) {
  3881. return TTR("Multi-window support is not available because Interface > Editor > Single Window Mode is enabled in the editor settings.");
  3882. }
  3883. return TTR("Multi-window support is not available because Interface > Multi Window > Enable is disabled in the editor settings.");
  3884. }
  3885. void EditorNode::_inherit_request(String p_file) {
  3886. current_menu_option = FILE_NEW_INHERITED_SCENE;
  3887. _dialog_action(p_file);
  3888. }
  3889. void EditorNode::_instantiate_request(const Vector<String> &p_files) {
  3890. request_instantiate_scenes(p_files);
  3891. }
  3892. void EditorNode::_close_messages() {
  3893. old_split_ofs = center_split->get_split_offset();
  3894. center_split->set_split_offset(0);
  3895. }
  3896. void EditorNode::_show_messages() {
  3897. center_split->set_split_offset(old_split_ofs);
  3898. }
  3899. void EditorNode::_add_to_recent_scenes(const String &p_scene) {
  3900. Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scenes", Array());
  3901. if (rc.has(p_scene)) {
  3902. rc.erase(p_scene);
  3903. }
  3904. rc.push_front(p_scene);
  3905. if (rc.size() > 10) {
  3906. rc.resize(10);
  3907. }
  3908. EditorSettings::get_singleton()->set_project_metadata("recent_files", "scenes", rc);
  3909. _update_recent_scenes();
  3910. }
  3911. void EditorNode::_open_recent_scene(int p_idx) {
  3912. if (p_idx == recent_scenes->get_item_count() - 1) {
  3913. EditorSettings::get_singleton()->set_project_metadata("recent_files", "scenes", Array());
  3914. callable_mp(this, &EditorNode::_update_recent_scenes).call_deferred();
  3915. } else {
  3916. Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scenes", Array());
  3917. ERR_FAIL_INDEX(p_idx, rc.size());
  3918. if (load_scene(rc[p_idx]) != OK) {
  3919. rc.remove_at(p_idx);
  3920. EditorSettings::get_singleton()->set_project_metadata("recent_files", "scenes", rc);
  3921. _update_recent_scenes();
  3922. }
  3923. }
  3924. }
  3925. void EditorNode::_update_recent_scenes() {
  3926. Array rc = EditorSettings::get_singleton()->get_project_metadata("recent_files", "scenes", Array());
  3927. recent_scenes->clear();
  3928. String path;
  3929. for (int i = 0; i < rc.size(); i++) {
  3930. path = rc[i];
  3931. recent_scenes->add_item(path.replace("res://", ""), i);
  3932. }
  3933. recent_scenes->add_separator();
  3934. recent_scenes->add_shortcut(ED_SHORTCUT("editor/clear_recent", TTRC("Clear Recent Scenes")));
  3935. recent_scenes->reset_size();
  3936. }
  3937. void EditorNode::_quick_opened(const String &p_file_path) {
  3938. if (ClassDB::is_parent_class(ResourceLoader::get_resource_type(p_file_path), "PackedScene")) {
  3939. open_request(p_file_path);
  3940. } else {
  3941. load_resource(p_file_path);
  3942. }
  3943. }
  3944. void EditorNode::_project_run_started() {
  3945. if (bool(EDITOR_GET("run/output/always_clear_output_on_play"))) {
  3946. log->clear();
  3947. }
  3948. int action_on_play = EDITOR_GET("run/bottom_panel/action_on_play");
  3949. if (action_on_play == ACTION_ON_PLAY_OPEN_OUTPUT) {
  3950. bottom_panel->make_item_visible(log);
  3951. } else if (action_on_play == ACTION_ON_PLAY_OPEN_DEBUGGER) {
  3952. bottom_panel->make_item_visible(EditorDebuggerNode::get_singleton());
  3953. }
  3954. }
  3955. void EditorNode::_project_run_stopped() {
  3956. int action_on_stop = EDITOR_GET("run/bottom_panel/action_on_stop");
  3957. if (action_on_stop == ACTION_ON_STOP_CLOSE_BUTTOM_PANEL) {
  3958. bottom_panel->hide_bottom_panel();
  3959. }
  3960. }
  3961. void EditorNode::notify_all_debug_sessions_exited() {
  3962. project_run_bar->stop_playing();
  3963. }
  3964. void EditorNode::add_io_error(const String &p_error) {
  3965. DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
  3966. singleton->load_errors->add_image(singleton->theme->get_icon(SNAME("Error"), EditorStringName(EditorIcons)));
  3967. singleton->load_errors->add_text(p_error + "\n");
  3968. // When a progress dialog is displayed, we will wait for it ot close before displaying
  3969. // the io errors to prevent the io popup to set it's parent to the progress dialog.
  3970. if (singleton->progress_dialog->is_visible()) {
  3971. singleton->load_errors_queued_to_display = true;
  3972. } else {
  3973. EditorInterface::get_singleton()->popup_dialog_centered_ratio(singleton->load_error_dialog, 0.5);
  3974. }
  3975. }
  3976. void EditorNode::add_io_warning(const String &p_warning) {
  3977. DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
  3978. singleton->load_errors->add_image(singleton->theme->get_icon(SNAME("Warning"), EditorStringName(EditorIcons)));
  3979. singleton->load_errors->add_text(p_warning + "\n");
  3980. // When a progress dialog is displayed, we will wait for it ot close before displaying
  3981. // the io errors to prevent the io popup to set it's parent to the progress dialog.
  3982. if (singleton->progress_dialog->is_visible()) {
  3983. singleton->load_errors_queued_to_display = true;
  3984. } else {
  3985. EditorInterface::get_singleton()->popup_dialog_centered_ratio(singleton->load_error_dialog, 0.5);
  3986. }
  3987. }
  3988. bool EditorNode::_find_scene_in_use(Node *p_node, const String &p_path) const {
  3989. if (p_node->get_scene_file_path() == p_path) {
  3990. return true;
  3991. }
  3992. for (int i = 0; i < p_node->get_child_count(); i++) {
  3993. if (_find_scene_in_use(p_node->get_child(i), p_path)) {
  3994. return true;
  3995. }
  3996. }
  3997. return false;
  3998. }
  3999. bool EditorNode::is_scene_in_use(const String &p_path) {
  4000. Node *es = get_edited_scene();
  4001. if (es) {
  4002. return _find_scene_in_use(es, p_path);
  4003. }
  4004. return false;
  4005. }
  4006. OS::ProcessID EditorNode::has_child_process(OS::ProcessID p_pid) const {
  4007. return project_run_bar->has_child_process(p_pid);
  4008. }
  4009. void EditorNode::stop_child_process(OS::ProcessID p_pid) {
  4010. project_run_bar->stop_child_process(p_pid);
  4011. }
  4012. Ref<Script> EditorNode::get_object_custom_type_base(const Object *p_object) const {
  4013. ERR_FAIL_NULL_V(p_object, nullptr);
  4014. const Node *node = Object::cast_to<const Node>(p_object);
  4015. if (node && node->has_meta(SceneStringName(_custom_type_script))) {
  4016. return node->get_meta(SceneStringName(_custom_type_script));
  4017. }
  4018. Ref<Script> scr = p_object->get_script();
  4019. if (scr.is_valid()) {
  4020. // Uncommenting would break things! Consider adding a parameter if you need it.
  4021. // StringName name = EditorNode::get_editor_data().script_class_get_name(base_script->get_path());
  4022. // if (name != StringName()) {
  4023. // return name;
  4024. // }
  4025. // TODO: Should probably be deprecated in 4.x
  4026. StringName base = scr->get_instance_base_type();
  4027. if (base != StringName() && EditorNode::get_editor_data().get_custom_types().has(base)) {
  4028. const Vector<EditorData::CustomType> &types = EditorNode::get_editor_data().get_custom_types()[base];
  4029. Ref<Script> base_scr = scr;
  4030. while (base_scr.is_valid()) {
  4031. for (int i = 0; i < types.size(); ++i) {
  4032. if (types[i].script == base_scr) {
  4033. return types[i].script;
  4034. }
  4035. }
  4036. base_scr = base_scr->get_base_script();
  4037. }
  4038. }
  4039. }
  4040. return nullptr;
  4041. }
  4042. StringName EditorNode::get_object_custom_type_name(const Object *p_object) const {
  4043. ERR_FAIL_NULL_V(p_object, StringName());
  4044. Ref<Script> scr = p_object->get_script();
  4045. if (scr.is_null() && Object::cast_to<Script>(p_object)) {
  4046. scr = p_object;
  4047. }
  4048. if (scr.is_valid()) {
  4049. Ref<Script> base_scr = scr;
  4050. while (base_scr.is_valid()) {
  4051. StringName name = EditorNode::get_editor_data().script_class_get_name(base_scr->get_path());
  4052. if (name != StringName()) {
  4053. return name;
  4054. }
  4055. // TODO: Should probably be deprecated in 4.x.
  4056. StringName base = base_scr->get_instance_base_type();
  4057. if (base != StringName() && EditorNode::get_editor_data().get_custom_types().has(base)) {
  4058. const Vector<EditorData::CustomType> &types = EditorNode::get_editor_data().get_custom_types()[base];
  4059. for (int i = 0; i < types.size(); ++i) {
  4060. if (types[i].script == base_scr) {
  4061. return types[i].name;
  4062. }
  4063. }
  4064. }
  4065. base_scr = base_scr->get_base_script();
  4066. }
  4067. }
  4068. return StringName();
  4069. }
  4070. void EditorNode::_pick_main_scene_custom_action(const String &p_custom_action_name) {
  4071. if (p_custom_action_name == "select_current") {
  4072. Node *scene = editor_data.get_edited_scene_root();
  4073. if (!scene) {
  4074. show_accept(TTR("There is no defined scene to run."), TTR("OK"));
  4075. return;
  4076. }
  4077. pick_main_scene->hide();
  4078. if (!FileAccess::exists(scene->get_scene_file_path())) {
  4079. current_menu_option = FILE_SAVE_AND_RUN_MAIN_SCENE;
  4080. _menu_option_confirm(FILE_SAVE_AS_SCENE, true);
  4081. file->set_title(TTR("Save scene before running..."));
  4082. } else {
  4083. current_menu_option = SETTINGS_PICK_MAIN_SCENE;
  4084. _dialog_action(scene->get_scene_file_path());
  4085. }
  4086. }
  4087. }
  4088. Ref<Texture2D> EditorNode::_get_class_or_script_icon(const String &p_class, const Ref<Script> &p_script, const String &p_fallback, bool p_fallback_script_to_theme) {
  4089. ERR_FAIL_COND_V_MSG(p_class.is_empty(), nullptr, "Class name cannot be empty.");
  4090. EditorData &ed = EditorNode::get_editor_data();
  4091. // Check for a script icon first.
  4092. if (p_script.is_valid()) {
  4093. Ref<Texture2D> script_icon = ed.get_script_icon(p_script);
  4094. if (script_icon.is_valid()) {
  4095. return script_icon;
  4096. }
  4097. if (p_fallback_script_to_theme) {
  4098. // Look for the native base type in the editor theme. This is relevant for
  4099. // scripts extending other scripts and for built-in classes.
  4100. String script_class_name = p_script->get_language()->get_global_class_name(p_script->get_path());
  4101. String base_type;
  4102. if (script_class_name.is_empty()) {
  4103. base_type = p_script->get_instance_base_type();
  4104. } else {
  4105. base_type = ScriptServer::get_global_class_native_base(script_class_name);
  4106. }
  4107. if (theme.is_valid() && theme->has_icon(base_type, EditorStringName(EditorIcons))) {
  4108. return theme->get_icon(base_type, EditorStringName(EditorIcons));
  4109. }
  4110. }
  4111. }
  4112. // Script was not valid or didn't yield any useful values, try the class name
  4113. // directly.
  4114. // Check if the class name is an extension-defined type.
  4115. Ref<Texture2D> ext_icon = ed.extension_class_get_icon(p_class);
  4116. if (ext_icon.is_valid()) {
  4117. return ext_icon;
  4118. }
  4119. // Check if the class name is a custom type.
  4120. // TODO: Should probably be deprecated in 4.x
  4121. const EditorData::CustomType *ctype = ed.get_custom_type_by_name(p_class);
  4122. if (ctype && ctype->icon.is_valid()) {
  4123. return ctype->icon;
  4124. }
  4125. // Look up the class name or the fallback name in the editor theme.
  4126. // This is only relevant for built-in classes.
  4127. if (theme.is_valid()) {
  4128. if (theme->has_icon(p_class, EditorStringName(EditorIcons))) {
  4129. return theme->get_icon(p_class, EditorStringName(EditorIcons));
  4130. }
  4131. if (!p_fallback.is_empty() && theme->has_icon(p_fallback, EditorStringName(EditorIcons))) {
  4132. return theme->get_icon(p_fallback, EditorStringName(EditorIcons));
  4133. }
  4134. // If the fallback is empty or wasn't found, use the default fallback.
  4135. if (ClassDB::class_exists(p_class)) {
  4136. bool instantiable = !ClassDB::is_virtual(p_class) && ClassDB::can_instantiate(p_class);
  4137. if (ClassDB::is_parent_class(p_class, SNAME("Node"))) {
  4138. return theme->get_icon(instantiable ? "Node" : "NodeDisabled", EditorStringName(EditorIcons));
  4139. } else {
  4140. return theme->get_icon(instantiable ? "Object" : "ObjectDisabled", EditorStringName(EditorIcons));
  4141. }
  4142. }
  4143. }
  4144. return nullptr;
  4145. }
  4146. Ref<Texture2D> EditorNode::get_object_icon(const Object *p_object, const String &p_fallback) {
  4147. ERR_FAIL_NULL_V_MSG(p_object, nullptr, "Object cannot be null.");
  4148. Ref<Script> scr = p_object->get_script();
  4149. if (scr.is_null() && p_object->is_class("Script")) {
  4150. scr = p_object;
  4151. }
  4152. return _get_class_or_script_icon(p_object->get_class(), scr, p_fallback);
  4153. }
  4154. Ref<Texture2D> EditorNode::get_class_icon(const String &p_class, const String &p_fallback) {
  4155. ERR_FAIL_COND_V_MSG(p_class.is_empty(), nullptr, "Class name cannot be empty.");
  4156. Ref<Script> scr;
  4157. if (ScriptServer::is_global_class(p_class)) {
  4158. scr = EditorNode::get_editor_data().script_class_load_script(p_class);
  4159. } else if (ResourceLoader::exists(p_class)) { // If the script is not a class_name we check if the script resource exists.
  4160. scr = ResourceLoader::load(p_class);
  4161. }
  4162. return _get_class_or_script_icon(p_class, scr, p_fallback, true);
  4163. }
  4164. bool EditorNode::is_object_of_custom_type(const Object *p_object, const StringName &p_class) {
  4165. ERR_FAIL_NULL_V(p_object, false);
  4166. Ref<Script> scr = p_object->get_script();
  4167. if (scr.is_null() && Object::cast_to<Script>(p_object)) {
  4168. scr = p_object;
  4169. }
  4170. if (scr.is_valid()) {
  4171. Ref<Script> base_script = scr;
  4172. while (base_script.is_valid()) {
  4173. StringName name = EditorNode::get_editor_data().script_class_get_name(base_script->get_path());
  4174. if (name == p_class) {
  4175. return true;
  4176. }
  4177. base_script = base_script->get_base_script();
  4178. }
  4179. }
  4180. return false;
  4181. }
  4182. void EditorNode::progress_add_task(const String &p_task, const String &p_label, int p_steps, bool p_can_cancel) {
  4183. if (!singleton) {
  4184. return;
  4185. } else if (singleton->cmdline_export_mode) {
  4186. print_line(p_task + ": begin: " + p_label + " steps: " + itos(p_steps));
  4187. } else if (singleton->progress_dialog) {
  4188. singleton->progress_dialog->add_task(p_task, p_label, p_steps, p_can_cancel);
  4189. }
  4190. }
  4191. bool EditorNode::progress_task_step(const String &p_task, const String &p_state, int p_step, bool p_force_refresh) {
  4192. if (!singleton) {
  4193. return false;
  4194. } else if (singleton->cmdline_export_mode) {
  4195. print_line("\t" + p_task + ": step " + itos(p_step) + ": " + p_state);
  4196. return false;
  4197. } else if (singleton->progress_dialog) {
  4198. return singleton->progress_dialog->task_step(p_task, p_state, p_step, p_force_refresh);
  4199. } else {
  4200. return false;
  4201. }
  4202. }
  4203. void EditorNode::progress_end_task(const String &p_task) {
  4204. if (!singleton) {
  4205. return;
  4206. } else if (singleton->cmdline_export_mode) {
  4207. print_line(p_task + ": end");
  4208. } else if (singleton->progress_dialog) {
  4209. singleton->progress_dialog->end_task(p_task);
  4210. }
  4211. }
  4212. void EditorNode::progress_add_task_bg(const String &p_task, const String &p_label, int p_steps) {
  4213. singleton->progress_hb->add_task(p_task, p_label, p_steps);
  4214. }
  4215. void EditorNode::progress_task_step_bg(const String &p_task, int p_step) {
  4216. singleton->progress_hb->task_step(p_task, p_step);
  4217. }
  4218. void EditorNode::progress_end_task_bg(const String &p_task) {
  4219. singleton->progress_hb->end_task(p_task);
  4220. }
  4221. void EditorNode::_progress_dialog_visibility_changed() {
  4222. // Open the io errors after the progress dialog is closed.
  4223. if (load_errors_queued_to_display && !progress_dialog->is_visible()) {
  4224. EditorInterface::get_singleton()->popup_dialog_centered_ratio(singleton->load_error_dialog, 0.5);
  4225. load_errors_queued_to_display = false;
  4226. }
  4227. }
  4228. void EditorNode::_load_error_dialog_visibility_changed() {
  4229. if (!load_error_dialog->is_visible()) {
  4230. load_errors->clear();
  4231. }
  4232. }
  4233. String EditorNode::_get_system_info() const {
  4234. String distribution_name = OS::get_singleton()->get_distribution_name();
  4235. if (distribution_name.is_empty()) {
  4236. distribution_name = OS::get_singleton()->get_name();
  4237. }
  4238. if (distribution_name.is_empty()) {
  4239. distribution_name = "Other";
  4240. }
  4241. const String distribution_version = OS::get_singleton()->get_version_alias();
  4242. String godot_version = "Godot v" + String(VERSION_FULL_CONFIG);
  4243. if (String(VERSION_BUILD) != "official") {
  4244. String hash = String(VERSION_HASH);
  4245. hash = hash.is_empty() ? String("unknown") : vformat("(%s)", hash.left(9));
  4246. godot_version += " " + hash;
  4247. }
  4248. String display_session_type;
  4249. #ifdef LINUXBSD_ENABLED
  4250. // `replace` is necessary, because `capitalize` introduces a whitespace between "x" and "11".
  4251. display_session_type = OS::get_singleton()->get_environment("XDG_SESSION_TYPE").capitalize().replace(" ", "");
  4252. #endif // LINUXBSD_ENABLED
  4253. String driver_name = OS::get_singleton()->get_current_rendering_driver_name().to_lower();
  4254. String rendering_method = OS::get_singleton()->get_current_rendering_method().to_lower();
  4255. const String rendering_device_name = RenderingServer::get_singleton()->get_video_adapter_name();
  4256. RenderingDevice::DeviceType device_type = RenderingServer::get_singleton()->get_video_adapter_type();
  4257. String device_type_string;
  4258. switch (device_type) {
  4259. case RenderingDevice::DeviceType::DEVICE_TYPE_INTEGRATED_GPU:
  4260. device_type_string = "integrated";
  4261. break;
  4262. case RenderingDevice::DeviceType::DEVICE_TYPE_DISCRETE_GPU:
  4263. device_type_string = "dedicated";
  4264. break;
  4265. case RenderingDevice::DeviceType::DEVICE_TYPE_VIRTUAL_GPU:
  4266. device_type_string = "virtual";
  4267. break;
  4268. case RenderingDevice::DeviceType::DEVICE_TYPE_CPU:
  4269. device_type_string = "(software emulation on CPU)";
  4270. break;
  4271. case RenderingDevice::DeviceType::DEVICE_TYPE_OTHER:
  4272. case RenderingDevice::DeviceType::DEVICE_TYPE_MAX:
  4273. break; // Can't happen, but silences warning for DEVICE_TYPE_MAX
  4274. }
  4275. const Vector<String> video_adapter_driver_info = OS::get_singleton()->get_video_adapter_driver_info();
  4276. const String processor_name = OS::get_singleton()->get_processor_name();
  4277. const int processor_count = OS::get_singleton()->get_processor_count();
  4278. // Prettify
  4279. if (rendering_method == "forward_plus") {
  4280. rendering_method = "Forward+";
  4281. } else if (rendering_method == "mobile") {
  4282. rendering_method = "Mobile";
  4283. } else if (rendering_method == "gl_compatibility") {
  4284. rendering_method = "Compatibility";
  4285. }
  4286. if (driver_name == "vulkan") {
  4287. driver_name = "Vulkan";
  4288. } else if (driver_name == "d3d12") {
  4289. driver_name = "Direct3D 12";
  4290. } else if (driver_name == "opengl3_angle") {
  4291. driver_name = "OpenGL ES 3/ANGLE";
  4292. } else if (driver_name == "opengl3_es") {
  4293. driver_name = "OpenGL ES 3";
  4294. } else if (driver_name == "opengl3") {
  4295. if (OS::get_singleton()->get_gles_over_gl()) {
  4296. driver_name = "OpenGL 3";
  4297. } else {
  4298. driver_name = "OpenGL ES 3";
  4299. }
  4300. } else if (driver_name == "metal") {
  4301. driver_name = "Metal";
  4302. }
  4303. // Join info.
  4304. Vector<String> info;
  4305. info.push_back(godot_version);
  4306. String distribution_display_session_type = distribution_name;
  4307. if (!distribution_version.is_empty()) {
  4308. distribution_display_session_type += " " + distribution_version;
  4309. }
  4310. if (!display_session_type.is_empty()) {
  4311. distribution_display_session_type += " on " + display_session_type;
  4312. }
  4313. info.push_back(distribution_display_session_type);
  4314. String display_driver_window_mode;
  4315. #ifdef LINUXBSD_ENABLED
  4316. // `replace` is necessary, because `capitalize` introduces a whitespace between "x" and "11".
  4317. display_driver_window_mode = DisplayServer::get_singleton()->get_name().capitalize().replace(" ", "") + " display driver";
  4318. #endif // LINUXBSD_ENABLED
  4319. if (!display_driver_window_mode.is_empty()) {
  4320. display_driver_window_mode += ", ";
  4321. }
  4322. display_driver_window_mode += get_viewport()->is_embedding_subwindows() ? "Single-window" : "Multi-window";
  4323. if (DisplayServer::get_singleton()->get_screen_count() == 1) {
  4324. display_driver_window_mode += ", " + itos(DisplayServer::get_singleton()->get_screen_count()) + " monitor";
  4325. } else {
  4326. display_driver_window_mode += ", " + itos(DisplayServer::get_singleton()->get_screen_count()) + " monitors";
  4327. }
  4328. info.push_back(display_driver_window_mode);
  4329. info.push_back(vformat("%s (%s)", driver_name, rendering_method));
  4330. String graphics;
  4331. if (!device_type_string.is_empty()) {
  4332. graphics = device_type_string + " ";
  4333. }
  4334. graphics += rendering_device_name;
  4335. if (video_adapter_driver_info.size() == 2) { // This vector is always either of length 0 or 2.
  4336. const String &vad_name = video_adapter_driver_info[0];
  4337. const String &vad_version = video_adapter_driver_info[1]; // Version could be potentially empty on Linux/BSD.
  4338. if (!vad_version.is_empty()) {
  4339. graphics += vformat(" (%s; %s)", vad_name, vad_version);
  4340. } else if (!vad_name.is_empty()) {
  4341. graphics += vformat(" (%s)", vad_name);
  4342. }
  4343. }
  4344. info.push_back(graphics);
  4345. info.push_back(vformat("%s (%d threads)", processor_name, processor_count));
  4346. return String(" - ").join(info);
  4347. }
  4348. bool EditorNode::_should_display_update_spinner() const {
  4349. #ifdef DEV_ENABLED
  4350. const bool in_dev = true;
  4351. #else
  4352. const bool in_dev = false;
  4353. #endif
  4354. const int show_update_spinner_setting = EDITOR_GET("interface/editor/show_update_spinner");
  4355. return (show_update_spinner_setting == 0 && in_dev) || show_update_spinner_setting == 1;
  4356. }
  4357. Ref<Texture2D> EditorNode::_file_dialog_get_icon(const String &p_path) {
  4358. EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem_path(p_path.get_base_dir());
  4359. if (efsd) {
  4360. String file = p_path.get_file();
  4361. for (int i = 0; i < efsd->get_file_count(); i++) {
  4362. if (efsd->get_file(i) == file) {
  4363. String type = efsd->get_file_type(i);
  4364. if (singleton->icon_type_cache.has(type)) {
  4365. return singleton->icon_type_cache[type];
  4366. } else {
  4367. return singleton->icon_type_cache["Object"];
  4368. }
  4369. }
  4370. }
  4371. }
  4372. return singleton->icon_type_cache["Object"];
  4373. }
  4374. void EditorNode::_build_icon_type_cache() {
  4375. List<StringName> tl;
  4376. theme->get_icon_list(EditorStringName(EditorIcons), &tl);
  4377. for (const StringName &E : tl) {
  4378. if (!ClassDB::class_exists(E)) {
  4379. continue;
  4380. }
  4381. icon_type_cache[E] = theme->get_icon(E, EditorStringName(EditorIcons));
  4382. }
  4383. }
  4384. void EditorNode::_enable_pending_addons() {
  4385. for (uint32_t i = 0; i < pending_addons.size(); i++) {
  4386. set_addon_plugin_enabled(pending_addons[i], true);
  4387. }
  4388. pending_addons.clear();
  4389. }
  4390. void EditorNode::_file_dialog_register(FileDialog *p_dialog) {
  4391. singleton->file_dialogs.insert(p_dialog);
  4392. }
  4393. void EditorNode::_file_dialog_unregister(FileDialog *p_dialog) {
  4394. singleton->file_dialogs.erase(p_dialog);
  4395. }
  4396. void EditorNode::_editor_file_dialog_register(EditorFileDialog *p_dialog) {
  4397. singleton->editor_file_dialogs.insert(p_dialog);
  4398. }
  4399. void EditorNode::_editor_file_dialog_unregister(EditorFileDialog *p_dialog) {
  4400. singleton->editor_file_dialogs.erase(p_dialog);
  4401. }
  4402. Vector<EditorNodeInitCallback> EditorNode::_init_callbacks;
  4403. void EditorNode::_begin_first_scan() {
  4404. // In headless mode, scan right away.
  4405. // This allows users to continue using `godot --headless --editor --quit` to prepare a project.
  4406. if (!DisplayServer::get_singleton()->window_can_draw()) {
  4407. OS::get_singleton()->benchmark_begin_measure("Editor", "First Scan");
  4408. EditorFileSystem::get_singleton()->scan();
  4409. return;
  4410. }
  4411. if (!waiting_for_first_scan) {
  4412. return;
  4413. }
  4414. requested_first_scan = true;
  4415. }
  4416. Error EditorNode::export_preset(const String &p_preset, const String &p_path, bool p_debug, bool p_pack_only, bool p_android_build_template, bool p_patch, const Vector<String> &p_patches) {
  4417. export_defer.preset = p_preset;
  4418. export_defer.path = p_path;
  4419. export_defer.debug = p_debug;
  4420. export_defer.pack_only = p_pack_only;
  4421. export_defer.android_build_template = p_android_build_template;
  4422. export_defer.patch = p_patch;
  4423. export_defer.patches = p_patches;
  4424. cmdline_export_mode = true;
  4425. return OK;
  4426. }
  4427. bool EditorNode::is_project_exporting() const {
  4428. return project_export && project_export->is_exporting();
  4429. }
  4430. void EditorNode::show_accept(const String &p_text, const String &p_title) {
  4431. current_menu_option = -1;
  4432. if (accept) {
  4433. _close_save_scene_progress();
  4434. accept->set_ok_button_text(p_title);
  4435. accept->set_text(p_text);
  4436. accept->reset_size();
  4437. EditorInterface::get_singleton()->popup_dialog_centered_clamped(accept, Size2i(), 0.0);
  4438. }
  4439. }
  4440. void EditorNode::show_save_accept(const String &p_text, const String &p_title) {
  4441. current_menu_option = -1;
  4442. if (save_accept) {
  4443. _close_save_scene_progress();
  4444. save_accept->set_ok_button_text(p_title);
  4445. save_accept->set_text(p_text);
  4446. save_accept->reset_size();
  4447. EditorInterface::get_singleton()->popup_dialog_centered_clamped(save_accept, Size2i(), 0.0);
  4448. }
  4449. }
  4450. void EditorNode::show_warning(const String &p_text, const String &p_title) {
  4451. if (warning) {
  4452. _close_save_scene_progress();
  4453. warning->set_text(p_text);
  4454. warning->set_title(p_title);
  4455. warning->reset_size();
  4456. EditorInterface::get_singleton()->popup_dialog_centered_clamped(warning, Size2i(), 0.0);
  4457. } else {
  4458. WARN_PRINT(p_title + " " + p_text);
  4459. }
  4460. }
  4461. void EditorNode::_copy_warning(const String &p_str) {
  4462. DisplayServer::get_singleton()->clipboard_set(warning->get_text());
  4463. }
  4464. void EditorNode::_save_editor_layout() {
  4465. if (!load_editor_layout_done) {
  4466. return;
  4467. }
  4468. Ref<ConfigFile> config;
  4469. config.instantiate();
  4470. // Load and amend existing config if it exists.
  4471. config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
  4472. editor_dock_manager->save_docks_to_config(config, "docks");
  4473. _save_open_scenes_to_config(config);
  4474. _save_central_editor_layout_to_config(config);
  4475. _save_window_settings_to_config(config, "EditorWindow");
  4476. editor_data.get_plugin_window_layout(config);
  4477. config->save(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
  4478. }
  4479. void EditorNode::_save_open_scenes_to_config(Ref<ConfigFile> p_layout) {
  4480. PackedStringArray scenes;
  4481. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  4482. String path = editor_data.get_scene_path(i);
  4483. if (path.is_empty()) {
  4484. continue;
  4485. }
  4486. scenes.push_back(path);
  4487. }
  4488. p_layout->set_value(EDITOR_NODE_CONFIG_SECTION, "open_scenes", scenes);
  4489. String currently_edited_scene_path = editor_data.get_scene_path(editor_data.get_edited_scene());
  4490. p_layout->set_value(EDITOR_NODE_CONFIG_SECTION, "current_scene", currently_edited_scene_path);
  4491. }
  4492. void EditorNode::save_editor_layout_delayed() {
  4493. editor_layout_save_delay_timer->start();
  4494. }
  4495. void EditorNode::_load_editor_layout() {
  4496. EditorProgress ep("loading_editor_layout", TTR("Loading editor"), 5);
  4497. ep.step(TTR("Loading editor layout..."), 0, true);
  4498. Ref<ConfigFile> config;
  4499. config.instantiate();
  4500. Error err = config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
  4501. if (err != OK) { // No config.
  4502. // If config is not found, expand the res:// folder and favorites by default.
  4503. TreeItem *root = FileSystemDock::get_singleton()->get_tree_control()->get_item_with_metadata("res://", 0);
  4504. if (root) {
  4505. root->set_collapsed(false);
  4506. }
  4507. TreeItem *favorites = FileSystemDock::get_singleton()->get_tree_control()->get_item_with_metadata("Favorites", 0);
  4508. if (favorites) {
  4509. favorites->set_collapsed(false);
  4510. }
  4511. if (overridden_default_layout >= 0) {
  4512. _layout_menu_option(overridden_default_layout);
  4513. }
  4514. } else {
  4515. ep.step(TTR("Loading docks..."), 1, true);
  4516. editor_dock_manager->load_docks_from_config(config, "docks");
  4517. ep.step(TTR("Reopening scenes..."), 2, true);
  4518. _load_open_scenes_from_config(config);
  4519. ep.step(TTR("Loading central editor layout..."), 3, true);
  4520. _load_central_editor_layout_from_config(config);
  4521. ep.step(TTR("Loading plugin window layout..."), 4, true);
  4522. editor_data.set_plugin_window_layout(config);
  4523. ep.step(TTR("Editor layout ready."), 5, true);
  4524. }
  4525. load_editor_layout_done = true;
  4526. }
  4527. void EditorNode::_save_central_editor_layout_to_config(Ref<ConfigFile> p_config_file) {
  4528. // Bottom panel.
  4529. int center_split_offset = center_split->get_split_offset();
  4530. p_config_file->set_value(EDITOR_NODE_CONFIG_SECTION, "center_split_offset", center_split_offset);
  4531. bottom_panel->save_layout_to_config(p_config_file, EDITOR_NODE_CONFIG_SECTION);
  4532. // Debugger tab.
  4533. int selected_default_debugger_tab_idx = EditorDebuggerNode::get_singleton()->get_default_debugger()->get_current_debugger_tab();
  4534. p_config_file->set_value(EDITOR_NODE_CONFIG_SECTION, "selected_default_debugger_tab_idx", selected_default_debugger_tab_idx);
  4535. // Main editor (plugin).
  4536. editor_main_screen->save_layout_to_config(p_config_file, EDITOR_NODE_CONFIG_SECTION);
  4537. }
  4538. void EditorNode::_load_central_editor_layout_from_config(Ref<ConfigFile> p_config_file) {
  4539. // Bottom panel.
  4540. bottom_panel->load_layout_from_config(p_config_file, EDITOR_NODE_CONFIG_SECTION);
  4541. if (p_config_file->has_section_key(EDITOR_NODE_CONFIG_SECTION, "center_split_offset")) {
  4542. int center_split_offset = p_config_file->get_value(EDITOR_NODE_CONFIG_SECTION, "center_split_offset");
  4543. center_split->set_split_offset(center_split_offset);
  4544. }
  4545. // Debugger tab.
  4546. if (p_config_file->has_section_key(EDITOR_NODE_CONFIG_SECTION, "selected_default_debugger_tab_idx")) {
  4547. int selected_default_debugger_tab_idx = p_config_file->get_value(EDITOR_NODE_CONFIG_SECTION, "selected_default_debugger_tab_idx");
  4548. EditorDebuggerNode::get_singleton()->get_default_debugger()->switch_to_debugger(selected_default_debugger_tab_idx);
  4549. }
  4550. // Main editor (plugin).
  4551. editor_main_screen->load_layout_from_config(p_config_file, EDITOR_NODE_CONFIG_SECTION);
  4552. }
  4553. void EditorNode::_save_window_settings_to_config(Ref<ConfigFile> p_layout, const String &p_section) {
  4554. Window *w = get_window();
  4555. if (w) {
  4556. p_layout->set_value(p_section, "screen", w->get_current_screen());
  4557. Window::Mode mode = w->get_mode();
  4558. switch (mode) {
  4559. case Window::MODE_WINDOWED:
  4560. p_layout->set_value(p_section, "mode", "windowed");
  4561. p_layout->set_value(p_section, "size", w->get_size());
  4562. break;
  4563. case Window::MODE_FULLSCREEN:
  4564. case Window::MODE_EXCLUSIVE_FULLSCREEN:
  4565. p_layout->set_value(p_section, "mode", "fullscreen");
  4566. break;
  4567. case Window::MODE_MINIMIZED:
  4568. if (was_window_windowed_last) {
  4569. p_layout->set_value(p_section, "mode", "windowed");
  4570. p_layout->set_value(p_section, "size", w->get_size());
  4571. } else {
  4572. p_layout->set_value(p_section, "mode", "maximized");
  4573. }
  4574. break;
  4575. default:
  4576. p_layout->set_value(p_section, "mode", "maximized");
  4577. break;
  4578. }
  4579. p_layout->set_value(p_section, "position", w->get_position());
  4580. }
  4581. }
  4582. void EditorNode::_load_open_scenes_from_config(Ref<ConfigFile> p_layout) {
  4583. if (!bool(EDITOR_GET("interface/scene_tabs/restore_scenes_on_load"))) {
  4584. return;
  4585. }
  4586. if (!p_layout->has_section(EDITOR_NODE_CONFIG_SECTION) ||
  4587. !p_layout->has_section_key(EDITOR_NODE_CONFIG_SECTION, "open_scenes")) {
  4588. return;
  4589. }
  4590. restoring_scenes = true;
  4591. PackedStringArray scenes = p_layout->get_value(EDITOR_NODE_CONFIG_SECTION, "open_scenes");
  4592. for (int i = 0; i < scenes.size(); i++) {
  4593. if (FileAccess::exists(scenes[i])) {
  4594. load_scene(scenes[i]);
  4595. }
  4596. }
  4597. if (p_layout->has_section_key(EDITOR_NODE_CONFIG_SECTION, "current_scene")) {
  4598. String current_scene = p_layout->get_value(EDITOR_NODE_CONFIG_SECTION, "current_scene");
  4599. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  4600. if (editor_data.get_scene_path(i) == current_scene) {
  4601. _set_current_scene(i);
  4602. break;
  4603. }
  4604. }
  4605. }
  4606. save_editor_layout_delayed();
  4607. restoring_scenes = false;
  4608. }
  4609. bool EditorNode::has_scenes_in_session() {
  4610. if (!bool(EDITOR_GET("interface/scene_tabs/restore_scenes_on_load"))) {
  4611. return false;
  4612. }
  4613. Ref<ConfigFile> config;
  4614. config.instantiate();
  4615. Error err = config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
  4616. if (err != OK) {
  4617. return false;
  4618. }
  4619. if (!config->has_section(EDITOR_NODE_CONFIG_SECTION) || !config->has_section_key(EDITOR_NODE_CONFIG_SECTION, "open_scenes")) {
  4620. return false;
  4621. }
  4622. Array scenes = config->get_value(EDITOR_NODE_CONFIG_SECTION, "open_scenes");
  4623. return !scenes.is_empty();
  4624. }
  4625. void EditorNode::undo() {
  4626. trigger_menu_option(EDIT_UNDO, true);
  4627. }
  4628. void EditorNode::redo() {
  4629. trigger_menu_option(EDIT_REDO, true);
  4630. }
  4631. bool EditorNode::ensure_main_scene(bool p_from_native) {
  4632. pick_main_scene->set_meta("from_native", p_from_native); // Whether from play button or native run.
  4633. String main_scene = GLOBAL_GET("application/run/main_scene");
  4634. if (main_scene.is_empty()) {
  4635. current_menu_option = -1;
  4636. pick_main_scene->set_text(TTR("No main scene has ever been defined. Select one?\nYou can change it later in \"Project Settings\" under the 'application' category."));
  4637. pick_main_scene->popup_centered();
  4638. if (editor_data.get_edited_scene_root()) {
  4639. select_current_scene_button->set_disabled(false);
  4640. select_current_scene_button->grab_focus();
  4641. } else {
  4642. select_current_scene_button->set_disabled(true);
  4643. }
  4644. return false;
  4645. }
  4646. if (!FileAccess::exists(main_scene)) {
  4647. current_menu_option = -1;
  4648. pick_main_scene->set_text(vformat(TTR("Selected scene '%s' does not exist. Select a valid one?\nYou can change it later in \"Project Settings\" under the 'application' category."), main_scene));
  4649. pick_main_scene->popup_centered();
  4650. return false;
  4651. }
  4652. if (ResourceLoader::get_resource_type(main_scene) != "PackedScene") {
  4653. current_menu_option = -1;
  4654. pick_main_scene->set_text(vformat(TTR("Selected scene '%s' is not a scene file. Select a valid one?\nYou can change it later in \"Project Settings\" under the 'application' category."), main_scene));
  4655. pick_main_scene->popup_centered();
  4656. return false;
  4657. }
  4658. return true;
  4659. }
  4660. void EditorNode::_immediate_dialog_confirmed() {
  4661. immediate_dialog_confirmed = true;
  4662. }
  4663. bool EditorNode::immediate_confirmation_dialog(const String &p_text, const String &p_ok_text, const String &p_cancel_text, uint32_t p_wrap_width) {
  4664. ConfirmationDialog *cd = memnew(ConfirmationDialog);
  4665. cd->set_text(p_text);
  4666. cd->set_ok_button_text(p_ok_text);
  4667. cd->set_cancel_button_text(p_cancel_text);
  4668. if (p_wrap_width > 0) {
  4669. cd->set_autowrap(true);
  4670. cd->get_label()->set_custom_minimum_size(Size2(p_wrap_width, 0) * EDSCALE);
  4671. }
  4672. cd->connect(SceneStringName(confirmed), callable_mp(singleton, &EditorNode::_immediate_dialog_confirmed));
  4673. singleton->gui_base->add_child(cd);
  4674. cd->popup_centered();
  4675. while (true) {
  4676. DisplayServer::get_singleton()->process_events();
  4677. Main::iteration();
  4678. if (singleton->immediate_dialog_confirmed || !cd->is_visible()) {
  4679. break;
  4680. }
  4681. }
  4682. memdelete(cd);
  4683. return singleton->immediate_dialog_confirmed;
  4684. }
  4685. void EditorNode::cleanup() {
  4686. _init_callbacks.clear();
  4687. }
  4688. void EditorNode::_update_layouts_menu() {
  4689. editor_layouts->clear();
  4690. overridden_default_layout = -1;
  4691. editor_layouts->reset_size();
  4692. editor_layouts->add_shortcut(ED_SHORTCUT("layout/save", TTRC("Save Layout...")), SETTINGS_LAYOUT_SAVE);
  4693. editor_layouts->add_shortcut(ED_SHORTCUT("layout/delete", TTRC("Delete Layout...")), SETTINGS_LAYOUT_DELETE);
  4694. editor_layouts->add_separator();
  4695. editor_layouts->add_shortcut(ED_SHORTCUT("layout/default", TTRC("Default")), SETTINGS_LAYOUT_DEFAULT);
  4696. Ref<ConfigFile> config;
  4697. config.instantiate();
  4698. Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
  4699. if (err != OK) {
  4700. return; // No config.
  4701. }
  4702. List<String> layouts;
  4703. config.ptr()->get_sections(&layouts);
  4704. for (const String &layout : layouts) {
  4705. if (layout == TTR("Default")) {
  4706. editor_layouts->remove_item(editor_layouts->get_item_index(SETTINGS_LAYOUT_DEFAULT));
  4707. overridden_default_layout = editor_layouts->get_item_count();
  4708. }
  4709. editor_layouts->add_item(layout);
  4710. }
  4711. }
  4712. void EditorNode::_layout_menu_option(int p_id) {
  4713. switch (p_id) {
  4714. case SETTINGS_LAYOUT_SAVE: {
  4715. current_menu_option = p_id;
  4716. layout_dialog->set_title(TTR("Save Layout"));
  4717. layout_dialog->set_ok_button_text(TTR("Save"));
  4718. layout_dialog->set_name_line_enabled(true);
  4719. layout_dialog->popup_centered();
  4720. } break;
  4721. case SETTINGS_LAYOUT_DELETE: {
  4722. current_menu_option = p_id;
  4723. layout_dialog->set_title(TTR("Delete Layout"));
  4724. layout_dialog->set_ok_button_text(TTR("Delete"));
  4725. layout_dialog->set_name_line_enabled(false);
  4726. layout_dialog->popup_centered();
  4727. } break;
  4728. case SETTINGS_LAYOUT_DEFAULT: {
  4729. editor_dock_manager->load_docks_from_config(default_layout, "docks");
  4730. _save_editor_layout();
  4731. } break;
  4732. default: {
  4733. Ref<ConfigFile> config;
  4734. config.instantiate();
  4735. Error err = config->load(EditorSettings::get_singleton()->get_editor_layouts_config());
  4736. if (err != OK) {
  4737. return; // No config.
  4738. }
  4739. editor_dock_manager->load_docks_from_config(config, editor_layouts->get_item_text(p_id));
  4740. _save_editor_layout();
  4741. }
  4742. }
  4743. }
  4744. void EditorNode::_proceed_closing_scene_tabs() {
  4745. List<String>::Element *E = tabs_to_close.front();
  4746. if (!E) {
  4747. if (_is_closing_editor()) {
  4748. current_menu_option = tab_closing_menu_option;
  4749. _menu_option_confirm(tab_closing_menu_option, true);
  4750. } else {
  4751. current_menu_option = -1;
  4752. save_confirmation->hide();
  4753. }
  4754. return;
  4755. }
  4756. String scene_to_close = E->get();
  4757. tabs_to_close.pop_front();
  4758. int tab_idx = -1;
  4759. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  4760. if (editor_data.get_scene_path(i) == scene_to_close) {
  4761. tab_idx = i;
  4762. break;
  4763. }
  4764. }
  4765. ERR_FAIL_COND(tab_idx < 0);
  4766. _scene_tab_closed(tab_idx);
  4767. }
  4768. bool EditorNode::_is_closing_editor() const {
  4769. return tab_closing_menu_option == FILE_QUIT || tab_closing_menu_option == RUN_PROJECT_MANAGER || tab_closing_menu_option == RELOAD_CURRENT_PROJECT;
  4770. }
  4771. void EditorNode::_scene_tab_closed(int p_tab) {
  4772. current_menu_option = SCENE_TAB_CLOSE;
  4773. tab_closing_idx = p_tab;
  4774. Node *scene = editor_data.get_edited_scene_root(p_tab);
  4775. if (!scene) {
  4776. _discard_changes();
  4777. return;
  4778. }
  4779. String scene_filename = scene->get_scene_file_path();
  4780. String unsaved_message;
  4781. if (EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(p_tab))) {
  4782. if (scene_filename.is_empty()) {
  4783. unsaved_message = TTR("This scene was never saved.");
  4784. } else {
  4785. // Consider editor startup to be a point of saving, so that when you
  4786. // close and reopen the editor, you don't get an excessively long
  4787. // "modified X hours ago".
  4788. const uint64_t last_modified_seconds = Time::get_singleton()->get_unix_time_from_system() - MAX(started_timestamp, FileAccess::get_modified_time(scene->get_scene_file_path()));
  4789. String last_modified_string;
  4790. if (last_modified_seconds < 120) {
  4791. last_modified_string = vformat(TTRN("%d second ago", "%d seconds ago", last_modified_seconds), last_modified_seconds);
  4792. } else if (last_modified_seconds < 7200) {
  4793. last_modified_string = vformat(TTRN("%d minute ago", "%d minutes ago", last_modified_seconds / 60), last_modified_seconds / 60);
  4794. } else {
  4795. last_modified_string = vformat(TTRN("%d hour ago", "%d hours ago", last_modified_seconds / 3600), last_modified_seconds / 3600);
  4796. }
  4797. unsaved_message = vformat(TTR("Scene \"%s\" has unsaved changes.\nLast saved: %s."), scene_filename, last_modified_string);
  4798. }
  4799. } else {
  4800. // Check if any plugin has unsaved changes in that scene.
  4801. for (int i = 0; i < editor_data.get_editor_plugin_count(); i++) {
  4802. unsaved_message = editor_data.get_editor_plugin(i)->get_unsaved_status(scene_filename);
  4803. if (!unsaved_message.is_empty()) {
  4804. break;
  4805. }
  4806. }
  4807. }
  4808. if (!unsaved_message.is_empty()) {
  4809. if (scene_tabs->get_current_tab() != p_tab) {
  4810. _set_current_scene(p_tab);
  4811. }
  4812. save_confirmation->set_ok_button_text(TTR("Save & Close"));
  4813. save_confirmation->set_text(unsaved_message + "\n\n" + TTR("Save before closing?"));
  4814. save_confirmation->reset_size();
  4815. save_confirmation->popup_centered();
  4816. } else {
  4817. _discard_changes();
  4818. }
  4819. save_editor_layout_delayed();
  4820. scene_tabs->update_scene_tabs();
  4821. }
  4822. void EditorNode::_cancel_close_scene_tab() {
  4823. if (_is_closing_editor()) {
  4824. tab_closing_menu_option = -1;
  4825. }
  4826. }
  4827. void EditorNode::_toggle_distraction_free_mode() {
  4828. if (EDITOR_GET("interface/editor/separate_distraction_mode")) {
  4829. int screen = editor_main_screen->get_selected_index();
  4830. if (screen == EditorMainScreen::EDITOR_SCRIPT) {
  4831. script_distraction_free = !script_distraction_free;
  4832. set_distraction_free_mode(script_distraction_free);
  4833. } else {
  4834. scene_distraction_free = !scene_distraction_free;
  4835. set_distraction_free_mode(scene_distraction_free);
  4836. }
  4837. } else {
  4838. set_distraction_free_mode(distraction_free->is_pressed());
  4839. }
  4840. }
  4841. void EditorNode::update_distraction_free_mode() {
  4842. if (!EDITOR_GET("interface/editor/separate_distraction_mode")) {
  4843. return;
  4844. }
  4845. int screen = editor_main_screen->get_selected_index();
  4846. if (screen == EditorMainScreen::EDITOR_SCRIPT) {
  4847. set_distraction_free_mode(script_distraction_free);
  4848. } else {
  4849. set_distraction_free_mode(scene_distraction_free);
  4850. }
  4851. }
  4852. void EditorNode::set_distraction_free_mode(bool p_enter) {
  4853. distraction_free->set_pressed(p_enter);
  4854. if (p_enter) {
  4855. if (editor_dock_manager->are_docks_visible()) {
  4856. editor_dock_manager->set_docks_visible(false);
  4857. }
  4858. } else {
  4859. editor_dock_manager->set_docks_visible(true);
  4860. }
  4861. }
  4862. bool EditorNode::is_distraction_free_mode_enabled() const {
  4863. return distraction_free->is_pressed();
  4864. }
  4865. Dictionary EditorNode::drag_resource(const Ref<Resource> &p_res, Control *p_from) {
  4866. Control *drag_control = memnew(Control);
  4867. TextureRect *drag_preview = memnew(TextureRect);
  4868. Label *label = memnew(Label);
  4869. label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  4870. Ref<Texture2D> preview;
  4871. {
  4872. // TODO: make proper previews
  4873. Ref<ImageTexture> texture = theme->get_icon(SNAME("FileBigThumb"), EditorStringName(EditorIcons));
  4874. Ref<Image> img = texture->get_image();
  4875. img = img->duplicate();
  4876. img->resize(48, 48); // meh
  4877. preview = ImageTexture::create_from_image(img);
  4878. }
  4879. drag_preview->set_texture(preview);
  4880. drag_control->add_child(drag_preview);
  4881. if (p_res->get_path().is_resource_file()) {
  4882. label->set_text(p_res->get_path().get_file());
  4883. } else if (!p_res->get_name().is_empty()) {
  4884. label->set_text(p_res->get_name());
  4885. } else {
  4886. label->set_text(p_res->get_class());
  4887. }
  4888. drag_control->add_child(label);
  4889. p_from->set_drag_preview(drag_control); // Wait until it enters scene.
  4890. label->set_position(Point2((preview->get_width() - label->get_minimum_size().width) / 2, preview->get_height()));
  4891. Dictionary drag_data;
  4892. drag_data["type"] = "resource";
  4893. drag_data["resource"] = p_res;
  4894. drag_data["from"] = p_from;
  4895. return drag_data;
  4896. }
  4897. Dictionary EditorNode::drag_files_and_dirs(const Vector<String> &p_paths, Control *p_from) {
  4898. bool has_folder = false;
  4899. bool has_file = false;
  4900. for (int i = 0; i < p_paths.size(); i++) {
  4901. bool is_folder = p_paths[i].ends_with("/");
  4902. has_folder |= is_folder;
  4903. has_file |= !is_folder;
  4904. }
  4905. int max_rows = 6;
  4906. int num_rows = p_paths.size() > max_rows ? max_rows - 1 : p_paths.size(); // Don't waste a row to say "1 more file" - list it instead.
  4907. VBoxContainer *vbox = memnew(VBoxContainer);
  4908. for (int i = 0; i < num_rows; i++) {
  4909. HBoxContainer *hbox = memnew(HBoxContainer);
  4910. TextureRect *icon = memnew(TextureRect);
  4911. Label *label = memnew(Label);
  4912. label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  4913. if (p_paths[i].ends_with("/")) {
  4914. label->set_text(p_paths[i].substr(0, p_paths[i].length() - 1).get_file());
  4915. icon->set_texture(theme->get_icon(SNAME("Folder"), EditorStringName(EditorIcons)));
  4916. } else {
  4917. label->set_text(p_paths[i].get_file());
  4918. icon->set_texture(theme->get_icon(SNAME("File"), EditorStringName(EditorIcons)));
  4919. }
  4920. icon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
  4921. icon->set_size(Size2(16, 16));
  4922. hbox->add_child(icon);
  4923. hbox->add_child(label);
  4924. vbox->add_child(hbox);
  4925. }
  4926. if (p_paths.size() > num_rows) {
  4927. Label *label = memnew(Label);
  4928. if (has_file && has_folder) {
  4929. label->set_text(vformat(TTR("%d more files or folders"), p_paths.size() - num_rows));
  4930. } else if (has_folder) {
  4931. label->set_text(vformat(TTR("%d more folders"), p_paths.size() - num_rows));
  4932. } else {
  4933. label->set_text(vformat(TTR("%d more files"), p_paths.size() - num_rows));
  4934. }
  4935. vbox->add_child(label);
  4936. }
  4937. p_from->set_drag_preview(vbox); // Wait until it enters scene.
  4938. Dictionary drag_data;
  4939. drag_data["type"] = has_folder ? "files_and_dirs" : "files";
  4940. drag_data["files"] = p_paths;
  4941. drag_data["from"] = p_from;
  4942. return drag_data;
  4943. }
  4944. void EditorNode::add_tool_menu_item(const String &p_name, const Callable &p_callback) {
  4945. int idx = tool_menu->get_item_count();
  4946. tool_menu->add_item(p_name, TOOLS_CUSTOM);
  4947. tool_menu->set_item_metadata(idx, p_callback);
  4948. }
  4949. void EditorNode::add_tool_submenu_item(const String &p_name, PopupMenu *p_submenu) {
  4950. ERR_FAIL_NULL(p_submenu);
  4951. ERR_FAIL_COND(p_submenu->get_parent() != nullptr);
  4952. tool_menu->add_submenu_node_item(p_name, p_submenu, TOOLS_CUSTOM);
  4953. }
  4954. void EditorNode::remove_tool_menu_item(const String &p_name) {
  4955. for (int i = 0; i < tool_menu->get_item_count(); i++) {
  4956. if (tool_menu->get_item_id(i) != TOOLS_CUSTOM) {
  4957. continue;
  4958. }
  4959. if (tool_menu->get_item_text(i) == p_name) {
  4960. if (tool_menu->get_item_submenu(i) != "") {
  4961. Node *n = tool_menu->get_node(tool_menu->get_item_submenu(i));
  4962. tool_menu->remove_child(n);
  4963. memdelete(n);
  4964. }
  4965. tool_menu->remove_item(i);
  4966. tool_menu->reset_size();
  4967. return;
  4968. }
  4969. }
  4970. }
  4971. PopupMenu *EditorNode::get_export_as_menu() {
  4972. return export_as_menu;
  4973. }
  4974. void EditorNode::_dropped_files(const Vector<String> &p_files) {
  4975. String to_path = FileSystemDock::get_singleton()->get_folder_path_at_mouse_position();
  4976. if (to_path.is_empty()) {
  4977. to_path = FileSystemDock::get_singleton()->get_current_directory();
  4978. }
  4979. to_path = ProjectSettings::get_singleton()->globalize_path(to_path);
  4980. _add_dropped_files_recursive(p_files, to_path);
  4981. EditorFileSystem::get_singleton()->scan_changes();
  4982. }
  4983. void EditorNode::_add_dropped_files_recursive(const Vector<String> &p_files, String to_path) {
  4984. Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  4985. ERR_FAIL_COND(dir.is_null());
  4986. for (int i = 0; i < p_files.size(); i++) {
  4987. const String &from = p_files[i];
  4988. String to = to_path.path_join(from.get_file());
  4989. if (dir->dir_exists(from)) {
  4990. Vector<String> sub_files;
  4991. Ref<DirAccess> sub_dir = DirAccess::open(from);
  4992. ERR_FAIL_COND(sub_dir.is_null());
  4993. sub_dir->list_dir_begin();
  4994. String next_file = sub_dir->get_next();
  4995. while (!next_file.is_empty()) {
  4996. if (next_file == "." || next_file == "..") {
  4997. next_file = sub_dir->get_next();
  4998. continue;
  4999. }
  5000. sub_files.push_back(from.path_join(next_file));
  5001. next_file = sub_dir->get_next();
  5002. }
  5003. if (!sub_files.is_empty()) {
  5004. dir->make_dir(to);
  5005. _add_dropped_files_recursive(sub_files, to);
  5006. }
  5007. continue;
  5008. }
  5009. dir->copy(from, to);
  5010. }
  5011. }
  5012. void EditorNode::_file_access_close_error_notify(const String &p_str) {
  5013. callable_mp_static(&EditorNode::_file_access_close_error_notify_impl).call_deferred(p_str);
  5014. }
  5015. void EditorNode::_file_access_close_error_notify_impl(const String &p_str) {
  5016. add_io_error(vformat(TTR("Unable to write to file '%s', file in use, locked or lacking permissions."), p_str));
  5017. }
  5018. // Recursive function to inform nodes that an array of nodes have had their scene reimported.
  5019. // It will attempt to call a method named '_nodes_scene_reimported' on every node in the
  5020. // tree so that editor scripts which create transient nodes will have the opportunity
  5021. // to recreate them.
  5022. void EditorNode::_notify_nodes_scene_reimported(Node *p_node, Array p_reimported_nodes) {
  5023. Skeleton3D *skel_3d = Object::cast_to<Skeleton3D>(p_node);
  5024. if (skel_3d) {
  5025. skel_3d->reset_bone_poses();
  5026. } else {
  5027. BoneAttachment3D *attachment = Object::cast_to<BoneAttachment3D>(p_node);
  5028. if (attachment) {
  5029. attachment->notify_rebind_required();
  5030. }
  5031. }
  5032. if (p_node->has_method("_nodes_scene_reimported")) {
  5033. p_node->call("_nodes_scene_reimported", p_reimported_nodes);
  5034. }
  5035. for (int i = 0; i < p_node->get_child_count(); i++) {
  5036. _notify_nodes_scene_reimported(p_node->get_child(i), p_reimported_nodes);
  5037. }
  5038. }
  5039. void EditorNode::reload_scene(const String &p_path) {
  5040. int scene_idx = -1;
  5041. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
  5042. if (editor_data.get_scene_path(i) == p_path) {
  5043. scene_idx = i;
  5044. break;
  5045. }
  5046. }
  5047. int current_tab = editor_data.get_edited_scene();
  5048. if (scene_idx == -1) {
  5049. if (get_edited_scene()) {
  5050. int current_history_id = editor_data.get_current_edited_scene_history_id();
  5051. bool is_unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(current_history_id);
  5052. // Scene is not open, so at it might be instantiated. We'll refresh the whole scene later.
  5053. EditorUndoRedoManager::get_singleton()->clear_history(current_history_id, false);
  5054. if (is_unsaved) {
  5055. EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(current_history_id);
  5056. }
  5057. }
  5058. return;
  5059. }
  5060. if (current_tab == scene_idx) {
  5061. editor_data.apply_changes_in_editors();
  5062. _save_editor_states(p_path);
  5063. }
  5064. // Reload scene.
  5065. _remove_scene(scene_idx, false);
  5066. load_scene(p_path, true, false, true);
  5067. // Adjust index so tab is back a the previous position.
  5068. editor_data.move_edited_scene_to_index(scene_idx);
  5069. EditorUndoRedoManager::get_singleton()->clear_history(editor_data.get_scene_history_id(scene_idx), false);
  5070. // Recover the tab.
  5071. scene_tabs->set_current_tab(current_tab);
  5072. }
  5073. void EditorNode::find_all_instances_inheriting_path_in_node(Node *p_root, Node *p_node, const String &p_instance_path, HashSet<Node *> &p_instance_list) {
  5074. String scene_file_path = p_node->get_scene_file_path();
  5075. bool valid_instance_found = false;
  5076. // Attempt to find all the instances matching path we're going to reload.
  5077. if (p_node->get_scene_file_path() == p_instance_path) {
  5078. valid_instance_found = true;
  5079. } else {
  5080. Node *current_node = p_node;
  5081. Ref<SceneState> inherited_state = current_node->get_scene_inherited_state();
  5082. while (inherited_state.is_valid()) {
  5083. String inherited_path = inherited_state->get_path();
  5084. if (inherited_path == p_instance_path) {
  5085. valid_instance_found = true;
  5086. break;
  5087. }
  5088. inherited_state = inherited_state->get_base_scene_state();
  5089. }
  5090. }
  5091. // Instead of adding this instance directly, if its not owned by the scene, walk its ancestors
  5092. // and find the first node still owned by the scene. This is what we will reloading instead.
  5093. if (valid_instance_found) {
  5094. Node *current_node = p_node;
  5095. while (true) {
  5096. if (current_node->get_owner() == p_root || current_node->get_owner() == nullptr) {
  5097. p_instance_list.insert(current_node);
  5098. break;
  5099. }
  5100. current_node = current_node->get_parent();
  5101. }
  5102. }
  5103. for (int i = 0; i < p_node->get_child_count(); i++) {
  5104. find_all_instances_inheriting_path_in_node(p_root, p_node->get_child(i), p_instance_path, p_instance_list);
  5105. }
  5106. }
  5107. void EditorNode::preload_reimporting_with_path_in_edited_scenes(const List<String> &p_scenes) {
  5108. EditorProgress progress("preload_reimporting_scene", TTR("Preparing scenes for reload"), editor_data.get_edited_scene_count());
  5109. int original_edited_scene_idx = editor_data.get_edited_scene();
  5110. // Walk through each opened scene to get a global list of all instances which match
  5111. // the current reimported scenes.
  5112. for (int current_scene_idx = 0; current_scene_idx < editor_data.get_edited_scene_count(); current_scene_idx++) {
  5113. progress.step(vformat(TTR("Analyzing scene %s"), editor_data.get_scene_title(current_scene_idx)), current_scene_idx);
  5114. Node *edited_scene_root = editor_data.get_edited_scene_root(current_scene_idx);
  5115. if (edited_scene_root) {
  5116. SceneModificationsEntry scene_modifications;
  5117. for (const String &instance_path : p_scenes) {
  5118. if (editor_data.get_scene_path(current_scene_idx) == instance_path) {
  5119. continue;
  5120. }
  5121. HashSet<Node *> instances_to_reimport;
  5122. find_all_instances_inheriting_path_in_node(edited_scene_root, edited_scene_root, instance_path, instances_to_reimport);
  5123. if (instances_to_reimport.size() > 0) {
  5124. editor_data.set_edited_scene(current_scene_idx);
  5125. List<Node *> instance_list_with_children;
  5126. for (Node *original_node : instances_to_reimport) {
  5127. InstanceModificationsEntry instance_modifications;
  5128. // Fetching all the modified properties of the nodes reimported scene.
  5129. get_preload_scene_modification_table(edited_scene_root, original_node, original_node, instance_modifications);
  5130. instance_modifications.original_node = original_node;
  5131. instance_modifications.instance_path = instance_path;
  5132. scene_modifications.instance_list.push_back(instance_modifications);
  5133. instance_list_with_children.push_back(original_node);
  5134. get_children_nodes(original_node, instance_list_with_children);
  5135. }
  5136. // Search the scene to find nodes that references the nodes will be recreated.
  5137. get_preload_modifications_reference_to_nodes(edited_scene_root, edited_scene_root, instances_to_reimport, instance_list_with_children, scene_modifications.other_instances_modifications);
  5138. }
  5139. }
  5140. if (scene_modifications.instance_list.size() > 0) {
  5141. scenes_modification_table[current_scene_idx] = scene_modifications;
  5142. }
  5143. }
  5144. }
  5145. editor_data.set_edited_scene(original_edited_scene_idx);
  5146. progress.step(TTR("Preparation done."), editor_data.get_edited_scene_count());
  5147. }
  5148. void EditorNode::reload_instances_with_path_in_edited_scenes() {
  5149. if (scenes_modification_table.size() == 0) {
  5150. return;
  5151. }
  5152. EditorProgress progress("reloading_scene", TTR("Scenes reloading"), editor_data.get_edited_scene_count());
  5153. progress.step(TTR("Reloading..."), 0, true);
  5154. Error err;
  5155. Array replaced_nodes;
  5156. HashMap<String, Ref<PackedScene>> local_scene_cache;
  5157. // Reload the new instances.
  5158. for (KeyValue<int, SceneModificationsEntry> &scene_modifications_elem : scenes_modification_table) {
  5159. for (InstanceModificationsEntry instance_modifications : scene_modifications_elem.value.instance_list) {
  5160. if (!local_scene_cache.has(instance_modifications.instance_path)) {
  5161. Ref<PackedScene> instance_scene_packed_scene = ResourceLoader::load(instance_modifications.instance_path, "", ResourceFormatLoader::CACHE_MODE_REPLACE, &err);
  5162. ERR_FAIL_COND(err != OK);
  5163. ERR_FAIL_COND(instance_scene_packed_scene.is_null());
  5164. local_scene_cache[instance_modifications.instance_path] = instance_scene_packed_scene;
  5165. }
  5166. }
  5167. }
  5168. // Save the current scene state/selection in case of lost.
  5169. Dictionary editor_state = _get_main_scene_state();
  5170. editor_data.save_edited_scene_state(editor_selection, &editor_history, editor_state);
  5171. editor_selection->clear();
  5172. int original_edited_scene_idx = editor_data.get_edited_scene();
  5173. for (KeyValue<int, SceneModificationsEntry> &scene_modifications_elem : scenes_modification_table) {
  5174. // Set the current scene.
  5175. int current_scene_idx = scene_modifications_elem.key;
  5176. SceneModificationsEntry *scene_modifications = &scene_modifications_elem.value;
  5177. editor_data.set_edited_scene(current_scene_idx);
  5178. Node *current_edited_scene = editor_data.get_edited_scene_root(current_scene_idx);
  5179. // Make sure the node is in the tree so that editor_selection can add node smoothly.
  5180. if (original_edited_scene_idx != current_scene_idx) {
  5181. // Prevent scene roots with the same name from being in the tree at the same time.
  5182. Node *original_edited_scene_root = editor_data.get_edited_scene_root(original_edited_scene_idx);
  5183. if (original_edited_scene_root && original_edited_scene_root->get_name() == current_edited_scene->get_name()) {
  5184. scene_root->remove_child(original_edited_scene_root);
  5185. }
  5186. scene_root->add_child(current_edited_scene);
  5187. }
  5188. // Restore the state so that the selection can be updated.
  5189. editor_state = editor_data.restore_edited_scene_state(editor_selection, &editor_history);
  5190. int current_history_id = editor_data.get_current_edited_scene_history_id();
  5191. bool is_unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(current_history_id);
  5192. // Clear the history for this affected tab.
  5193. EditorUndoRedoManager::get_singleton()->clear_history(current_history_id, false);
  5194. // Update the version
  5195. editor_data.is_scene_changed(current_scene_idx);
  5196. for (InstanceModificationsEntry instance_modifications : scene_modifications->instance_list) {
  5197. Node *original_node = instance_modifications.original_node;
  5198. String original_node_file_path = original_node->get_scene_file_path();
  5199. Ref<PackedScene> instance_scene_packed_scene = local_scene_cache[instance_modifications.instance_path];
  5200. // Load a replacement scene for the node.
  5201. Ref<PackedScene> current_packed_scene;
  5202. Ref<PackedScene> base_packed_scene;
  5203. if (original_node_file_path == instance_modifications.instance_path) {
  5204. // If the node file name directly matches the scene we're replacing,
  5205. // just load it since we already cached it.
  5206. current_packed_scene = instance_scene_packed_scene;
  5207. } else {
  5208. // Otherwise, check the inheritance chain, reloading and caching any scenes
  5209. // we require along the way.
  5210. List<String> required_load_paths;
  5211. // Do we need to check if the paths are empty?
  5212. if (!original_node_file_path.is_empty()) {
  5213. required_load_paths.push_front(original_node_file_path);
  5214. }
  5215. Ref<SceneState> inherited_state = original_node->get_scene_inherited_state();
  5216. while (inherited_state.is_valid()) {
  5217. String inherited_path = inherited_state->get_path();
  5218. // Do we need to check if the paths are empty?
  5219. if (!inherited_path.is_empty()) {
  5220. required_load_paths.push_front(inherited_path);
  5221. }
  5222. inherited_state = inherited_state->get_base_scene_state();
  5223. }
  5224. // Ensure the inheritance chain is loaded in the correct order so that cache can
  5225. // be properly updated.
  5226. for (String path : required_load_paths) {
  5227. if (current_packed_scene.is_valid()) {
  5228. base_packed_scene = current_packed_scene;
  5229. }
  5230. if (!local_scene_cache.find(path)) {
  5231. current_packed_scene = ResourceLoader::load(path, "", ResourceFormatLoader::CACHE_MODE_REPLACE, &err);
  5232. local_scene_cache[path] = current_packed_scene;
  5233. } else {
  5234. current_packed_scene = local_scene_cache[path];
  5235. }
  5236. }
  5237. }
  5238. ERR_FAIL_COND(current_packed_scene.is_null());
  5239. // Instantiate early so that caches cleared on load in SceneState can be rebuilt early.
  5240. Node *instantiated_node = nullptr;
  5241. // If we are in a inherited scene, it's easier to create a new base scene and
  5242. // grab the node from there.
  5243. // When scene_path_to_node is '.' and we have scene_inherited_state, it's because
  5244. // it's a multi-level inheritance scene. We should use
  5245. NodePath scene_path_to_node = current_edited_scene->get_path_to(original_node);
  5246. Ref<SceneState> scene_state = current_edited_scene->get_scene_inherited_state();
  5247. if (scene_path_to_node != "." && scene_state.is_valid() && scene_state->get_path() != instance_modifications.instance_path && scene_state->find_node_by_path(scene_path_to_node) >= 0) {
  5248. Node *root_node = scene_state->instantiate(SceneState::GenEditState::GEN_EDIT_STATE_INSTANCE);
  5249. instantiated_node = root_node->get_node(scene_path_to_node);
  5250. if (instantiated_node) {
  5251. if (instantiated_node->get_parent()) {
  5252. // Remove from the root so we can delete it from memory.
  5253. instantiated_node->get_parent()->remove_child(instantiated_node);
  5254. // No need of the additional children that could have been added to the node
  5255. // in the base scene. That will be managed by the 'addition_list' later.
  5256. _remove_all_not_owned_children(instantiated_node, instantiated_node);
  5257. memdelete(root_node);
  5258. }
  5259. } else {
  5260. // Should not happen because we checked with find_node_by_path before, just in case.
  5261. memdelete(root_node);
  5262. }
  5263. }
  5264. if (!instantiated_node) {
  5265. // If no base scene was found to create the node, we will use the reimported packed scene directly.
  5266. // But, when the current edited scene is the reimported scene, it's because it's an inherited scene
  5267. // derived from the reimported scene. In that case, we will not instantiate current_packed_scene, because
  5268. // we would reinstantiate ourself. Using the base scene is better.
  5269. if (current_edited_scene == original_node) {
  5270. if (base_packed_scene.is_valid()) {
  5271. instantiated_node = base_packed_scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  5272. } else {
  5273. instantiated_node = instance_scene_packed_scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  5274. }
  5275. } else {
  5276. instantiated_node = current_packed_scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  5277. }
  5278. }
  5279. ERR_FAIL_NULL(instantiated_node);
  5280. // Disconnect all relevant connections, all connections from and persistent connections to.
  5281. for (const KeyValue<NodePath, ModificationNodeEntry> &modification_table_entry : instance_modifications.modifications) {
  5282. for (Connection conn : modification_table_entry.value.connections_from) {
  5283. conn.signal.get_object()->disconnect(conn.signal.get_name(), conn.callable);
  5284. }
  5285. for (ConnectionWithNodePath cwnp : modification_table_entry.value.connections_to) {
  5286. Connection conn = cwnp.connection;
  5287. if (conn.flags & CONNECT_PERSIST) {
  5288. conn.signal.get_object()->disconnect(conn.signal.get_name(), conn.callable);
  5289. }
  5290. }
  5291. }
  5292. // Store all the paths for any selected nodes which are ancestors of the node we're replacing.
  5293. List<NodePath> selected_node_paths;
  5294. for (Node *selected_node : editor_selection->get_selected_node_list()) {
  5295. if (selected_node == original_node || original_node->is_ancestor_of(selected_node)) {
  5296. selected_node_paths.push_back(original_node->get_path_to(selected_node));
  5297. editor_selection->remove_node(selected_node);
  5298. }
  5299. }
  5300. // Remove all nodes which were added as additional elements (they will be restored later).
  5301. for (AdditiveNodeEntry additive_node_entry : instance_modifications.addition_list) {
  5302. Node *addition_node = additive_node_entry.node;
  5303. addition_node->get_parent()->remove_child(addition_node);
  5304. }
  5305. // Clear ownership of the nodes (kind of hack to workaround an issue with
  5306. // replace_by when called on nodes in other tabs).
  5307. List<Node *> nodes_owned_by_original_node;
  5308. original_node->get_owned_by(original_node, &nodes_owned_by_original_node);
  5309. for (Node *owned_node : nodes_owned_by_original_node) {
  5310. owned_node->set_owner(nullptr);
  5311. }
  5312. // Replace the old nodes in the history with the new ones.
  5313. // Otherwise, the history will contain old nodes, and some could still be
  5314. // instantiated if used elsewhere, causing the "current edited item" to be
  5315. // linked to a node that will be destroyed later. This caused the editor to
  5316. // crash when reimporting scenes with animations when "Editable children" was enabled.
  5317. replace_history_reimported_nodes(original_node, instantiated_node, original_node);
  5318. // Reset the editable instance state.
  5319. HashMap<NodePath, SceneEditorDataEntry> scene_editor_data_table;
  5320. Node *owner = original_node->get_owner();
  5321. if (!owner) {
  5322. owner = original_node;
  5323. }
  5324. get_scene_editor_data_for_node(owner, original_node, scene_editor_data_table);
  5325. bool original_node_scene_instance_load_placeholder = original_node->get_scene_instance_load_placeholder();
  5326. // Delete all the remaining node children.
  5327. while (original_node->get_child_count()) {
  5328. Node *child = original_node->get_child(0);
  5329. original_node->remove_child(child);
  5330. child->queue_free();
  5331. }
  5332. // Update the name to match
  5333. instantiated_node->set_name(original_node->get_name());
  5334. // Is this replacing the edited root node?
  5335. if (current_edited_scene == original_node) {
  5336. // Set the instance as un inherited scene of itself.
  5337. instantiated_node->set_scene_inherited_state(instantiated_node->get_scene_instance_state());
  5338. instantiated_node->set_scene_instance_state(nullptr);
  5339. instantiated_node->set_scene_file_path(original_node_file_path);
  5340. current_edited_scene = instantiated_node;
  5341. editor_data.set_edited_scene_root(current_edited_scene);
  5342. if (original_edited_scene_idx == current_scene_idx) {
  5343. // How that the editor executes a redraw while destroying or progressing the EditorProgress,
  5344. // it crashes when the root scene has been replaced because the edited scene
  5345. // was freed and no longer in the scene tree.
  5346. SceneTreeDock::get_singleton()->set_edited_scene(current_edited_scene);
  5347. if (get_tree()) {
  5348. get_tree()->set_edited_scene_root(current_edited_scene);
  5349. }
  5350. }
  5351. }
  5352. // Replace the original node with the instantiated version.
  5353. original_node->replace_by(instantiated_node, false);
  5354. // Mark the old node for deletion.
  5355. original_node->queue_free();
  5356. // Restore the placeholder state from the original node.
  5357. instantiated_node->set_scene_instance_load_placeholder(original_node_scene_instance_load_placeholder);
  5358. // Attempt to re-add all the additional nodes.
  5359. for (AdditiveNodeEntry additive_node_entry : instance_modifications.addition_list) {
  5360. Node *parent_node = instantiated_node->get_node_or_null(additive_node_entry.parent);
  5361. if (!parent_node) {
  5362. parent_node = current_edited_scene;
  5363. }
  5364. parent_node->add_child(additive_node_entry.node);
  5365. parent_node->move_child(additive_node_entry.node, additive_node_entry.index);
  5366. // If the additive node's owner was the node which got replaced, update it.
  5367. if (additive_node_entry.owner == original_node) {
  5368. additive_node_entry.owner = instantiated_node;
  5369. }
  5370. additive_node_entry.node->set_owner(additive_node_entry.owner);
  5371. // If the parent node was lost, attempt to restore the original global transform.
  5372. {
  5373. Node2D *node_2d = Object::cast_to<Node2D>(additive_node_entry.node);
  5374. if (node_2d) {
  5375. node_2d->set_transform(additive_node_entry.transform_2d);
  5376. }
  5377. Node3D *node_3d = Object::cast_to<Node3D>(additive_node_entry.node);
  5378. if (node_3d) {
  5379. node_3d->set_transform(additive_node_entry.transform_3d);
  5380. }
  5381. }
  5382. }
  5383. // Restore the scene's editable instance and folded states.
  5384. for (HashMap<NodePath, SceneEditorDataEntry>::Iterator I = scene_editor_data_table.begin(); I; ++I) {
  5385. Node *node = owner->get_node_or_null(I->key);
  5386. if (node) {
  5387. if (owner != node) {
  5388. owner->set_editable_instance(node, I->value.is_editable);
  5389. }
  5390. node->set_display_folded(I->value.is_display_folded);
  5391. }
  5392. }
  5393. // Restore the selection.
  5394. if (selected_node_paths.size()) {
  5395. for (NodePath selected_node_path : selected_node_paths) {
  5396. Node *selected_node = instantiated_node->get_node_or_null(selected_node_path);
  5397. if (selected_node) {
  5398. editor_selection->add_node(selected_node);
  5399. }
  5400. }
  5401. editor_selection->update();
  5402. }
  5403. // Attempt to restore the modified properties and signals for the instantitated node and all its owned children.
  5404. for (KeyValue<NodePath, ModificationNodeEntry> &E : instance_modifications.modifications) {
  5405. NodePath new_current_path = E.key;
  5406. Node *modifiable_node = instantiated_node->get_node_or_null(new_current_path);
  5407. update_node_from_node_modification_entry(modifiable_node, E.value);
  5408. }
  5409. // Add the newly instantiated node to the edited scene's replaced node list.
  5410. replaced_nodes.push_back(instantiated_node);
  5411. }
  5412. // Attempt to restore the modified properties and signals for the instantitated node and all its owned children.
  5413. for (KeyValue<NodePath, ModificationNodeEntry> &E : scene_modifications->other_instances_modifications) {
  5414. NodePath new_current_path = E.key;
  5415. Node *modifiable_node = current_edited_scene->get_node_or_null(new_current_path);
  5416. if (modifiable_node) {
  5417. update_node_from_node_modification_entry(modifiable_node, E.value);
  5418. }
  5419. }
  5420. if (is_unsaved) {
  5421. EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(current_history_id);
  5422. }
  5423. // Save the current handled scene state.
  5424. editor_data.save_edited_scene_state(editor_selection, &editor_history, editor_state);
  5425. editor_selection->clear();
  5426. // Cleanup the history of the changes.
  5427. editor_history.cleanup_history();
  5428. if (original_edited_scene_idx != current_scene_idx) {
  5429. scene_root->remove_child(current_edited_scene);
  5430. // Ensure the current edited scene is re-added if removed earlier because it has the same name
  5431. // as the reimported scene. The editor could crash when reloading SceneTreeDock if the current
  5432. // edited scene is not in the scene tree.
  5433. Node *original_edited_scene_root = editor_data.get_edited_scene_root(original_edited_scene_idx);
  5434. if (original_edited_scene_root && !original_edited_scene_root->get_parent()) {
  5435. scene_root->add_child(original_edited_scene_root);
  5436. }
  5437. }
  5438. }
  5439. // For the whole editor, call the _notify_nodes_scene_reimported with a list of replaced nodes.
  5440. // To inform anything that depends on them that they should update as appropriate.
  5441. _notify_nodes_scene_reimported(this, replaced_nodes);
  5442. editor_data.set_edited_scene(original_edited_scene_idx);
  5443. editor_data.restore_edited_scene_state(editor_selection, &editor_history);
  5444. progress.step(TTR("Reloading done."), editor_data.get_edited_scene_count());
  5445. }
  5446. void EditorNode::_remove_all_not_owned_children(Node *p_node, Node *p_owner) {
  5447. Vector<Node *> nodes_to_remove;
  5448. if (p_node != p_owner && p_node->get_owner() != p_owner) {
  5449. nodes_to_remove.push_back(p_node);
  5450. }
  5451. for (int i = 0; i < p_node->get_child_count(); i++) {
  5452. Node *child_node = p_node->get_child(i);
  5453. _remove_all_not_owned_children(child_node, p_owner);
  5454. }
  5455. for (Node *node : nodes_to_remove) {
  5456. node->get_parent()->remove_child(node);
  5457. node->queue_free();
  5458. }
  5459. }
  5460. int EditorNode::plugin_init_callback_count = 0;
  5461. void EditorNode::add_plugin_init_callback(EditorPluginInitializeCallback p_callback) {
  5462. ERR_FAIL_COND(plugin_init_callback_count == MAX_INIT_CALLBACKS);
  5463. plugin_init_callbacks[plugin_init_callback_count++] = p_callback;
  5464. }
  5465. EditorPluginInitializeCallback EditorNode::plugin_init_callbacks[EditorNode::MAX_INIT_CALLBACKS];
  5466. int EditorNode::build_callback_count = 0;
  5467. void EditorNode::add_build_callback(EditorBuildCallback p_callback) {
  5468. ERR_FAIL_COND(build_callback_count == MAX_INIT_CALLBACKS);
  5469. build_callbacks[build_callback_count++] = p_callback;
  5470. }
  5471. EditorBuildCallback EditorNode::build_callbacks[EditorNode::MAX_BUILD_CALLBACKS];
  5472. bool EditorNode::call_build() {
  5473. bool builds_successful = true;
  5474. for (int i = 0; i < build_callback_count && builds_successful; i++) {
  5475. if (!build_callbacks[i]()) {
  5476. ERR_PRINT("A Godot Engine build callback failed.");
  5477. builds_successful = false;
  5478. }
  5479. }
  5480. if (builds_successful && !editor_data.call_build()) {
  5481. ERR_PRINT("An EditorPlugin build callback failed.");
  5482. builds_successful = false;
  5483. }
  5484. return builds_successful;
  5485. }
  5486. void EditorNode::_inherit_imported(const String &p_action) {
  5487. open_imported->hide();
  5488. load_scene(open_import_request, true, true);
  5489. }
  5490. void EditorNode::_open_imported() {
  5491. load_scene(open_import_request, true, false, true);
  5492. }
  5493. void EditorNode::dim_editor(bool p_dimming) {
  5494. dimmed = p_dimming;
  5495. gui_base->set_modulate(p_dimming ? Color(0.5, 0.5, 0.5) : Color(1, 1, 1));
  5496. }
  5497. bool EditorNode::is_editor_dimmed() const {
  5498. return dimmed;
  5499. }
  5500. void EditorNode::open_export_template_manager() {
  5501. export_template_manager->popup_manager();
  5502. }
  5503. void EditorNode::add_resource_conversion_plugin(const Ref<EditorResourceConversionPlugin> &p_plugin) {
  5504. resource_conversion_plugins.push_back(p_plugin);
  5505. }
  5506. void EditorNode::remove_resource_conversion_plugin(const Ref<EditorResourceConversionPlugin> &p_plugin) {
  5507. resource_conversion_plugins.erase(p_plugin);
  5508. }
  5509. Vector<Ref<EditorResourceConversionPlugin>> EditorNode::find_resource_conversion_plugin_for_resource(const Ref<Resource> &p_for_resource) {
  5510. if (p_for_resource.is_null()) {
  5511. return Vector<Ref<EditorResourceConversionPlugin>>();
  5512. }
  5513. Vector<Ref<EditorResourceConversionPlugin>> ret;
  5514. for (Ref<EditorResourceConversionPlugin> resource_conversion_plugin : resource_conversion_plugins) {
  5515. if (resource_conversion_plugin.is_valid() && resource_conversion_plugin->handles(p_for_resource)) {
  5516. ret.push_back(resource_conversion_plugin);
  5517. }
  5518. }
  5519. return ret;
  5520. }
  5521. Vector<Ref<EditorResourceConversionPlugin>> EditorNode::find_resource_conversion_plugin_for_type_name(const String &p_type) {
  5522. Vector<Ref<EditorResourceConversionPlugin>> ret;
  5523. if (ClassDB::can_instantiate(p_type)) {
  5524. Ref<Resource> temp = Object::cast_to<Resource>(ClassDB::instantiate(p_type));
  5525. if (temp.is_valid()) {
  5526. for (Ref<EditorResourceConversionPlugin> resource_conversion_plugin : resource_conversion_plugins) {
  5527. if (resource_conversion_plugin.is_valid() && resource_conversion_plugin->handles(temp)) {
  5528. ret.push_back(resource_conversion_plugin);
  5529. }
  5530. }
  5531. }
  5532. }
  5533. return ret;
  5534. }
  5535. void EditorNode::_update_renderer_color() {
  5536. String rendering_method = renderer->get_selected_metadata();
  5537. if (rendering_method == "forward_plus") {
  5538. renderer->add_theme_color_override(SceneStringName(font_color), theme->get_color(SNAME("forward_plus_color"), EditorStringName(Editor)));
  5539. } else if (rendering_method == "mobile") {
  5540. renderer->add_theme_color_override(SceneStringName(font_color), theme->get_color(SNAME("mobile_color"), EditorStringName(Editor)));
  5541. } else if (rendering_method == "gl_compatibility") {
  5542. renderer->add_theme_color_override(SceneStringName(font_color), theme->get_color(SNAME("gl_compatibility_color"), EditorStringName(Editor)));
  5543. }
  5544. }
  5545. void EditorNode::_renderer_selected(int p_which) {
  5546. String rendering_method = renderer->get_item_metadata(p_which);
  5547. String current_renderer = GLOBAL_GET("rendering/renderer/rendering_method");
  5548. if (rendering_method == current_renderer) {
  5549. return;
  5550. }
  5551. renderer_request = rendering_method;
  5552. video_restart_dialog->set_text(
  5553. vformat(TTR("Changing the renderer requires restarting the editor.\n\nChoosing Save & Restart will change the rendering method to:\n- Desktop platforms: %s\n- Mobile platforms: %s\n- Web platform: gl_compatibility"),
  5554. renderer_request, renderer_request.replace("forward_plus", "mobile")));
  5555. video_restart_dialog->popup_centered();
  5556. renderer->select(renderer_current);
  5557. _update_renderer_color();
  5558. }
  5559. void EditorNode::_add_renderer_entry(const String &p_renderer_name, bool p_mark_overridden) {
  5560. String item_text;
  5561. if (p_renderer_name == "forward_plus") {
  5562. item_text = TTR("Forward+");
  5563. }
  5564. if (p_renderer_name == "mobile") {
  5565. item_text = TTR("Mobile");
  5566. }
  5567. if (p_renderer_name == "gl_compatibility") {
  5568. item_text = TTR("Compatibility");
  5569. }
  5570. if (p_mark_overridden) {
  5571. item_text += " " + TTR("(Overridden)");
  5572. }
  5573. renderer->add_item(item_text);
  5574. }
  5575. void EditorNode::_resource_saved(Ref<Resource> p_resource, const String &p_path) {
  5576. if (singleton->saving_resources_in_path.has(p_resource)) {
  5577. // This is going to be handled by save_resource_in_path when the time is right.
  5578. return;
  5579. }
  5580. if (EditorFileSystem::get_singleton()) {
  5581. EditorFileSystem::get_singleton()->update_file(p_path);
  5582. }
  5583. singleton->editor_folding.save_resource_folding(p_resource, p_path);
  5584. }
  5585. void EditorNode::_resource_loaded(Ref<Resource> p_resource, const String &p_path) {
  5586. singleton->editor_folding.load_resource_folding(p_resource, p_path);
  5587. }
  5588. void EditorNode::_feature_profile_changed() {
  5589. Ref<EditorFeatureProfile> profile = feature_profile_manager->get_current_profile();
  5590. if (profile.is_valid()) {
  5591. editor_dock_manager->set_dock_enabled(NodeDock::get_singleton(), !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_NODE_DOCK));
  5592. // The Import dock is useless without the FileSystem dock. Ensure the configuration is valid.
  5593. bool fs_dock_disabled = profile->is_feature_disabled(EditorFeatureProfile::FEATURE_FILESYSTEM_DOCK);
  5594. editor_dock_manager->set_dock_enabled(FileSystemDock::get_singleton(), !fs_dock_disabled);
  5595. editor_dock_manager->set_dock_enabled(ImportDock::get_singleton(), !fs_dock_disabled && !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_IMPORT_DOCK));
  5596. editor_dock_manager->set_dock_enabled(history_dock, !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_HISTORY_DOCK));
  5597. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_3D, !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_3D));
  5598. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_SCRIPT, !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_SCRIPT));
  5599. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_GAME, !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_GAME));
  5600. if (AssetLibraryEditorPlugin::is_available()) {
  5601. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_ASSETLIB, !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_ASSET_LIB));
  5602. }
  5603. } else {
  5604. editor_dock_manager->set_dock_enabled(ImportDock::get_singleton(), true);
  5605. editor_dock_manager->set_dock_enabled(NodeDock::get_singleton(), true);
  5606. editor_dock_manager->set_dock_enabled(FileSystemDock::get_singleton(), true);
  5607. editor_dock_manager->set_dock_enabled(history_dock, true);
  5608. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_3D, true);
  5609. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_SCRIPT, true);
  5610. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_GAME, true);
  5611. if (AssetLibraryEditorPlugin::is_available()) {
  5612. editor_main_screen->set_button_enabled(EditorMainScreen::EDITOR_ASSETLIB, true);
  5613. }
  5614. }
  5615. }
  5616. void EditorNode::_bind_methods() {
  5617. ClassDB::bind_method(D_METHOD("push_item", "object", "property", "inspector_only"), &EditorNode::push_item, DEFVAL(""), DEFVAL(false));
  5618. ClassDB::bind_method("set_edited_scene", &EditorNode::set_edited_scene);
  5619. ClassDB::bind_method("stop_child_process", &EditorNode::stop_child_process);
  5620. ADD_SIGNAL(MethodInfo("request_help_search"));
  5621. ADD_SIGNAL(MethodInfo("script_add_function_request", PropertyInfo(Variant::OBJECT, "obj"), PropertyInfo(Variant::STRING, "function"), PropertyInfo(Variant::PACKED_STRING_ARRAY, "args")));
  5622. ADD_SIGNAL(MethodInfo("resource_saved", PropertyInfo(Variant::OBJECT, "obj")));
  5623. ADD_SIGNAL(MethodInfo("scene_saved", PropertyInfo(Variant::STRING, "path")));
  5624. ADD_SIGNAL(MethodInfo("scene_changed"));
  5625. ADD_SIGNAL(MethodInfo("scene_closed", PropertyInfo(Variant::STRING, "path")));
  5626. }
  5627. static Node *_resource_get_edited_scene() {
  5628. return EditorNode::get_singleton()->get_edited_scene();
  5629. }
  5630. void EditorNode::_print_handler(void *p_this, const String &p_string, bool p_error, bool p_rich) {
  5631. callable_mp_static(&EditorNode::_print_handler_impl).call_deferred(p_string, p_error, p_rich);
  5632. }
  5633. void EditorNode::_print_handler_impl(const String &p_string, bool p_error, bool p_rich) {
  5634. if (!singleton) {
  5635. return;
  5636. }
  5637. if (p_error) {
  5638. singleton->log->add_message(p_string, EditorLog::MSG_TYPE_ERROR);
  5639. } else if (p_rich) {
  5640. singleton->log->add_message(p_string, EditorLog::MSG_TYPE_STD_RICH);
  5641. } else {
  5642. singleton->log->add_message(p_string, EditorLog::MSG_TYPE_STD);
  5643. }
  5644. }
  5645. static void _execute_thread(void *p_ud) {
  5646. EditorNode::ExecuteThreadArgs *eta = (EditorNode::ExecuteThreadArgs *)p_ud;
  5647. Error err = OS::get_singleton()->execute(eta->path, eta->args, &eta->output, &eta->exitcode, true, &eta->execute_output_mutex);
  5648. print_verbose("Thread exit status: " + itos(eta->exitcode));
  5649. if (err != OK) {
  5650. eta->exitcode = err;
  5651. }
  5652. eta->done.set();
  5653. }
  5654. int EditorNode::execute_and_show_output(const String &p_title, const String &p_path, const List<String> &p_arguments, bool p_close_on_ok, bool p_close_on_errors, String *r_output) {
  5655. if (execute_output_dialog) {
  5656. execute_output_dialog->set_title(p_title);
  5657. execute_output_dialog->get_ok_button()->set_disabled(true);
  5658. execute_outputs->clear();
  5659. execute_outputs->set_scroll_follow(true);
  5660. EditorInterface::get_singleton()->popup_dialog_centered_ratio(execute_output_dialog);
  5661. }
  5662. ExecuteThreadArgs eta;
  5663. eta.path = p_path;
  5664. eta.args = p_arguments;
  5665. eta.exitcode = 255;
  5666. int prev_len = 0;
  5667. eta.execute_output_thread.start(_execute_thread, &eta);
  5668. while (!eta.done.is_set()) {
  5669. {
  5670. MutexLock lock(eta.execute_output_mutex);
  5671. if (prev_len != eta.output.length()) {
  5672. String to_add = eta.output.substr(prev_len, eta.output.length());
  5673. prev_len = eta.output.length();
  5674. execute_outputs->add_text(to_add);
  5675. DisplayServer::get_singleton()->process_events(); // Get rid of pending events.
  5676. Main::iteration();
  5677. }
  5678. }
  5679. OS::get_singleton()->delay_usec(1000);
  5680. }
  5681. eta.execute_output_thread.wait_to_finish();
  5682. execute_outputs->add_text("\nExit Code: " + itos(eta.exitcode));
  5683. if (execute_output_dialog) {
  5684. if (p_close_on_errors && eta.exitcode != 0) {
  5685. execute_output_dialog->hide();
  5686. }
  5687. if (p_close_on_ok && eta.exitcode == 0) {
  5688. execute_output_dialog->hide();
  5689. }
  5690. execute_output_dialog->get_ok_button()->set_disabled(false);
  5691. }
  5692. if (r_output) {
  5693. *r_output = eta.output;
  5694. }
  5695. return eta.exitcode;
  5696. }
  5697. void EditorNode::set_unfocused_low_processor_usage_mode_enabled(bool p_enabled) {
  5698. unfocused_low_processor_usage_mode_enabled = p_enabled;
  5699. }
  5700. EditorNode::EditorNode() {
  5701. DEV_ASSERT(!singleton);
  5702. singleton = this;
  5703. set_translation_domain("godot.editor");
  5704. Resource::_get_local_scene_func = _resource_get_edited_scene;
  5705. {
  5706. PortableCompressedTexture2D::set_keep_all_compressed_buffers(true);
  5707. RenderingServer::get_singleton()->set_debug_generate_wireframes(true);
  5708. AudioServer::get_singleton()->set_enable_tagging_used_audio_streams(true);
  5709. // No navigation by default if in editor.
  5710. if (NavigationServer3D::get_singleton()->get_debug_enabled()) {
  5711. NavigationServer3D::get_singleton()->set_active(true);
  5712. } else {
  5713. NavigationServer3D::get_singleton()->set_active(false);
  5714. }
  5715. // No physics by default if in editor.
  5716. PhysicsServer3D::get_singleton()->set_active(false);
  5717. PhysicsServer2D::get_singleton()->set_active(false);
  5718. // No scripting by default if in editor (except for tool).
  5719. ScriptServer::set_scripting_enabled(false);
  5720. if (!DisplayServer::get_singleton()->is_touchscreen_available()) {
  5721. // Only if no touchscreen ui hint, disable emulation just in case.
  5722. Input::get_singleton()->set_emulate_touch_from_mouse(false);
  5723. }
  5724. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_CUSTOM_CURSOR_SHAPE)) {
  5725. DisplayServer::get_singleton()->cursor_set_custom_image(Ref<Resource>());
  5726. }
  5727. }
  5728. SceneState::set_disable_placeholders(true);
  5729. ResourceLoader::clear_translation_remaps(); // Using no remaps if in editor.
  5730. ResourceLoader::clear_path_remaps();
  5731. ResourceLoader::set_create_missing_resources_if_class_unavailable(true);
  5732. EditorPropertyNameProcessor *epnp = memnew(EditorPropertyNameProcessor);
  5733. add_child(epnp);
  5734. EditorUndoRedoManager::get_singleton()->connect("version_changed", callable_mp(this, &EditorNode::_update_undo_redo_allowed));
  5735. EditorUndoRedoManager::get_singleton()->connect("history_changed", callable_mp(this, &EditorNode::_update_undo_redo_allowed));
  5736. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &EditorNode::_update_from_settings));
  5737. GDExtensionManager::get_singleton()->connect("extensions_reloaded", callable_mp(this, &EditorNode::_gdextensions_reloaded));
  5738. TranslationServer::get_singleton()->set_enabled(false);
  5739. // Load settings.
  5740. if (!EditorSettings::get_singleton()) {
  5741. EditorSettings::create();
  5742. }
  5743. ED_SHORTCUT("editor/lock_selected_nodes", TTRC("Lock Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | Key::L);
  5744. ED_SHORTCUT("editor/unlock_selected_nodes", TTRC("Unlock Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::L);
  5745. ED_SHORTCUT("editor/group_selected_nodes", TTRC("Group Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | Key::G);
  5746. ED_SHORTCUT("editor/ungroup_selected_nodes", TTRC("Ungroup Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::G);
  5747. FileAccess::set_backup_save(EDITOR_GET("filesystem/on_save/safe_save_on_backup_then_rename"));
  5748. _update_vsync_mode();
  5749. // Warm up the surface upgrade tool as early as possible.
  5750. surface_upgrade_tool = memnew(SurfaceUpgradeTool);
  5751. run_surface_upgrade_tool = EditorSettings::get_singleton()->get_project_metadata("surface_upgrade_tool", "run_on_restart", false);
  5752. if (run_surface_upgrade_tool) {
  5753. SurfaceUpgradeTool::get_singleton()->begin_upgrade();
  5754. }
  5755. {
  5756. bool agile_input_event_flushing = EDITOR_GET("input/buffering/agile_event_flushing");
  5757. bool use_accumulated_input = EDITOR_GET("input/buffering/use_accumulated_input");
  5758. Input::get_singleton()->set_agile_input_event_flushing(agile_input_event_flushing);
  5759. Input::get_singleton()->set_use_accumulated_input(use_accumulated_input);
  5760. }
  5761. {
  5762. int display_scale = EDITOR_GET("interface/editor/display_scale");
  5763. switch (display_scale) {
  5764. case 0:
  5765. // Try applying a suitable display scale automatically.
  5766. EditorScale::set_scale(EditorSettings::get_singleton()->get_auto_display_scale());
  5767. break;
  5768. case 1:
  5769. EditorScale::set_scale(0.75);
  5770. break;
  5771. case 2:
  5772. EditorScale::set_scale(1.0);
  5773. break;
  5774. case 3:
  5775. EditorScale::set_scale(1.25);
  5776. break;
  5777. case 4:
  5778. EditorScale::set_scale(1.5);
  5779. break;
  5780. case 5:
  5781. EditorScale::set_scale(1.75);
  5782. break;
  5783. case 6:
  5784. EditorScale::set_scale(2.0);
  5785. break;
  5786. default:
  5787. EditorScale::set_scale(EDITOR_GET("interface/editor/custom_display_scale"));
  5788. break;
  5789. }
  5790. }
  5791. // Define a minimum window size to prevent UI elements from overlapping or being cut off.
  5792. Window *w = Object::cast_to<Window>(SceneTree::get_singleton()->get_root());
  5793. if (w) {
  5794. const Size2 minimum_size = Size2(1024, 600) * EDSCALE;
  5795. w->set_min_size(minimum_size); // Calling it this early doesn't sync the property with DS.
  5796. DisplayServer::get_singleton()->window_set_min_size(minimum_size);
  5797. }
  5798. EditorFileDialog::set_default_show_hidden_files(EDITOR_GET("filesystem/file_dialog/show_hidden_files"));
  5799. EditorFileDialog::set_default_display_mode((EditorFileDialog::DisplayMode)EDITOR_GET("filesystem/file_dialog/display_mode").operator int());
  5800. int swap_cancel_ok = EDITOR_GET("interface/editor/accept_dialog_cancel_ok_buttons");
  5801. if (swap_cancel_ok != 0) { // 0 is auto, set in register_scene based on DisplayServer.
  5802. // Swap on means OK first.
  5803. AcceptDialog::set_swap_cancel_ok(swap_cancel_ok == 2);
  5804. }
  5805. int ed_root_dir = EDITOR_GET("interface/editor/ui_layout_direction");
  5806. Control::set_root_layout_direction(ed_root_dir);
  5807. Window::set_root_layout_direction(ed_root_dir);
  5808. ResourceLoader::set_abort_on_missing_resources(false);
  5809. ResourceLoader::set_error_notify_func(&EditorNode::add_io_error);
  5810. ResourceLoader::set_dependency_error_notify_func(&EditorNode::_dependency_error_report);
  5811. SceneState::set_instantiation_warning_notify_func([](const String &p_warning) {
  5812. add_io_warning(p_warning);
  5813. callable_mp(EditorInterface::get_singleton(), &EditorInterface::mark_scene_as_unsaved).call_deferred();
  5814. });
  5815. {
  5816. // Register importers at the beginning, so dialogs are created with the right extensions.
  5817. Ref<ResourceImporterTexture> import_texture = memnew(ResourceImporterTexture(true));
  5818. ResourceFormatImporter::get_singleton()->add_importer(import_texture);
  5819. Ref<ResourceImporterLayeredTexture> import_cubemap;
  5820. import_cubemap.instantiate();
  5821. import_cubemap->set_mode(ResourceImporterLayeredTexture::MODE_CUBEMAP);
  5822. ResourceFormatImporter::get_singleton()->add_importer(import_cubemap);
  5823. Ref<ResourceImporterLayeredTexture> import_array;
  5824. import_array.instantiate();
  5825. import_array->set_mode(ResourceImporterLayeredTexture::MODE_2D_ARRAY);
  5826. ResourceFormatImporter::get_singleton()->add_importer(import_array);
  5827. Ref<ResourceImporterLayeredTexture> import_cubemap_array;
  5828. import_cubemap_array.instantiate();
  5829. import_cubemap_array->set_mode(ResourceImporterLayeredTexture::MODE_CUBEMAP_ARRAY);
  5830. ResourceFormatImporter::get_singleton()->add_importer(import_cubemap_array);
  5831. Ref<ResourceImporterLayeredTexture> import_3d = memnew(ResourceImporterLayeredTexture(true));
  5832. import_3d->set_mode(ResourceImporterLayeredTexture::MODE_3D);
  5833. ResourceFormatImporter::get_singleton()->add_importer(import_3d);
  5834. Ref<ResourceImporterImage> import_image;
  5835. import_image.instantiate();
  5836. ResourceFormatImporter::get_singleton()->add_importer(import_image);
  5837. Ref<ResourceImporterTextureAtlas> import_texture_atlas;
  5838. import_texture_atlas.instantiate();
  5839. ResourceFormatImporter::get_singleton()->add_importer(import_texture_atlas);
  5840. Ref<ResourceImporterDynamicFont> import_font_data_dynamic;
  5841. import_font_data_dynamic.instantiate();
  5842. ResourceFormatImporter::get_singleton()->add_importer(import_font_data_dynamic);
  5843. Ref<ResourceImporterBMFont> import_font_data_bmfont;
  5844. import_font_data_bmfont.instantiate();
  5845. ResourceFormatImporter::get_singleton()->add_importer(import_font_data_bmfont);
  5846. Ref<ResourceImporterImageFont> import_font_data_image;
  5847. import_font_data_image.instantiate();
  5848. ResourceFormatImporter::get_singleton()->add_importer(import_font_data_image);
  5849. Ref<ResourceImporterCSVTranslation> import_csv_translation;
  5850. import_csv_translation.instantiate();
  5851. ResourceFormatImporter::get_singleton()->add_importer(import_csv_translation);
  5852. Ref<ResourceImporterWAV> import_wav;
  5853. import_wav.instantiate();
  5854. ResourceFormatImporter::get_singleton()->add_importer(import_wav);
  5855. Ref<ResourceImporterOBJ> import_obj;
  5856. import_obj.instantiate();
  5857. ResourceFormatImporter::get_singleton()->add_importer(import_obj);
  5858. Ref<ResourceImporterShaderFile> import_shader_file;
  5859. import_shader_file.instantiate();
  5860. ResourceFormatImporter::get_singleton()->add_importer(import_shader_file);
  5861. Ref<ResourceImporterScene> import_scene = memnew(ResourceImporterScene("PackedScene", true));
  5862. ResourceFormatImporter::get_singleton()->add_importer(import_scene);
  5863. Ref<ResourceImporterScene> import_animation = memnew(ResourceImporterScene("AnimationLibrary", true));
  5864. ResourceFormatImporter::get_singleton()->add_importer(import_animation);
  5865. {
  5866. Ref<EditorSceneFormatImporterCollada> import_collada;
  5867. import_collada.instantiate();
  5868. ResourceImporterScene::add_scene_importer(import_collada);
  5869. Ref<EditorOBJImporter> import_obj2;
  5870. import_obj2.instantiate();
  5871. ResourceImporterScene::add_scene_importer(import_obj2);
  5872. Ref<EditorSceneFormatImporterESCN> import_escn;
  5873. import_escn.instantiate();
  5874. ResourceImporterScene::add_scene_importer(import_escn);
  5875. }
  5876. Ref<ResourceImporterBitMap> import_bitmap;
  5877. import_bitmap.instantiate();
  5878. ResourceFormatImporter::get_singleton()->add_importer(import_bitmap);
  5879. }
  5880. {
  5881. Ref<EditorInspectorDefaultPlugin> eidp;
  5882. eidp.instantiate();
  5883. EditorInspector::add_inspector_plugin(eidp);
  5884. Ref<EditorInspectorRootMotionPlugin> rmp;
  5885. rmp.instantiate();
  5886. EditorInspector::add_inspector_plugin(rmp);
  5887. Ref<EditorInspectorVisualShaderModePlugin> smp;
  5888. smp.instantiate();
  5889. EditorInspector::add_inspector_plugin(smp);
  5890. Ref<EditorInspectorParticleProcessMaterialPlugin> ppm;
  5891. ppm.instantiate();
  5892. EditorInspector::add_inspector_plugin(ppm);
  5893. }
  5894. editor_selection = memnew(EditorSelection);
  5895. EditorFileSystem *efs = memnew(EditorFileSystem);
  5896. add_child(efs);
  5897. EditorContextMenuPluginManager::create();
  5898. // Used for previews.
  5899. FileDialog::get_icon_func = _file_dialog_get_icon;
  5900. FileDialog::register_func = _file_dialog_register;
  5901. FileDialog::unregister_func = _file_dialog_unregister;
  5902. EditorFileDialog::get_icon_func = _file_dialog_get_icon;
  5903. EditorFileDialog::register_func = _editor_file_dialog_register;
  5904. EditorFileDialog::unregister_func = _editor_file_dialog_unregister;
  5905. editor_export = memnew(EditorExport);
  5906. add_child(editor_export);
  5907. // Exporters might need the theme.
  5908. EditorThemeManager::initialize();
  5909. theme = EditorThemeManager::generate_theme();
  5910. DisplayServer::set_early_window_clear_color_override(true, theme->get_color(SNAME("background"), EditorStringName(Editor)));
  5911. register_exporters();
  5912. ED_SHORTCUT("canvas_item_editor/pan_view", TTRC("Pan View"), Key::SPACE);
  5913. const Vector<String> textfile_ext = ((String)(EDITOR_GET("docks/filesystem/textfile_extensions"))).split(",", false);
  5914. for (const String &E : textfile_ext) {
  5915. textfile_extensions.insert(E);
  5916. }
  5917. const Vector<String> other_file_ext = ((String)(EDITOR_GET("docks/filesystem/other_file_extensions"))).split(",", false);
  5918. for (const String &E : other_file_ext) {
  5919. other_file_extensions.insert(E);
  5920. }
  5921. resource_preview = memnew(EditorResourcePreview);
  5922. add_child(resource_preview);
  5923. progress_dialog = memnew(ProgressDialog);
  5924. progress_dialog->set_unparent_when_invisible(true);
  5925. progress_dialog->connect(SceneStringName(visibility_changed), callable_mp(this, &EditorNode::_progress_dialog_visibility_changed));
  5926. gui_base = memnew(Panel);
  5927. add_child(gui_base);
  5928. // Take up all screen.
  5929. gui_base->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  5930. gui_base->set_anchor(SIDE_RIGHT, Control::ANCHOR_END);
  5931. gui_base->set_anchor(SIDE_BOTTOM, Control::ANCHOR_END);
  5932. gui_base->set_end(Point2(0, 0));
  5933. main_vbox = memnew(VBoxContainer);
  5934. gui_base->add_child(main_vbox);
  5935. title_bar = memnew(EditorTitleBar);
  5936. main_vbox->add_child(title_bar);
  5937. left_l_hsplit = memnew(DockSplitContainer);
  5938. left_l_hsplit->set_name("DockHSplitLeftL");
  5939. main_vbox->add_child(left_l_hsplit);
  5940. left_l_hsplit->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  5941. left_l_vsplit = memnew(DockSplitContainer);
  5942. left_l_vsplit->set_name("DockVSplitLeftL");
  5943. left_l_vsplit->set_vertical(true);
  5944. left_l_hsplit->add_child(left_l_vsplit);
  5945. TabContainer *dock_slot[EditorDockManager::DOCK_SLOT_MAX];
  5946. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_UL] = memnew(TabContainer);
  5947. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_UL]->set_name("DockSlotLeftUL");
  5948. left_l_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_LEFT_UL]);
  5949. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_BL] = memnew(TabContainer);
  5950. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_BL]->set_name("DockSlotLeftBL");
  5951. left_l_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_LEFT_BL]);
  5952. left_r_hsplit = memnew(DockSplitContainer);
  5953. left_r_hsplit->set_name("DockHSplitLeftR");
  5954. left_l_hsplit->add_child(left_r_hsplit);
  5955. left_r_vsplit = memnew(DockSplitContainer);
  5956. left_r_vsplit->set_name("DockVSplitLeftR");
  5957. left_r_vsplit->set_vertical(true);
  5958. left_r_hsplit->add_child(left_r_vsplit);
  5959. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_UR] = memnew(TabContainer);
  5960. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_UR]->set_name("DockSlotLeftUR");
  5961. left_r_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_LEFT_UR]);
  5962. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_BR] = memnew(TabContainer);
  5963. dock_slot[EditorDockManager::DOCK_SLOT_LEFT_BR]->set_name("DockSlotLeftBR");
  5964. left_r_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_LEFT_BR]);
  5965. main_hsplit = memnew(DockSplitContainer);
  5966. main_hsplit->set_name("DockHSplitMain");
  5967. left_r_hsplit->add_child(main_hsplit);
  5968. VBoxContainer *center_vb = memnew(VBoxContainer);
  5969. main_hsplit->add_child(center_vb);
  5970. center_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  5971. center_split = memnew(DockSplitContainer);
  5972. center_split->set_name("DockVSplitCenter");
  5973. center_split->set_vertical(true);
  5974. center_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  5975. center_split->set_collapsed(false);
  5976. center_vb->add_child(center_split);
  5977. right_hsplit = memnew(DockSplitContainer);
  5978. right_hsplit->set_name("DockHSplitRight");
  5979. main_hsplit->add_child(right_hsplit);
  5980. right_l_vsplit = memnew(DockSplitContainer);
  5981. right_l_vsplit->set_name("DockVSplitRightL");
  5982. right_l_vsplit->set_vertical(true);
  5983. right_hsplit->add_child(right_l_vsplit);
  5984. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_UL] = memnew(TabContainer);
  5985. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_UL]->set_name("DockSlotRightUL");
  5986. right_l_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_UL]);
  5987. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_BL] = memnew(TabContainer);
  5988. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_BL]->set_name("DockSlotRightBL");
  5989. right_l_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_BL]);
  5990. right_r_vsplit = memnew(DockSplitContainer);
  5991. right_r_vsplit->set_name("DockVSplitRightR");
  5992. right_r_vsplit->set_vertical(true);
  5993. right_hsplit->add_child(right_r_vsplit);
  5994. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_UR] = memnew(TabContainer);
  5995. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_UR]->set_name("DockSlotRightUR");
  5996. right_r_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_UR]);
  5997. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_BR] = memnew(TabContainer);
  5998. dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_BR]->set_name("DockSlotRightBR");
  5999. right_r_vsplit->add_child(dock_slot[EditorDockManager::DOCK_SLOT_RIGHT_BR]);
  6000. editor_dock_manager = memnew(EditorDockManager);
  6001. // Save the splits for easier access.
  6002. editor_dock_manager->add_vsplit(left_l_vsplit);
  6003. editor_dock_manager->add_vsplit(left_r_vsplit);
  6004. editor_dock_manager->add_vsplit(right_l_vsplit);
  6005. editor_dock_manager->add_vsplit(right_r_vsplit);
  6006. editor_dock_manager->add_hsplit(left_l_hsplit);
  6007. editor_dock_manager->add_hsplit(left_r_hsplit);
  6008. editor_dock_manager->add_hsplit(main_hsplit);
  6009. editor_dock_manager->add_hsplit(right_hsplit);
  6010. for (int i = 0; i < EditorDockManager::DOCK_SLOT_MAX; i++) {
  6011. editor_dock_manager->register_dock_slot((EditorDockManager::DockSlot)i, dock_slot[i]);
  6012. }
  6013. editor_layout_save_delay_timer = memnew(Timer);
  6014. add_child(editor_layout_save_delay_timer);
  6015. editor_layout_save_delay_timer->set_wait_time(0.5);
  6016. editor_layout_save_delay_timer->set_one_shot(true);
  6017. editor_layout_save_delay_timer->connect("timeout", callable_mp(this, &EditorNode::_save_editor_layout));
  6018. scan_changes_timer = memnew(Timer);
  6019. scan_changes_timer->set_wait_time(0.5);
  6020. scan_changes_timer->set_autostart(EDITOR_GET("interface/editor/import_resources_when_unfocused"));
  6021. scan_changes_timer->connect("timeout", callable_mp(EditorFileSystem::get_singleton(), &EditorFileSystem::scan_changes));
  6022. add_child(scan_changes_timer);
  6023. top_split = memnew(VSplitContainer);
  6024. center_split->add_child(top_split);
  6025. top_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  6026. top_split->set_collapsed(true);
  6027. VBoxContainer *srt = memnew(VBoxContainer);
  6028. srt->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  6029. srt->add_theme_constant_override("separation", 0);
  6030. top_split->add_child(srt);
  6031. scene_tabs = memnew(EditorSceneTabs);
  6032. srt->add_child(scene_tabs);
  6033. scene_tabs->connect("tab_changed", callable_mp(this, &EditorNode::_set_current_scene));
  6034. scene_tabs->connect("tab_closed", callable_mp(this, &EditorNode::_scene_tab_closed));
  6035. distraction_free = memnew(Button);
  6036. distraction_free->set_theme_type_variation("FlatMenuButton");
  6037. ED_SHORTCUT_AND_COMMAND("editor/distraction_free_mode", TTRC("Distraction Free Mode"), KeyModifierMask::CTRL | KeyModifierMask::SHIFT | Key::F11);
  6038. ED_SHORTCUT_OVERRIDE("editor/distraction_free_mode", "macos", KeyModifierMask::META | KeyModifierMask::SHIFT | Key::D);
  6039. ED_SHORTCUT_AND_COMMAND("editor/toggle_last_opened_bottom_panel", TTRC("Toggle Last Opened Bottom Panel"), KeyModifierMask::CMD_OR_CTRL | Key::J);
  6040. distraction_free->set_shortcut(ED_GET_SHORTCUT("editor/distraction_free_mode"));
  6041. distraction_free->set_tooltip_text(TTRC("Toggle distraction-free mode."));
  6042. distraction_free->set_toggle_mode(true);
  6043. scene_tabs->add_extra_button(distraction_free);
  6044. distraction_free->connect(SceneStringName(pressed), callable_mp(this, &EditorNode::_toggle_distraction_free_mode));
  6045. editor_main_screen = memnew(EditorMainScreen);
  6046. editor_main_screen->set_custom_minimum_size(Size2(0, 80) * EDSCALE);
  6047. editor_main_screen->set_draw_behind_parent(true);
  6048. srt->add_child(editor_main_screen);
  6049. editor_main_screen->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  6050. scene_root = memnew(SubViewport);
  6051. scene_root->set_embedding_subwindows(true);
  6052. scene_root->set_disable_3d(true);
  6053. scene_root->set_disable_input(true);
  6054. scene_root->set_as_audio_listener_2d(true);
  6055. bool global_menu = !bool(EDITOR_GET("interface/editor/use_embedded_menu")) && NativeMenu::get_singleton()->has_feature(NativeMenu::FEATURE_GLOBAL_MENU);
  6056. bool can_expand = bool(EDITOR_GET("interface/editor/expand_to_title")) && DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_EXTEND_TO_TITLE);
  6057. if (can_expand) {
  6058. // Add spacer to avoid other controls under window minimize/maximize/close buttons (left side).
  6059. left_menu_spacer = memnew(Control);
  6060. left_menu_spacer->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  6061. title_bar->add_child(left_menu_spacer);
  6062. }
  6063. main_menu = memnew(MenuBar);
  6064. main_menu->set_mouse_filter(Control::MOUSE_FILTER_STOP);
  6065. title_bar->add_child(main_menu);
  6066. main_menu->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
  6067. main_menu->set_theme_type_variation("MainMenuBar");
  6068. main_menu->set_start_index(0); // Main menu, add to the start of global menu.
  6069. main_menu->set_prefer_global_menu(global_menu);
  6070. main_menu->set_switch_on_hover(true);
  6071. file_menu = memnew(PopupMenu);
  6072. file_menu->set_name(TTR("Scene"));
  6073. main_menu->add_child(file_menu);
  6074. main_menu->set_menu_tooltip(0, TTR("Operations with scene files."));
  6075. accept = memnew(AcceptDialog);
  6076. accept->set_autowrap(true);
  6077. accept->set_min_size(Vector2i(600, 0));
  6078. accept->set_unparent_when_invisible(true);
  6079. save_accept = memnew(AcceptDialog);
  6080. save_accept->set_unparent_when_invisible(true);
  6081. save_accept->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind((int)MenuOptions::FILE_SAVE_AS_SCENE));
  6082. project_export = memnew(ProjectExportDialog);
  6083. gui_base->add_child(project_export);
  6084. dependency_error = memnew(DependencyErrorDialog);
  6085. gui_base->add_child(dependency_error);
  6086. dependency_fixer = memnew(DependencyEditor);
  6087. gui_base->add_child(dependency_fixer);
  6088. editor_settings_dialog = memnew(EditorSettingsDialog);
  6089. gui_base->add_child(editor_settings_dialog);
  6090. project_settings_editor = memnew(ProjectSettingsEditor(&editor_data));
  6091. gui_base->add_child(project_settings_editor);
  6092. scene_import_settings = memnew(SceneImportSettingsDialog);
  6093. gui_base->add_child(scene_import_settings);
  6094. audio_stream_import_settings = memnew(AudioStreamImportSettingsDialog);
  6095. gui_base->add_child(audio_stream_import_settings);
  6096. fontdata_import_settings = memnew(DynamicFontImportSettingsDialog);
  6097. gui_base->add_child(fontdata_import_settings);
  6098. export_template_manager = memnew(ExportTemplateManager);
  6099. gui_base->add_child(export_template_manager);
  6100. feature_profile_manager = memnew(EditorFeatureProfileManager);
  6101. gui_base->add_child(feature_profile_manager);
  6102. build_profile_manager = memnew(EditorBuildProfileManager);
  6103. gui_base->add_child(build_profile_manager);
  6104. about = memnew(EditorAbout);
  6105. gui_base->add_child(about);
  6106. feature_profile_manager->connect("current_feature_profile_changed", callable_mp(this, &EditorNode::_feature_profile_changed));
  6107. #if !defined(ANDROID_ENABLED) && !defined(WEB_ENABLED)
  6108. fbx_importer_manager = memnew(FBXImporterManager);
  6109. gui_base->add_child(fbx_importer_manager);
  6110. #endif
  6111. warning = memnew(AcceptDialog);
  6112. warning->set_unparent_when_invisible(true);
  6113. warning->add_button(TTR("Copy Text"), true, "copy");
  6114. warning->connect("custom_action", callable_mp(this, &EditorNode::_copy_warning));
  6115. ED_SHORTCUT("editor/next_tab", TTRC("Next Scene Tab"), KeyModifierMask::CTRL + Key::TAB);
  6116. ED_SHORTCUT("editor/prev_tab", TTRC("Previous Scene Tab"), KeyModifierMask::CTRL + KeyModifierMask::SHIFT + Key::TAB);
  6117. ED_SHORTCUT("editor/filter_files", TTRC("Focus FileSystem Filter"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::ALT + Key::P);
  6118. command_palette = EditorCommandPalette::get_singleton();
  6119. command_palette->set_title(TTR("Command Palette"));
  6120. gui_base->add_child(command_palette);
  6121. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/new_scene", TTRC("New Scene"), KeyModifierMask::CMD_OR_CTRL + Key::N), FILE_NEW_SCENE);
  6122. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/new_inherited_scene", TTRC("New Inherited Scene..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::N), FILE_NEW_INHERITED_SCENE);
  6123. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/open_scene", TTRC("Open Scene..."), KeyModifierMask::CMD_OR_CTRL + Key::O), FILE_OPEN_SCENE);
  6124. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/reopen_closed_scene", TTRC("Reopen Closed Scene"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::T), FILE_OPEN_PREV);
  6125. recent_scenes = memnew(PopupMenu);
  6126. file_menu->add_submenu_node_item(TTR("Open Recent"), recent_scenes, FILE_OPEN_RECENT);
  6127. recent_scenes->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_open_recent_scene));
  6128. file_menu->add_separator();
  6129. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_scene", TTRC("Save Scene"), KeyModifierMask::CMD_OR_CTRL + Key::S), FILE_SAVE_SCENE);
  6130. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_scene_as", TTRC("Save Scene As..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::S), FILE_SAVE_AS_SCENE);
  6131. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/save_all_scenes", TTRC("Save All Scenes"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::S), FILE_SAVE_ALL_SCENES);
  6132. file_menu->add_separator();
  6133. file_menu->add_shortcut(ED_SHORTCUT_ARRAY_AND_COMMAND("editor/quick_open", TTRC("Quick Open..."), { int32_t(KeyModifierMask::SHIFT + KeyModifierMask::ALT + Key::O), int32_t(KeyModifierMask::CMD_OR_CTRL + Key::P) }), FILE_QUICK_OPEN);
  6134. ED_SHORTCUT_OVERRIDE_ARRAY("editor/quick_open", "macos", { int32_t(KeyModifierMask::META + KeyModifierMask::CTRL + Key::O), int32_t(KeyModifierMask::CMD_OR_CTRL + Key::P) });
  6135. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open_scene", TTRC("Quick Open Scene..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::O), FILE_QUICK_OPEN_SCENE);
  6136. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/quick_open_script", TTRC("Quick Open Script..."), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::ALT + Key::O), FILE_QUICK_OPEN_SCRIPT);
  6137. file_menu->add_separator();
  6138. export_as_menu = memnew(PopupMenu);
  6139. file_menu->add_submenu_node_item(TTR("Export As..."), export_as_menu);
  6140. export_as_menu->add_shortcut(ED_SHORTCUT("editor/export_as_mesh_library", TTRC("MeshLibrary...")), FILE_EXPORT_MESH_LIBRARY);
  6141. export_as_menu->connect("index_pressed", callable_mp(this, &EditorNode::_export_as_menu_option));
  6142. file_menu->add_separator();
  6143. file_menu->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO, false, true);
  6144. file_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO, false, true);
  6145. file_menu->add_separator();
  6146. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/reload_saved_scene", TTRC("Reload Saved Scene")), EDIT_RELOAD_SAVED_SCENE);
  6147. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/close_scene", TTRC("Close Scene"), KeyModifierMask::CMD_OR_CTRL + KeyModifierMask::SHIFT + Key::W), FILE_CLOSE);
  6148. ED_SHORTCUT_OVERRIDE("editor/close_scene", "macos", KeyModifierMask::CMD_OR_CTRL + Key::W);
  6149. if (!global_menu || !OS::get_singleton()->has_feature("macos")) {
  6150. // On macOS "Quit" and "About" options are in the "app" menu.
  6151. file_menu->add_separator();
  6152. file_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/file_quit", TTRC("Quit"), KeyModifierMask::CMD_OR_CTRL + Key::Q), FILE_QUIT, true);
  6153. }
  6154. ED_SHORTCUT_AND_COMMAND("editor/editor_settings", TTRC("Editor Settings..."));
  6155. ED_SHORTCUT_OVERRIDE("editor/editor_settings", "macos", KeyModifierMask::META + Key::COMMA);
  6156. #ifdef MACOS_ENABLED
  6157. if (global_menu && NativeMenu::get_singleton()->has_system_menu(NativeMenu::APPLICATION_MENU_ID)) {
  6158. apple_menu = memnew(PopupMenu);
  6159. apple_menu->set_system_menu(NativeMenu::APPLICATION_MENU_ID);
  6160. main_menu->add_child(apple_menu);
  6161. apple_menu->add_shortcut(ED_GET_SHORTCUT("editor/editor_settings"), SETTINGS_PREFERENCES);
  6162. apple_menu->add_separator();
  6163. apple_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
  6164. }
  6165. #endif
  6166. project_menu = memnew(PopupMenu);
  6167. project_menu->set_name(TTR("Project"));
  6168. main_menu->add_child(project_menu);
  6169. project_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/project_settings", TTRC("Project Settings..."), Key::NONE, TTRC("Project Settings")), RUN_SETTINGS);
  6170. project_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
  6171. project_menu->add_separator();
  6172. project_menu->add_item(TTR("Version Control"), VCS_MENU);
  6173. project_menu->add_separator();
  6174. project_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/export", TTRC("Export..."), Key::NONE, TTRC("Export")), FILE_EXPORT_PROJECT);
  6175. #ifndef ANDROID_ENABLED
  6176. project_menu->add_item(TTR("Install Android Build Template..."), FILE_INSTALL_ANDROID_SOURCE);
  6177. project_menu->add_item(TTR("Open User Data Folder"), RUN_USER_DATA_FOLDER);
  6178. #endif
  6179. project_menu->add_separator();
  6180. tool_menu = memnew(PopupMenu);
  6181. tool_menu->connect("index_pressed", callable_mp(this, &EditorNode::_tool_menu_option));
  6182. project_menu->add_submenu_node_item(TTR("Tools"), tool_menu);
  6183. tool_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/orphan_resource_explorer", TTRC("Orphan Resource Explorer...")), TOOLS_ORPHAN_RESOURCES);
  6184. tool_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/engine_compilation_configuration_editor", TTRC("Engine Compilation Configuration Editor...")), TOOLS_BUILD_PROFILE_MANAGER);
  6185. tool_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/upgrade_mesh_surfaces", TTRC("Upgrade Mesh Surfaces...")), TOOLS_SURFACE_UPGRADE);
  6186. project_menu->add_separator();
  6187. project_menu->add_shortcut(ED_SHORTCUT("editor/reload_current_project", TTRC("Reload Current Project")), RELOAD_CURRENT_PROJECT);
  6188. ED_SHORTCUT_AND_COMMAND("editor/quit_to_project_list", TTRC("Quit to Project List"), KeyModifierMask::CTRL + KeyModifierMask::SHIFT + Key::Q);
  6189. ED_SHORTCUT_OVERRIDE("editor/quit_to_project_list", "macos", KeyModifierMask::META + KeyModifierMask::CTRL + KeyModifierMask::ALT + Key::Q);
  6190. project_menu->add_shortcut(ED_GET_SHORTCUT("editor/quit_to_project_list"), RUN_PROJECT_MANAGER, true);
  6191. // Spacer to center 2D / 3D / Script buttons.
  6192. HBoxContainer *left_spacer = memnew(HBoxContainer);
  6193. left_spacer->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  6194. left_spacer->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  6195. title_bar->add_child(left_spacer);
  6196. if (can_expand && global_menu) {
  6197. project_title = memnew(Label);
  6198. project_title->add_theme_font_override(SceneStringName(font), theme->get_font(SNAME("bold"), EditorStringName(EditorFonts)));
  6199. project_title->add_theme_font_size_override(SceneStringName(font_size), theme->get_font_size(SNAME("bold_size"), EditorStringName(EditorFonts)));
  6200. project_title->set_focus_mode(Control::FOCUS_NONE);
  6201. project_title->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
  6202. project_title->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  6203. project_title->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  6204. project_title->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  6205. left_spacer->add_child(project_title);
  6206. }
  6207. HBoxContainer *main_editor_button_hb = memnew(HBoxContainer);
  6208. main_editor_button_hb->set_mouse_filter(Control::MOUSE_FILTER_STOP);
  6209. editor_main_screen->set_button_container(main_editor_button_hb);
  6210. title_bar->add_child(main_editor_button_hb);
  6211. // Options are added and handled by DebuggerEditorPlugin.
  6212. debug_menu = memnew(PopupMenu);
  6213. debug_menu->set_name(TTR("Debug"));
  6214. main_menu->add_child(debug_menu);
  6215. settings_menu = memnew(PopupMenu);
  6216. settings_menu->set_name(TTR("Editor"));
  6217. main_menu->add_child(settings_menu);
  6218. #ifdef MACOS_ENABLED
  6219. if (!global_menu) {
  6220. settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/editor_settings"), SETTINGS_PREFERENCES);
  6221. }
  6222. #else
  6223. settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/editor_settings"), SETTINGS_PREFERENCES);
  6224. #endif
  6225. settings_menu->add_shortcut(ED_SHORTCUT("editor/command_palette", TTRC("Command Palette..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::P), HELP_COMMAND_PALETTE);
  6226. settings_menu->add_separator();
  6227. settings_menu->add_submenu_node_item(TTR("Editor Docks"), editor_dock_manager->get_docks_menu());
  6228. editor_layouts = memnew(PopupMenu);
  6229. editor_layouts->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  6230. settings_menu->add_submenu_node_item(TTR("Editor Layout"), editor_layouts);
  6231. editor_layouts->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_layout_menu_option));
  6232. settings_menu->add_separator();
  6233. ED_SHORTCUT_AND_COMMAND("editor/take_screenshot", TTRC("Take Screenshot"), KeyModifierMask::CTRL | Key::F12);
  6234. ED_SHORTCUT_OVERRIDE("editor/take_screenshot", "macos", KeyModifierMask::META | Key::F12);
  6235. settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/take_screenshot"), EDITOR_SCREENSHOT);
  6236. settings_menu->set_item_tooltip(-1, TTR("Screenshots are stored in the user data folder (\"user://\")."));
  6237. ED_SHORTCUT_AND_COMMAND("editor/fullscreen_mode", TTRC("Toggle Fullscreen"), KeyModifierMask::SHIFT | Key::F11);
  6238. ED_SHORTCUT_OVERRIDE("editor/fullscreen_mode", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::F);
  6239. settings_menu->add_shortcut(ED_GET_SHORTCUT("editor/fullscreen_mode"), SETTINGS_TOGGLE_FULLSCREEN);
  6240. settings_menu->add_separator();
  6241. #ifndef ANDROID_ENABLED
  6242. if (OS::get_singleton()->get_data_path() == OS::get_singleton()->get_config_path()) {
  6243. // Configuration and data folders are located in the same place (Windows/macOS).
  6244. settings_menu->add_item(TTR("Open Editor Data/Settings Folder"), SETTINGS_EDITOR_DATA_FOLDER);
  6245. } else {
  6246. // Separate configuration and data folders (Linux).
  6247. settings_menu->add_item(TTR("Open Editor Data Folder"), SETTINGS_EDITOR_DATA_FOLDER);
  6248. settings_menu->add_item(TTR("Open Editor Settings Folder"), SETTINGS_EDITOR_CONFIG_FOLDER);
  6249. }
  6250. settings_menu->add_separator();
  6251. #endif
  6252. settings_menu->add_item(TTR("Manage Editor Features..."), SETTINGS_MANAGE_FEATURE_PROFILES);
  6253. settings_menu->add_item(TTR("Manage Export Templates..."), SETTINGS_MANAGE_EXPORT_TEMPLATES);
  6254. #if !defined(ANDROID_ENABLED) && !defined(WEB_ENABLED)
  6255. settings_menu->add_item(TTR("Configure FBX Importer..."), SETTINGS_MANAGE_FBX_IMPORTER);
  6256. #endif
  6257. help_menu = memnew(PopupMenu);
  6258. help_menu->set_name(TTR("Help"));
  6259. if (global_menu && NativeMenu::get_singleton()->has_system_menu(NativeMenu::HELP_MENU_ID)) {
  6260. help_menu->set_system_menu(NativeMenu::HELP_MENU_ID);
  6261. }
  6262. main_menu->add_child(help_menu);
  6263. help_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
  6264. ED_SHORTCUT_AND_COMMAND("editor/editor_help", TTRC("Search Help..."), Key::F1);
  6265. ED_SHORTCUT_OVERRIDE("editor/editor_help", "macos", KeyModifierMask::ALT | Key::SPACE);
  6266. help_menu->add_icon_shortcut(theme->get_icon(SNAME("HelpSearch"), EditorStringName(EditorIcons)), ED_GET_SHORTCUT("editor/editor_help"), HELP_SEARCH);
  6267. help_menu->add_separator();
  6268. help_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/online_docs", TTRC("Online Documentation")), HELP_DOCS);
  6269. help_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/forum", TTRC("Forum")), HELP_FORUM);
  6270. help_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/community", TTRC("Community")), HELP_COMMUNITY);
  6271. help_menu->add_separator();
  6272. help_menu->add_icon_shortcut(theme->get_icon(SNAME("ActionCopy"), EditorStringName(EditorIcons)), ED_SHORTCUT_AND_COMMAND("editor/copy_system_info", TTRC("Copy System Info")), HELP_COPY_SYSTEM_INFO);
  6273. help_menu->set_item_tooltip(-1, TTR("Copies the system info as a single-line text into the clipboard."));
  6274. help_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/report_a_bug", TTRC("Report a Bug")), HELP_REPORT_A_BUG);
  6275. help_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/suggest_a_feature", TTRC("Suggest a Feature")), HELP_SUGGEST_A_FEATURE);
  6276. help_menu->add_shortcut(ED_SHORTCUT_AND_COMMAND("editor/send_docs_feedback", TTRC("Send Docs Feedback")), HELP_SEND_DOCS_FEEDBACK);
  6277. help_menu->add_separator();
  6278. if (!global_menu || !OS::get_singleton()->has_feature("macos")) {
  6279. // On macOS "Quit" and "About" options are in the "app" menu.
  6280. help_menu->add_icon_shortcut(theme->get_icon(SNAME("Godot"), EditorStringName(EditorIcons)), ED_SHORTCUT_AND_COMMAND("editor/about", TTRC("About Godot...")), HELP_ABOUT);
  6281. }
  6282. help_menu->add_icon_shortcut(theme->get_icon(SNAME("Heart"), EditorStringName(EditorIcons)), ED_SHORTCUT_AND_COMMAND("editor/support_development", TTRC("Support Godot Development")), HELP_SUPPORT_GODOT_DEVELOPMENT);
  6283. // Spacer to center 2D / 3D / Script buttons.
  6284. Control *right_spacer = memnew(Control);
  6285. right_spacer->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  6286. right_spacer->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  6287. title_bar->add_child(right_spacer);
  6288. project_run_bar = memnew(EditorRunBar);
  6289. project_run_bar->set_mouse_filter(Control::MOUSE_FILTER_STOP);
  6290. title_bar->add_child(project_run_bar);
  6291. project_run_bar->connect("play_pressed", callable_mp(this, &EditorNode::_project_run_started));
  6292. project_run_bar->connect("stop_pressed", callable_mp(this, &EditorNode::_project_run_stopped));
  6293. HBoxContainer *right_menu_hb = memnew(HBoxContainer);
  6294. right_menu_hb->set_mouse_filter(Control::MOUSE_FILTER_STOP);
  6295. title_bar->add_child(right_menu_hb);
  6296. renderer = memnew(OptionButton);
  6297. renderer->set_visible(true);
  6298. renderer->set_flat(true);
  6299. renderer->set_theme_type_variation("TopBarOptionButton");
  6300. renderer->set_fit_to_longest_item(false);
  6301. renderer->set_focus_mode(Control::FOCUS_NONE);
  6302. renderer->set_tooltip_text(TTR("Choose a rendering method.\n\nNotes:\n- On mobile platforms, the Mobile rendering method is used if Forward+ is selected here.\n- On the web platform, the Compatibility rendering method is always used."));
  6303. right_menu_hb->add_child(renderer);
  6304. if (can_expand) {
  6305. // Add spacer to avoid other controls under the window minimize/maximize/close buttons (right side).
  6306. right_menu_spacer = memnew(Control);
  6307. right_menu_spacer->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  6308. title_bar->add_child(right_menu_spacer);
  6309. }
  6310. String current_renderer_ps = GLOBAL_GET("rendering/renderer/rendering_method");
  6311. current_renderer_ps = current_renderer_ps.to_lower();
  6312. String current_renderer_os = OS::get_singleton()->get_current_rendering_method().to_lower();
  6313. // Add the renderers name to the UI.
  6314. if (current_renderer_ps == current_renderer_os) {
  6315. renderer->connect(SceneStringName(item_selected), callable_mp(this, &EditorNode::_renderer_selected));
  6316. // As we are doing string comparisons, keep in standard case to prevent problems with capitals
  6317. // "vulkan" in particular uses lowercase "v" in the code, and uppercase in the UI.
  6318. PackedStringArray renderers = ProjectSettings::get_singleton()->get_custom_property_info().get(StringName("rendering/renderer/rendering_method")).hint_string.split(",", false);
  6319. for (int i = 0; i < renderers.size(); i++) {
  6320. String rendering_method = renderers[i];
  6321. _add_renderer_entry(rendering_method, false);
  6322. renderer->set_item_metadata(i, rendering_method);
  6323. // Lowercase for standard comparison.
  6324. rendering_method = rendering_method.to_lower();
  6325. if (current_renderer_ps == rendering_method) {
  6326. renderer->select(i);
  6327. renderer_current = i;
  6328. }
  6329. }
  6330. } else {
  6331. // It's an CLI-overridden rendering method.
  6332. _add_renderer_entry(current_renderer_os, true);
  6333. renderer->set_item_metadata(0, current_renderer_os);
  6334. renderer->select(0);
  6335. renderer_current = 0;
  6336. }
  6337. _update_renderer_color();
  6338. video_restart_dialog = memnew(ConfirmationDialog);
  6339. video_restart_dialog->set_ok_button_text(TTR("Save & Restart"));
  6340. video_restart_dialog->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind(SET_RENDERER_NAME_SAVE_AND_RESTART));
  6341. gui_base->add_child(video_restart_dialog);
  6342. progress_hb = memnew(BackgroundProgress);
  6343. layout_dialog = memnew(EditorLayoutsDialog);
  6344. gui_base->add_child(layout_dialog);
  6345. layout_dialog->set_hide_on_ok(false);
  6346. layout_dialog->set_size(Size2(225, 270) * EDSCALE);
  6347. layout_dialog->connect("name_confirmed", callable_mp(this, &EditorNode::_dialog_action));
  6348. update_spinner = memnew(MenuButton);
  6349. right_menu_hb->add_child(update_spinner);
  6350. update_spinner->set_button_icon(theme->get_icon(SNAME("Progress1"), EditorStringName(EditorIcons)));
  6351. update_spinner->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
  6352. PopupMenu *p = update_spinner->get_popup();
  6353. p->add_radio_check_item(TTR("Update Continuously"), SETTINGS_UPDATE_CONTINUOUSLY);
  6354. p->add_radio_check_item(TTR("Update When Changed"), SETTINGS_UPDATE_WHEN_CHANGED);
  6355. p->add_separator();
  6356. p->add_item(TTR("Hide Update Spinner"), SETTINGS_UPDATE_SPINNER_HIDE);
  6357. _update_update_spinner();
  6358. // Instantiate and place editor docks.
  6359. memnew(SceneTreeDock(scene_root, editor_selection, editor_data));
  6360. memnew(InspectorDock(editor_data));
  6361. memnew(ImportDock);
  6362. memnew(NodeDock);
  6363. FileSystemDock *filesystem_dock = memnew(FileSystemDock);
  6364. filesystem_dock->connect("inherit", callable_mp(this, &EditorNode::_inherit_request));
  6365. filesystem_dock->connect("instantiate", callable_mp(this, &EditorNode::_instantiate_request));
  6366. filesystem_dock->connect("display_mode_changed", callable_mp(this, &EditorNode::_save_editor_layout));
  6367. get_project_settings()->connect_filesystem_dock_signals(filesystem_dock);
  6368. history_dock = memnew(HistoryDock);
  6369. // Scene: Top left.
  6370. editor_dock_manager->add_dock(SceneTreeDock::get_singleton(), TTR("Scene"), EditorDockManager::DOCK_SLOT_LEFT_UR, nullptr, "PackedScene");
  6371. // Import: Top left, behind Scene.
  6372. editor_dock_manager->add_dock(ImportDock::get_singleton(), TTR("Import"), EditorDockManager::DOCK_SLOT_LEFT_UR, nullptr, "FileAccess");
  6373. // FileSystem: Bottom left.
  6374. editor_dock_manager->add_dock(FileSystemDock::get_singleton(), TTR("FileSystem"), EditorDockManager::DOCK_SLOT_LEFT_BR, ED_SHORTCUT_AND_COMMAND("bottom_panels/toggle_filesystem_bottom_panel", TTRC("Toggle FileSystem Bottom Panel"), KeyModifierMask::ALT | Key::F), "Folder");
  6375. // Inspector: Full height right.
  6376. editor_dock_manager->add_dock(InspectorDock::get_singleton(), TTR("Inspector"), EditorDockManager::DOCK_SLOT_RIGHT_UL, nullptr, "AnimationTrackList");
  6377. // Node: Full height right, behind Inspector.
  6378. editor_dock_manager->add_dock(NodeDock::get_singleton(), TTR("Node"), EditorDockManager::DOCK_SLOT_RIGHT_UL, nullptr, "Object");
  6379. // History: Full height right, behind Node.
  6380. editor_dock_manager->add_dock(history_dock, TTR("History"), EditorDockManager::DOCK_SLOT_RIGHT_UL, nullptr, "History");
  6381. // Add some offsets to left_r and main hsplits to make LEFT_R and RIGHT_L docks wider than minsize.
  6382. left_r_hsplit->set_split_offset(270 * EDSCALE);
  6383. main_hsplit->set_split_offset(-270 * EDSCALE);
  6384. // Define corresponding default layout.
  6385. const String docks_section = "docks";
  6386. default_layout.instantiate();
  6387. // Dock numbers are based on DockSlot enum value + 1.
  6388. default_layout->set_value(docks_section, "dock_3", "Scene,Import");
  6389. default_layout->set_value(docks_section, "dock_4", "FileSystem");
  6390. default_layout->set_value(docks_section, "dock_5", "Inspector,Node,History");
  6391. // There are 4 vsplits and 4 hsplits.
  6392. for (int i = 0; i < editor_dock_manager->get_vsplit_count(); i++) {
  6393. default_layout->set_value(docks_section, "dock_split_" + itos(i + 1), 0);
  6394. }
  6395. default_layout->set_value(docks_section, "dock_hsplit_1", 0);
  6396. default_layout->set_value(docks_section, "dock_hsplit_2", 270);
  6397. default_layout->set_value(docks_section, "dock_hsplit_3", -270);
  6398. default_layout->set_value(docks_section, "dock_hsplit_4", 0);
  6399. _update_layouts_menu();
  6400. // Bottom panels.
  6401. bottom_panel = memnew(EditorBottomPanel);
  6402. center_split->add_child(bottom_panel);
  6403. center_split->set_dragger_visibility(SplitContainer::DRAGGER_HIDDEN);
  6404. log = memnew(EditorLog);
  6405. Button *output_button = bottom_panel->add_item(TTR("Output"), log, ED_SHORTCUT_AND_COMMAND("bottom_panels/toggle_output_bottom_panel", TTRC("Toggle Output Bottom Panel"), KeyModifierMask::ALT | Key::O));
  6406. log->set_tool_button(output_button);
  6407. center_split->connect(SceneStringName(resized), callable_mp(this, &EditorNode::_vp_resized));
  6408. native_shader_source_visualizer = memnew(EditorNativeShaderSourceVisualizer);
  6409. gui_base->add_child(native_shader_source_visualizer);
  6410. orphan_resources = memnew(OrphanResourcesDialog);
  6411. gui_base->add_child(orphan_resources);
  6412. surface_upgrade_dialog = memnew(SurfaceUpgradeDialog);
  6413. gui_base->add_child(surface_upgrade_dialog);
  6414. confirmation = memnew(ConfirmationDialog);
  6415. gui_base->add_child(confirmation);
  6416. confirmation->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_confirm_current));
  6417. save_confirmation = memnew(ConfirmationDialog);
  6418. save_confirmation->add_button(TTR("Don't Save"), DisplayServer::get_singleton()->get_swap_cancel_ok(), "discard");
  6419. gui_base->add_child(save_confirmation);
  6420. save_confirmation->set_min_size(Vector2(450.0 * EDSCALE, 0));
  6421. save_confirmation->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_confirm_current));
  6422. save_confirmation->connect("custom_action", callable_mp(this, &EditorNode::_discard_changes));
  6423. save_confirmation->connect("canceled", callable_mp(this, &EditorNode::_cancel_close_scene_tab));
  6424. gradle_build_manage_templates = memnew(ConfirmationDialog);
  6425. gradle_build_manage_templates->set_text(TTR("Android build template is missing, please install relevant templates."));
  6426. gradle_build_manage_templates->set_ok_button_text(TTR("Manage Templates"));
  6427. gradle_build_manage_templates->add_button(TTR("Install from file"))->connect(SceneStringName(pressed), callable_mp(this, &EditorNode::_menu_option).bind(SETTINGS_INSTALL_ANDROID_BUILD_TEMPLATE));
  6428. gradle_build_manage_templates->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind(SETTINGS_MANAGE_EXPORT_TEMPLATES));
  6429. gui_base->add_child(gradle_build_manage_templates);
  6430. file_android_build_source = memnew(EditorFileDialog);
  6431. file_android_build_source->set_title(TTR("Select Android sources file"));
  6432. file_android_build_source->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
  6433. file_android_build_source->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  6434. file_android_build_source->add_filter("*.zip");
  6435. file_android_build_source->connect("file_selected", callable_mp(this, &EditorNode::_android_build_source_selected));
  6436. gui_base->add_child(file_android_build_source);
  6437. {
  6438. VBoxContainer *vbox = memnew(VBoxContainer);
  6439. install_android_build_template_message = memnew(Label);
  6440. install_android_build_template_message->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
  6441. install_android_build_template_message->set_custom_minimum_size(Size2(300 * EDSCALE, 1));
  6442. vbox->add_child(install_android_build_template_message);
  6443. choose_android_export_profile = memnew(OptionButton);
  6444. choose_android_export_profile->connect(SceneStringName(item_selected), callable_mp(this, &EditorNode::_android_export_preset_selected));
  6445. vbox->add_child(choose_android_export_profile);
  6446. install_android_build_template = memnew(ConfirmationDialog);
  6447. install_android_build_template->set_ok_button_text(TTR("Install"));
  6448. install_android_build_template->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_confirm_current));
  6449. install_android_build_template->add_child(vbox);
  6450. install_android_build_template->set_min_size(Vector2(500.0 * EDSCALE, 0));
  6451. gui_base->add_child(install_android_build_template);
  6452. }
  6453. remove_android_build_template = memnew(ConfirmationDialog);
  6454. remove_android_build_template->set_ok_button_text(TTR("Show in File Manager"));
  6455. remove_android_build_template->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind(FILE_EXPLORE_ANDROID_BUILD_TEMPLATES));
  6456. gui_base->add_child(remove_android_build_template);
  6457. file_templates = memnew(EditorFileDialog);
  6458. file_templates->set_title(TTR("Import Templates From ZIP File"));
  6459. gui_base->add_child(file_templates);
  6460. file_templates->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  6461. file_templates->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
  6462. file_templates->clear_filters();
  6463. file_templates->add_filter("*.tpz", TTR("Template Package"));
  6464. file = memnew(EditorFileDialog);
  6465. gui_base->add_child(file);
  6466. file->set_current_dir("res://");
  6467. file->set_transient_to_focused(true);
  6468. file_export_lib = memnew(EditorFileDialog);
  6469. file_export_lib->set_title(TTR("Export Library"));
  6470. file_export_lib->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
  6471. file_export_lib->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
  6472. file_export_lib->add_option(TTR("Merge With Existing"), Vector<String>(), true);
  6473. file_export_lib->add_option(TTR("Apply MeshInstance Transforms"), Vector<String>(), false);
  6474. gui_base->add_child(file_export_lib);
  6475. file_script = memnew(EditorFileDialog);
  6476. file_script->set_title(TTR("Open & Run a Script"));
  6477. file_script->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
  6478. file_script->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  6479. List<String> sexts;
  6480. ResourceLoader::get_recognized_extensions_for_type("Script", &sexts);
  6481. for (const String &E : sexts) {
  6482. file_script->add_filter("*." + E);
  6483. }
  6484. gui_base->add_child(file_script);
  6485. file_script->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
  6486. file_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
  6487. file_menu->connect("about_to_popup", callable_mp(this, &EditorNode::_update_file_menu_opened));
  6488. file_menu->connect("popup_hide", callable_mp(this, &EditorNode::_update_file_menu_closed));
  6489. settings_menu->connect(SceneStringName(id_pressed), callable_mp(this, &EditorNode::_menu_option));
  6490. file->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
  6491. file_templates->connect("file_selected", callable_mp(this, &EditorNode::_dialog_action));
  6492. audio_preview_gen = memnew(AudioStreamPreviewGenerator);
  6493. add_child(audio_preview_gen);
  6494. add_editor_plugin(memnew(DebuggerEditorPlugin(debug_menu)));
  6495. disk_changed = memnew(ConfirmationDialog);
  6496. {
  6497. disk_changed->set_title(TTR("Files have been modified outside Godot"));
  6498. VBoxContainer *vbc = memnew(VBoxContainer);
  6499. disk_changed->add_child(vbc);
  6500. Label *dl = memnew(Label);
  6501. dl->set_text(TTR("The following files are newer on disk:"));
  6502. vbc->add_child(dl);
  6503. disk_changed_list = memnew(Tree);
  6504. vbc->add_child(disk_changed_list);
  6505. disk_changed_list->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  6506. Label *what_action_label = memnew(Label);
  6507. what_action_label->set_text(TTR("What action should be taken?"));
  6508. vbc->add_child(what_action_label);
  6509. disk_changed->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_reload_modified_scenes));
  6510. disk_changed->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_reload_project_settings));
  6511. disk_changed->set_ok_button_text(TTR("Reload from disk"));
  6512. disk_changed->add_button(TTR("Ignore external changes"), !DisplayServer::get_singleton()->get_swap_cancel_ok(), "resave");
  6513. disk_changed->connect("custom_action", callable_mp(this, &EditorNode::_resave_scenes));
  6514. }
  6515. gui_base->add_child(disk_changed);
  6516. add_editor_plugin(memnew(AnimationPlayerEditorPlugin));
  6517. add_editor_plugin(memnew(AnimationTrackKeyEditEditorPlugin));
  6518. add_editor_plugin(memnew(AnimationMarkerKeyEditEditorPlugin));
  6519. add_editor_plugin(memnew(CanvasItemEditorPlugin));
  6520. add_editor_plugin(memnew(Node3DEditorPlugin));
  6521. add_editor_plugin(memnew(ScriptEditorPlugin));
  6522. add_editor_plugin(memnew(GameViewPlugin));
  6523. EditorAudioBuses *audio_bus_editor = EditorAudioBuses::register_editor();
  6524. ScriptTextEditor::register_editor(); // Register one for text scripts.
  6525. TextEditor::register_editor();
  6526. if (AssetLibraryEditorPlugin::is_available()) {
  6527. add_editor_plugin(memnew(AssetLibraryEditorPlugin));
  6528. } else {
  6529. print_verbose("Asset Library not available (due to using Web editor, or SSL support disabled).");
  6530. }
  6531. // More visually meaningful to have this later.
  6532. bottom_panel->move_item_to_end(AnimationPlayerEditor::get_singleton());
  6533. add_editor_plugin(VersionControlEditorPlugin::get_singleton());
  6534. vcs_actions_menu = VersionControlEditorPlugin::get_singleton()->get_version_control_actions_panel();
  6535. vcs_actions_menu->connect("index_pressed", callable_mp(this, &EditorNode::_version_control_menu_option));
  6536. vcs_actions_menu->add_item(TTR("Create/Override Version Control Metadata..."), RUN_VCS_METADATA);
  6537. vcs_actions_menu->add_item(TTR("Version Control Settings..."), RUN_VCS_SETTINGS);
  6538. project_menu->set_item_submenu_node(project_menu->get_item_index(VCS_MENU), vcs_actions_menu);
  6539. add_editor_plugin(memnew(AudioBusesEditorPlugin(audio_bus_editor)));
  6540. for (int i = 0; i < EditorPlugins::get_plugin_count(); i++) {
  6541. add_editor_plugin(EditorPlugins::create(i));
  6542. }
  6543. for (const StringName &extension_class_name : GDExtensionEditorPlugins::get_extension_classes()) {
  6544. add_extension_editor_plugin(extension_class_name);
  6545. }
  6546. GDExtensionEditorPlugins::editor_node_add_plugin = &EditorNode::add_extension_editor_plugin;
  6547. GDExtensionEditorPlugins::editor_node_remove_plugin = &EditorNode::remove_extension_editor_plugin;
  6548. for (int i = 0; i < plugin_init_callback_count; i++) {
  6549. plugin_init_callbacks[i]();
  6550. }
  6551. resource_preview->add_preview_generator(Ref<EditorTexturePreviewPlugin>(memnew(EditorTexturePreviewPlugin)));
  6552. resource_preview->add_preview_generator(Ref<EditorImagePreviewPlugin>(memnew(EditorImagePreviewPlugin)));
  6553. resource_preview->add_preview_generator(Ref<EditorPackedScenePreviewPlugin>(memnew(EditorPackedScenePreviewPlugin)));
  6554. resource_preview->add_preview_generator(Ref<EditorMaterialPreviewPlugin>(memnew(EditorMaterialPreviewPlugin)));
  6555. resource_preview->add_preview_generator(Ref<EditorScriptPreviewPlugin>(memnew(EditorScriptPreviewPlugin)));
  6556. resource_preview->add_preview_generator(Ref<EditorAudioStreamPreviewPlugin>(memnew(EditorAudioStreamPreviewPlugin)));
  6557. resource_preview->add_preview_generator(Ref<EditorMeshPreviewPlugin>(memnew(EditorMeshPreviewPlugin)));
  6558. resource_preview->add_preview_generator(Ref<EditorBitmapPreviewPlugin>(memnew(EditorBitmapPreviewPlugin)));
  6559. resource_preview->add_preview_generator(Ref<EditorFontPreviewPlugin>(memnew(EditorFontPreviewPlugin)));
  6560. resource_preview->add_preview_generator(Ref<EditorGradientPreviewPlugin>(memnew(EditorGradientPreviewPlugin)));
  6561. {
  6562. Ref<StandardMaterial3DConversionPlugin> spatial_mat_convert;
  6563. spatial_mat_convert.instantiate();
  6564. resource_conversion_plugins.push_back(spatial_mat_convert);
  6565. Ref<ORMMaterial3DConversionPlugin> orm_mat_convert;
  6566. orm_mat_convert.instantiate();
  6567. resource_conversion_plugins.push_back(orm_mat_convert);
  6568. Ref<CanvasItemMaterialConversionPlugin> canvas_item_mat_convert;
  6569. canvas_item_mat_convert.instantiate();
  6570. resource_conversion_plugins.push_back(canvas_item_mat_convert);
  6571. Ref<ParticleProcessMaterialConversionPlugin> particles_mat_convert;
  6572. particles_mat_convert.instantiate();
  6573. resource_conversion_plugins.push_back(particles_mat_convert);
  6574. Ref<ProceduralSkyMaterialConversionPlugin> procedural_sky_mat_convert;
  6575. procedural_sky_mat_convert.instantiate();
  6576. resource_conversion_plugins.push_back(procedural_sky_mat_convert);
  6577. Ref<PanoramaSkyMaterialConversionPlugin> panorama_sky_mat_convert;
  6578. panorama_sky_mat_convert.instantiate();
  6579. resource_conversion_plugins.push_back(panorama_sky_mat_convert);
  6580. Ref<PhysicalSkyMaterialConversionPlugin> physical_sky_mat_convert;
  6581. physical_sky_mat_convert.instantiate();
  6582. resource_conversion_plugins.push_back(physical_sky_mat_convert);
  6583. Ref<FogMaterialConversionPlugin> fog_mat_convert;
  6584. fog_mat_convert.instantiate();
  6585. resource_conversion_plugins.push_back(fog_mat_convert);
  6586. Ref<VisualShaderConversionPlugin> vshader_convert;
  6587. vshader_convert.instantiate();
  6588. resource_conversion_plugins.push_back(vshader_convert);
  6589. }
  6590. update_spinner_step_msec = OS::get_singleton()->get_ticks_msec();
  6591. update_spinner_step_frame = Engine::get_singleton()->get_frames_drawn();
  6592. editor_plugins_over = memnew(EditorPluginList);
  6593. editor_plugins_force_over = memnew(EditorPluginList);
  6594. editor_plugins_force_input_forwarding = memnew(EditorPluginList);
  6595. Ref<GDExtensionExportPlugin> gdextension_export_plugin;
  6596. gdextension_export_plugin.instantiate();
  6597. EditorExport::get_singleton()->add_export_plugin(gdextension_export_plugin);
  6598. Ref<DedicatedServerExportPlugin> dedicated_server_export_plugin;
  6599. dedicated_server_export_plugin.instantiate();
  6600. EditorExport::get_singleton()->add_export_plugin(dedicated_server_export_plugin);
  6601. Ref<PackedSceneEditorTranslationParserPlugin> packed_scene_translation_parser_plugin;
  6602. packed_scene_translation_parser_plugin.instantiate();
  6603. EditorTranslationParser::get_singleton()->add_parser(packed_scene_translation_parser_plugin, EditorTranslationParser::STANDARD);
  6604. _edit_current();
  6605. current = nullptr;
  6606. saving_resource = Ref<Resource>();
  6607. set_process(true);
  6608. open_imported = memnew(ConfirmationDialog);
  6609. open_imported->set_ok_button_text(TTR("Open Anyway"));
  6610. new_inherited_button = open_imported->add_button(TTR("New Inherited"), !DisplayServer::get_singleton()->get_swap_cancel_ok(), "inherit");
  6611. open_imported->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_open_imported));
  6612. open_imported->connect("custom_action", callable_mp(this, &EditorNode::_inherit_imported));
  6613. gui_base->add_child(open_imported);
  6614. quick_open_dialog = memnew(EditorQuickOpenDialog);
  6615. gui_base->add_child(quick_open_dialog);
  6616. quick_open_color_palette = memnew(EditorQuickOpenDialog);
  6617. gui_base->add_child(quick_open_color_palette);
  6618. _update_recent_scenes();
  6619. set_process_shortcut_input(true);
  6620. load_errors = memnew(RichTextLabel);
  6621. load_error_dialog = memnew(AcceptDialog);
  6622. load_error_dialog->set_unparent_when_invisible(true);
  6623. load_error_dialog->add_child(load_errors);
  6624. load_error_dialog->set_title(TTR("Load Errors"));
  6625. load_error_dialog->connect(SceneStringName(visibility_changed), callable_mp(this, &EditorNode::_load_error_dialog_visibility_changed));
  6626. execute_outputs = memnew(RichTextLabel);
  6627. execute_outputs->set_selection_enabled(true);
  6628. execute_outputs->set_context_menu_enabled(true);
  6629. execute_output_dialog = memnew(AcceptDialog);
  6630. execute_output_dialog->set_unparent_when_invisible(true);
  6631. execute_output_dialog->add_child(execute_outputs);
  6632. execute_output_dialog->set_title("");
  6633. EditorFileSystem::get_singleton()->connect("sources_changed", callable_mp(this, &EditorNode::_sources_changed));
  6634. EditorFileSystem::get_singleton()->connect("filesystem_changed", callable_mp(this, &EditorNode::_fs_changed));
  6635. EditorFileSystem::get_singleton()->connect("resources_reimporting", callable_mp(this, &EditorNode::_resources_reimporting));
  6636. EditorFileSystem::get_singleton()->connect("resources_reimported", callable_mp(this, &EditorNode::_resources_reimported));
  6637. EditorFileSystem::get_singleton()->connect("resources_reload", callable_mp(this, &EditorNode::_resources_changed));
  6638. _build_icon_type_cache();
  6639. pick_main_scene = memnew(ConfirmationDialog);
  6640. gui_base->add_child(pick_main_scene);
  6641. pick_main_scene->set_ok_button_text(TTR("Select"));
  6642. pick_main_scene->connect(SceneStringName(confirmed), callable_mp(this, &EditorNode::_menu_option).bind(SETTINGS_PICK_MAIN_SCENE));
  6643. select_current_scene_button = pick_main_scene->add_button(TTR("Select Current"), true, "select_current");
  6644. pick_main_scene->connect("custom_action", callable_mp(this, &EditorNode::_pick_main_scene_custom_action));
  6645. for (int i = 0; i < _init_callbacks.size(); i++) {
  6646. _init_callbacks[i]();
  6647. }
  6648. editor_data.add_edited_scene(-1);
  6649. editor_data.set_edited_scene(0);
  6650. scene_tabs->update_scene_tabs();
  6651. ImportDock::get_singleton()->initialize_import_options();
  6652. FileAccess::set_file_close_fail_notify_callback(_file_access_close_error_notify);
  6653. print_handler.printfunc = _print_handler;
  6654. print_handler.userdata = this;
  6655. add_print_handler(&print_handler);
  6656. ResourceSaver::set_save_callback(_resource_saved);
  6657. ResourceLoader::set_load_callback(_resource_loaded);
  6658. // Use the Ctrl modifier so F2 can be used to rename nodes in the scene tree dock.
  6659. ED_SHORTCUT_AND_COMMAND("editor/editor_2d", TTRC("Open 2D Editor"), KeyModifierMask::CTRL | Key::F1);
  6660. ED_SHORTCUT_AND_COMMAND("editor/editor_3d", TTRC("Open 3D Editor"), KeyModifierMask::CTRL | Key::F2);
  6661. ED_SHORTCUT_AND_COMMAND("editor/editor_script", TTRC("Open Script Editor"), KeyModifierMask::CTRL | Key::F3);
  6662. ED_SHORTCUT_AND_COMMAND("editor/editor_game", TTRC("Open Game View"), KeyModifierMask::CTRL | Key::F4);
  6663. ED_SHORTCUT_AND_COMMAND("editor/editor_assetlib", TTRC("Open Asset Library"), KeyModifierMask::CTRL | Key::F5);
  6664. ED_SHORTCUT_OVERRIDE("editor/editor_2d", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_1);
  6665. ED_SHORTCUT_OVERRIDE("editor/editor_3d", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_2);
  6666. ED_SHORTCUT_OVERRIDE("editor/editor_script", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_3);
  6667. ED_SHORTCUT_OVERRIDE("editor/editor_game", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_4);
  6668. ED_SHORTCUT_OVERRIDE("editor/editor_assetlib", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::KEY_5);
  6669. ED_SHORTCUT_AND_COMMAND("editor/editor_next", TTRC("Open the next Editor"));
  6670. ED_SHORTCUT_AND_COMMAND("editor/editor_prev", TTRC("Open the previous Editor"));
  6671. // Apply setting presets in case the editor_settings file is missing values.
  6672. EditorSettingsDialog::update_navigation_preset();
  6673. screenshot_timer = memnew(Timer);
  6674. screenshot_timer->set_one_shot(true);
  6675. screenshot_timer->set_wait_time(settings_menu->get_submenu_popup_delay() + 0.1f);
  6676. screenshot_timer->connect("timeout", callable_mp(this, &EditorNode::_request_screenshot));
  6677. add_child(screenshot_timer);
  6678. screenshot_timer->set_owner(get_owner());
  6679. // Adjust spacers to center 2D / 3D / Script buttons.
  6680. int max_w = MAX(project_run_bar->get_minimum_size().x + right_menu_hb->get_minimum_size().x, main_menu->get_minimum_size().x);
  6681. left_spacer->set_custom_minimum_size(Size2(MAX(0, max_w - main_menu->get_minimum_size().x), 0));
  6682. right_spacer->set_custom_minimum_size(Size2(MAX(0, max_w - project_run_bar->get_minimum_size().x - right_menu_hb->get_minimum_size().x), 0));
  6683. // Extend menu bar to window title.
  6684. if (can_expand) {
  6685. DisplayServer::get_singleton()->process_events();
  6686. DisplayServer::get_singleton()->window_set_flag(DisplayServer::WINDOW_FLAG_EXTEND_TO_TITLE, true, DisplayServer::MAIN_WINDOW_ID);
  6687. title_bar->set_can_move_window(true);
  6688. }
  6689. {
  6690. const String exec = OS::get_singleton()->get_executable_path();
  6691. const String old_exec = EditorSettings::get_singleton()->get_project_metadata("editor_metadata", "executable_path", "");
  6692. // Save editor executable path for third-party tools.
  6693. if (exec != old_exec) {
  6694. EditorSettings::get_singleton()->set_project_metadata("editor_metadata", "executable_path", exec);
  6695. }
  6696. }
  6697. follow_system_theme = EDITOR_GET("interface/theme/follow_system_theme");
  6698. use_system_accent_color = EDITOR_GET("interface/theme/use_system_accent_color");
  6699. system_theme_timer = memnew(Timer);
  6700. system_theme_timer->set_wait_time(1.0);
  6701. system_theme_timer->connect("timeout", callable_mp(this, &EditorNode::_check_system_theme_changed));
  6702. add_child(system_theme_timer);
  6703. system_theme_timer->set_owner(get_owner());
  6704. system_theme_timer->set_autostart(true);
  6705. }
  6706. EditorNode::~EditorNode() {
  6707. EditorInspector::cleanup_plugins();
  6708. EditorTranslationParser::get_singleton()->clean_parsers();
  6709. ResourceImporterScene::clean_up_importer_plugins();
  6710. EditorContextMenuPluginManager::cleanup();
  6711. remove_print_handler(&print_handler);
  6712. EditorHelp::cleanup_doc();
  6713. #if defined(MODULE_GDSCRIPT_ENABLED) || defined(MODULE_MONO_ENABLED)
  6714. EditorHelpHighlighter::free_singleton();
  6715. #endif
  6716. memdelete(editor_selection);
  6717. memdelete(editor_plugins_over);
  6718. memdelete(editor_plugins_force_over);
  6719. memdelete(editor_plugins_force_input_forwarding);
  6720. memdelete(progress_hb);
  6721. memdelete(surface_upgrade_tool);
  6722. memdelete(editor_dock_manager);
  6723. EditorSettings::destroy();
  6724. EditorThemeManager::finalize();
  6725. GDExtensionEditorPlugins::editor_node_add_plugin = nullptr;
  6726. GDExtensionEditorPlugins::editor_node_remove_plugin = nullptr;
  6727. FileDialog::get_icon_func = nullptr;
  6728. FileDialog::register_func = nullptr;
  6729. FileDialog::unregister_func = nullptr;
  6730. EditorFileDialog::get_icon_func = nullptr;
  6731. EditorFileDialog::register_func = nullptr;
  6732. EditorFileDialog::unregister_func = nullptr;
  6733. file_dialogs.clear();
  6734. editor_file_dialogs.clear();
  6735. singleton = nullptr;
  6736. }
  6737. /*
  6738. * EDITOR PLUGIN LIST
  6739. */
  6740. void EditorPluginList::make_visible(bool p_visible) {
  6741. for (int i = 0; i < plugins_list.size(); i++) {
  6742. plugins_list[i]->make_visible(p_visible);
  6743. }
  6744. }
  6745. void EditorPluginList::edit(Object *p_object) {
  6746. for (int i = 0; i < plugins_list.size(); i++) {
  6747. plugins_list[i]->edit(p_object);
  6748. }
  6749. }
  6750. bool EditorPluginList::forward_gui_input(const Ref<InputEvent> &p_event) {
  6751. bool discard = false;
  6752. for (int i = 0; i < plugins_list.size(); i++) {
  6753. if (plugins_list[i]->forward_canvas_gui_input(p_event)) {
  6754. discard = true;
  6755. }
  6756. }
  6757. return discard;
  6758. }
  6759. EditorPlugin::AfterGUIInput EditorPluginList::forward_3d_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event, bool serve_when_force_input_enabled) {
  6760. EditorPlugin::AfterGUIInput after = EditorPlugin::AFTER_GUI_INPUT_PASS;
  6761. for (int i = 0; i < plugins_list.size(); i++) {
  6762. if ((!serve_when_force_input_enabled) && plugins_list[i]->is_input_event_forwarding_always_enabled()) {
  6763. continue;
  6764. }
  6765. EditorPlugin::AfterGUIInput current_after = plugins_list[i]->forward_3d_gui_input(p_camera, p_event);
  6766. if (current_after == EditorPlugin::AFTER_GUI_INPUT_STOP) {
  6767. after = EditorPlugin::AFTER_GUI_INPUT_STOP;
  6768. }
  6769. if (after != EditorPlugin::AFTER_GUI_INPUT_STOP && current_after == EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  6770. after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
  6771. }
  6772. }
  6773. return after;
  6774. }
  6775. void EditorPluginList::forward_canvas_draw_over_viewport(Control *p_overlay) {
  6776. for (int i = 0; i < plugins_list.size(); i++) {
  6777. plugins_list[i]->forward_canvas_draw_over_viewport(p_overlay);
  6778. }
  6779. }
  6780. void EditorPluginList::forward_canvas_force_draw_over_viewport(Control *p_overlay) {
  6781. for (int i = 0; i < plugins_list.size(); i++) {
  6782. plugins_list[i]->forward_canvas_force_draw_over_viewport(p_overlay);
  6783. }
  6784. }
  6785. void EditorPluginList::forward_3d_draw_over_viewport(Control *p_overlay) {
  6786. for (int i = 0; i < plugins_list.size(); i++) {
  6787. plugins_list[i]->forward_3d_draw_over_viewport(p_overlay);
  6788. }
  6789. }
  6790. void EditorPluginList::forward_3d_force_draw_over_viewport(Control *p_overlay) {
  6791. for (int i = 0; i < plugins_list.size(); i++) {
  6792. plugins_list[i]->forward_3d_force_draw_over_viewport(p_overlay);
  6793. }
  6794. }
  6795. void EditorPluginList::add_plugin(EditorPlugin *p_plugin) {
  6796. ERR_FAIL_COND(plugins_list.has(p_plugin));
  6797. plugins_list.push_back(p_plugin);
  6798. }
  6799. void EditorPluginList::remove_plugin(EditorPlugin *p_plugin) {
  6800. plugins_list.erase(p_plugin);
  6801. }
  6802. bool EditorPluginList::is_empty() {
  6803. return plugins_list.is_empty();
  6804. }
  6805. void EditorPluginList::clear() {
  6806. plugins_list.clear();
  6807. }
  6808. EditorPluginList::EditorPluginList() {
  6809. }
  6810. EditorPluginList::~EditorPluginList() {
  6811. }