level_editor.vala 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623
  1. /*
  2. * Copyright (c) 2012-2025 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. #if CROWN_PLATFORM_WINDOWS
  6. extern uint GetCurrentProcessId();
  7. extern uintptr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
  8. #elif CROWN_PLATFORM_LINUX
  9. extern Posix.pid_t getpid();
  10. #endif
  11. namespace Crown
  12. {
  13. const int WINDOW_DEFAULT_WIDTH = 1280;
  14. const int WINDOW_DEFAULT_HEIGHT = 720;
  15. const string CROWN_EDITOR_NAME = "Crown Editor";
  16. const string CROWN_EDITOR_ICON_NAME = "org.crownengine.Crown";
  17. const string CROWN_SUBPROCESS_LAUNCHER = "org.crownengine.SubprocessLauncher";
  18. public const string PANEL_WAITING = "panel-waiting";
  19. public const string PANEL_EDITOR = "panel-editor";
  20. public const string PANEL_PROJECTS_LIST = "panel-projects-list";
  21. public const string PANEL_NEW_PROJECT = "panel-new-project";
  22. public enum Theme
  23. {
  24. DARK,
  25. LIGHT,
  26. COUNT
  27. }
  28. public enum ToolType
  29. {
  30. PLACE,
  31. MOVE,
  32. ROTATE,
  33. SCALE,
  34. COUNT
  35. }
  36. public enum SnapMode
  37. {
  38. RELATIVE,
  39. ABSOLUTE
  40. }
  41. public enum ReferenceSystem
  42. {
  43. LOCAL,
  44. WORLD
  45. }
  46. public enum CameraViewType
  47. {
  48. PERSPECTIVE,
  49. FRONT,
  50. BACK,
  51. RIGHT,
  52. LEFT,
  53. TOP,
  54. BOTTOM,
  55. COUNT;
  56. public string to_label()
  57. {
  58. switch (this) {
  59. case PERSPECTIVE:
  60. return "Perspective";
  61. case FRONT:
  62. return "View Front";
  63. case BACK:
  64. return "View Back";
  65. case RIGHT:
  66. return "View Right";
  67. case LEFT:
  68. return "View Left";
  69. case TOP:
  70. return "View Top";
  71. case BOTTOM:
  72. return "View Bottom";
  73. default:
  74. return "View Unknown";
  75. }
  76. }
  77. }
  78. public enum TargetConfig
  79. {
  80. RELEASE,
  81. DEVELOPMENT,
  82. DEBUG,
  83. COUNT;
  84. public string to_key()
  85. {
  86. switch (this) {
  87. case RELEASE:
  88. return "release";
  89. case DEVELOPMENT:
  90. return "development";
  91. case DEBUG:
  92. return "debug";
  93. default:
  94. return "unknown";
  95. }
  96. }
  97. public string to_label()
  98. {
  99. switch (this) {
  100. case RELEASE:
  101. return "Release";
  102. case DEVELOPMENT:
  103. return "Development";
  104. case DEBUG:
  105. return "Debug";
  106. default:
  107. return "unknown";
  108. }
  109. }
  110. }
  111. public enum TargetPlatform
  112. {
  113. ANDROID,
  114. HTML5,
  115. LINUX,
  116. WINDOWS,
  117. COUNT;
  118. public string to_key()
  119. {
  120. switch (this) {
  121. case ANDROID:
  122. return "android";
  123. case HTML5:
  124. return "html5";
  125. case LINUX:
  126. return "linux";
  127. case WINDOWS:
  128. return "windows";
  129. default:
  130. return "unknown";
  131. }
  132. }
  133. public string to_label()
  134. {
  135. switch (this) {
  136. case ANDROID:
  137. return "Android";
  138. case HTML5:
  139. return "HTML5";
  140. case LINUX:
  141. return "Linux";
  142. case WINDOWS:
  143. return "Windows";
  144. default:
  145. return "Unknown";
  146. }
  147. }
  148. }
  149. public enum TargetArch
  150. {
  151. X86,
  152. X64,
  153. ARM,
  154. ARM64,
  155. WASM
  156. }
  157. public class RuntimeInstance
  158. {
  159. public string _name;
  160. public uint32 _process_id;
  161. public uint _revision;
  162. public GLib.SourceFunc _stop_callback;
  163. public GLib.SourceFunc _refresh_callback;
  164. public bool _refresh_success;
  165. public ConsoleClient _client;
  166. public signal void connected(RuntimeInstance ri, string address, int port);
  167. public signal void disconnected(RuntimeInstance ri);
  168. public signal void disconnected_unexpected(RuntimeInstance ri);
  169. public signal void message_received(RuntimeInstance ri, ConsoleClient client, uint8[] json);
  170. public RuntimeInstance(string name)
  171. {
  172. _name = name;
  173. _process_id = uint32.MAX;
  174. _revision = 0;
  175. _stop_callback = null;
  176. _refresh_callback = null;
  177. _refresh_success = false;
  178. _client = new ConsoleClient();
  179. _client.connected.connect(on_client_connected);
  180. _client.message_received.connect(on_client_message_received);
  181. }
  182. public void on_client_connected(string address, int port)
  183. {
  184. connected(this, address, port);
  185. }
  186. public void on_client_disconnected()
  187. {
  188. disconnected(this);
  189. if (_stop_callback != null)
  190. _stop_callback();
  191. }
  192. public void on_client_disconnected_unexpected()
  193. {
  194. disconnected_unexpected(this);
  195. try {
  196. if (_process_id != uint32.MAX) {
  197. _subprocess_launcher.wait(_process_id);
  198. _process_id = uint32.MAX;
  199. }
  200. } catch (GLib.Error e) {
  201. loge(e.message);
  202. }
  203. }
  204. public void on_client_message_received(ConsoleClient client, uint8[] json)
  205. {
  206. message_received(this, client, json);
  207. }
  208. // Tries to connect to the @a client. Return the number of tries after
  209. // it succeeded or @a num_tries if failed.
  210. public async int connect_async(string address, int port, int num_tries, int interval)
  211. {
  212. // It is an error if the client disconnects after here.
  213. _client.disconnected.disconnect(on_client_disconnected);
  214. _client.disconnected.connect(on_client_disconnected_unexpected);
  215. // Try to connect to the client.
  216. int tries;
  217. for (tries = 0; tries < num_tries; ++tries) {
  218. _client.connect(address, port);
  219. if (_client.is_connected())
  220. break;
  221. GLib.Thread.usleep(interval*1000);
  222. }
  223. return tries;
  224. }
  225. public async void stop()
  226. {
  227. if (_client != null) {
  228. // Reset "disconnected" signal.
  229. _client.disconnected.disconnect(on_client_disconnected);
  230. _client.disconnected.disconnect(on_client_disconnected_unexpected);
  231. // Explicit call to this function should not produce error messages.
  232. _client.disconnected.connect(on_client_disconnected);
  233. if (_client.is_connected()) {
  234. _stop_callback = stop.callback;
  235. _client.send(RuntimeApi.quit());
  236. yield; // Wait for _client to disconnect.
  237. _stop_callback = null;
  238. }
  239. }
  240. try {
  241. if (_process_id != uint32.MAX)
  242. _subprocess_launcher.wait(_process_id);
  243. _process_id = uint32.MAX;
  244. } catch (GLib.Error e) {
  245. loge(e.message);
  246. }
  247. }
  248. public void send(string json)
  249. {
  250. _client.send(json);
  251. }
  252. public void send_script(string lua)
  253. {
  254. _client.send_script(lua);
  255. }
  256. public bool is_connected()
  257. {
  258. return _client.is_connected();
  259. }
  260. public async bool refresh(DataCompiler dc)
  261. {
  262. if (_refresh_callback != null)
  263. return false;
  264. if (!is_connected())
  265. return false;
  266. var compiler_revision = dc._revision;
  267. var refresh_list = yield dc.refresh_list(_revision);
  268. _client.send(DeviceApi.refresh(refresh_list));
  269. _client.send(DeviceApi.frame());
  270. _refresh_callback = refresh.callback;
  271. yield; // Wait for client to refresh the resources.
  272. if (_refresh_success)
  273. _revision = compiler_revision;
  274. return _refresh_success;
  275. }
  276. public void refresh_finished(bool success)
  277. {
  278. _refresh_success = success;
  279. if (_refresh_callback != null)
  280. _refresh_callback();
  281. _refresh_callback = null;
  282. }
  283. }
  284. const string BACKEND_STOPPING = "backend-stopping";
  285. const string COMPILER_CRASHED = "compiler-crashed";
  286. const string COMPILER_COMPILING_DATA = "compiler-compiling-data";
  287. const string COMPILER_FAILED_COMPILATION = "compiler-failed-compilation";
  288. const string COMPILER_CONNECTING = "compiler-connecting";
  289. Gtk.Stack make_compiler_stack(Gtk.Widget child)
  290. {
  291. Gtk.Stack stack = new Gtk.Stack();
  292. stack.add_named(stopping_backend(), BACKEND_STOPPING);
  293. stack.add_named(compiling_data(), COMPILER_COMPILING_DATA);
  294. stack.add_named(connecting_to_data_compiler(), COMPILER_CONNECTING);
  295. stack.add_named(compiler_crashed(), COMPILER_CRASHED);
  296. stack.add_named(compiler_failed_compilation(), COMPILER_FAILED_COMPILATION);
  297. stack.add_named(child, "child");
  298. return stack;
  299. }
  300. public class LevelEditorWindow : Gtk.ApplicationWindow
  301. {
  302. public const GLib.ActionEntry[] action_entries =
  303. {
  304. { "fullscreen", on_fullscreen, null, null }
  305. };
  306. public bool _fullscreen;
  307. public LevelEditorWindow(Gtk.Application app, Gtk.HeaderBar header_bar)
  308. {
  309. Object(application: app);
  310. this.add_action_entries(action_entries, this);
  311. this.set_titlebar(header_bar);
  312. this.title = CROWN_EDITOR_NAME;
  313. this.window_state_event.connect(this.on_window_state_event);
  314. this.delete_event.connect(this.on_delete_event);
  315. _fullscreen = false;
  316. this.set_default_size(WINDOW_DEFAULT_WIDTH, WINDOW_DEFAULT_HEIGHT);
  317. }
  318. public void on_fullscreen(GLib.SimpleAction action, GLib.Variant? param)
  319. {
  320. if (_fullscreen)
  321. unfullscreen();
  322. else
  323. fullscreen();
  324. }
  325. public bool on_window_state_event(Gdk.EventWindowState ev)
  326. {
  327. _fullscreen = (ev.new_window_state & Gdk.WindowState.FULLSCREEN) != 0;
  328. return Gdk.EVENT_PROPAGATE;
  329. }
  330. public bool on_delete_event()
  331. {
  332. GLib.Application.get_default().activate_action("quit", null);
  333. return Gdk.EVENT_STOP; // Keep window alive.
  334. }
  335. public Hashtable encode()
  336. {
  337. Hashtable json_obj = new Hashtable();
  338. // This is the appropriate size to save, see:
  339. // https://valadoc.org/gtk+-3.0/Gtk.Window.set_default_size.html
  340. int width;
  341. int height;
  342. this.get_size(out width, out height);
  343. json_obj["width"] = width;
  344. json_obj["height"] = height;
  345. json_obj["maximized"] = this.is_maximized;
  346. json_obj["fullscreen"] = this._fullscreen;
  347. return json_obj;
  348. }
  349. public void decode(Hashtable json_obj)
  350. {
  351. if (json_obj.has_key("width"))
  352. this.default_width = (int)(double)json_obj["width"];
  353. else
  354. this.default_width = WINDOW_DEFAULT_WIDTH;
  355. if (json_obj.has_key("height"))
  356. this.default_height = (int)(double)json_obj["height"];
  357. else
  358. this.default_height = WINDOW_DEFAULT_HEIGHT;
  359. if (json_obj.has_key("maximized")) {
  360. if ((bool)json_obj["maximized"])
  361. this.maximize();
  362. else
  363. this.unmaximize();
  364. }
  365. if (json_obj.has_key("fullscreen")) {
  366. if ((bool)json_obj["fullscreen"])
  367. this.fullscreen();
  368. else
  369. this.unfullscreen();
  370. }
  371. }
  372. }
  373. public enum StartGame
  374. {
  375. NORMAL,
  376. TEST
  377. }
  378. public class LevelEditorApplication : Gtk.Application
  379. {
  380. public const GLib.ActionEntry[] action_entries_file =
  381. {
  382. // parameter type
  383. // name activate() | state
  384. // | | | |
  385. { "menu-file", null, null, null },
  386. { "new-level", on_new_level, null, null },
  387. { "open-level", on_open_level, "s", null },
  388. { "new-project", on_new_project, null, null },
  389. { "add-project", on_add_project, null, null },
  390. { "remove-project", on_remove_project, "s", null },
  391. { "open-project", on_open_project, "(ss)", null },
  392. { "open-project-null", on_open_project, null, null },
  393. { "open-projects-list", on_open_projects_list, null, null },
  394. { "save", on_save, null, null },
  395. { "save-as", on_save_as, null, null },
  396. { "import", on_import, "(sas)", null },
  397. { "import-null", on_import, null, null },
  398. { "preferences", on_preferences, null, null },
  399. { "deploy", on_deploy, null, null },
  400. { "close-project", on_close_project, null, null },
  401. { "quit", on_quit, null, null },
  402. { "open-resource", on_open_resource, "s", null },
  403. { "copy-path", on_copy_path, "s", null },
  404. { "copy-name", on_copy_name, "s", null },
  405. };
  406. public const GLib.ActionEntry[] action_entries_edit =
  407. {
  408. { "menu-edit", null, null, null },
  409. { "rename", on_rename, "(ss)", null },
  410. { "tool", on_tool, "i", "1" }, // See: Crown.ToolType
  411. { "set-placeable", on_set_placeable, "(ss)", null },
  412. { "cancel-place", on_cancel_place, null, null },
  413. { "snap", on_snap, "i", "0" }, // See: Crown.SnapMode
  414. { "reference-system", on_reference_system, "i", "0" }, // See: Crown.ReferenceSystem
  415. { "snap-to-grid", on_snap_to_grid, null, "false" },
  416. { "menu-grid", null, null, null },
  417. { "grid-show", on_show_grid, null, "true" },
  418. { "grid-size", on_grid_size, "i", "10" }, // 10*meters.
  419. { "menu-rotation-snap", null, null, null },
  420. { "rotation-snap-size", on_rotation_snap_size, "i", "15" }
  421. };
  422. public const GLib.ActionEntry[] action_entries_create =
  423. {
  424. { "menu-create", null, null, null },
  425. { "menu-primitives", null, null, null },
  426. { "primitive-cube", on_spawn_primitive, null, null },
  427. { "primitive-sphere", on_spawn_primitive, null, null },
  428. { "primitive-cone", on_spawn_primitive, null, null },
  429. { "primitive-cylinder", on_spawn_primitive, null, null },
  430. { "primitive-plane", on_spawn_primitive, null, null },
  431. { "camera", on_spawn_primitive, null, null },
  432. { "light", on_spawn_primitive, null, null },
  433. { "sound-source", on_spawn_primitive, null, null },
  434. { "unit-empty", on_spawn_unit, null, null },
  435. { "shading-environment",on_spawn_unit, null, null },
  436. };
  437. public const GLib.ActionEntry[] action_entries_camera =
  438. {
  439. { "menu-camera", null, null, null },
  440. { "camera-frame-all", on_camera_frame_all, null, null }
  441. };
  442. public const GLib.ActionEntry[] action_entries_view =
  443. {
  444. { "menu-view", null, null, null },
  445. { "project-browser", on_project_browser, null, null },
  446. { "console", on_console, null, null },
  447. { "statusbar", on_statusbar, null, null },
  448. { "inspector", on_inspector, null, null },
  449. { "debug-render-world", on_debug_render_world, null, "false" },
  450. { "debug-physics-world", on_debug_physics_world, null, "false" }
  451. };
  452. public const GLib.ActionEntry[] action_entries_debug =
  453. {
  454. { "menu-debug", null, null, null },
  455. { "test-level", on_run_game, null, null },
  456. { "run-game", on_run_game, null, null },
  457. { "build-data", on_build_data, null, null },
  458. { "reload-all", on_reload_all, null, null },
  459. { "restart-backend", on_restart_backend, null, null },
  460. { "restart-editor-view", on_restart_editor_view, null, null }
  461. };
  462. public const GLib.ActionEntry[] action_entries_help =
  463. {
  464. { "menu-help", null, null, null },
  465. { "manual", on_manual, null, null },
  466. { "report-issue", on_report_issue, null, null },
  467. { "browse-logs", on_browse_logs, null, null },
  468. { "changelog", on_changelog, null, null },
  469. { "donate", on_donate, null, null },
  470. { "credits", on_credits, null, null }
  471. };
  472. public const GLib.ActionEntry[] action_entries_project =
  473. {
  474. { "delete-file", on_delete_file, "s", null },
  475. { "delete-directory", on_delete_directory, "s", null },
  476. { "create-directory", on_create_directory, "(ss)", null },
  477. { "create-script", on_create_script, "(ssb)", null },
  478. { "create-unit", on_create_unit, "(ss)", null },
  479. { "create-state-machine", on_create_state_machine, "(sss)", null },
  480. { "create-material", on_create_material, "(ss)", null },
  481. { "open-containing", on_open_containing, "s", null },
  482. { "texture-settings", on_texture_settings, "s", null },
  483. { "state-machine-editor", on_state_machine_editor, "s", null },
  484. { "open-object", on_open_object, "(ss)", null },
  485. { "reveal-resource", on_reveal, "(ss)", null },
  486. };
  487. public const GLib.ActionEntry[] action_entries_package =
  488. {
  489. { "create-package-android", on_create_package_android, "(sississsssi)", null },
  490. { "create-package-html5", on_create_package_html5, "(sis)", null },
  491. { "create-package-linux", on_create_package_linux, "(sis)", null },
  492. { "create-package-windows", on_create_package_windows, "(sis)", null }
  493. };
  494. public const GLib.ActionEntry[] action_entries_unit =
  495. {
  496. { "unit-save-as-prefab", on_unit_save_as_prefab, "(ss)", null },
  497. { "open-unit", on_open_unit, "s", null },
  498. };
  499. // Command line options
  500. public uint _launcher_watch_id;
  501. public string? _source_dir = null;
  502. public string _level_resource = "";
  503. public User _user;
  504. public Hashtable _settings;
  505. public Hashtable _window_state;
  506. // Editor state
  507. public double _grid_size;
  508. public double _rotation_snap;
  509. public bool _show_grid;
  510. public bool _snap_to_grid;
  511. public bool _debug_render_world;
  512. public bool _debug_physics_world;
  513. public ToolType _tool_type;
  514. public ToolType _tool_type_prev;
  515. public SnapMode _snap_mode;
  516. public ReferenceSystem _reference_system;
  517. // Project state
  518. public string _placeable_type;
  519. public string _placeable_name;
  520. // Accelerators
  521. public string[] _tool_place_accels;
  522. public string[] _tool_move_accels;
  523. public string[] _tool_rotate_accels;
  524. public string[] _tool_scale_accels;
  525. public string[] _delete_accels;
  526. public string[] _camera_view_perspective_accels;
  527. public string[] _camera_view_front_accels;
  528. public string[] _camera_view_back_accels;
  529. public string[] _camera_view_right_accels;
  530. public string[] _camera_view_left_accels;
  531. public string[] _camera_view_top_accels;
  532. public string[] _camera_view_bottom_accels;
  533. public string[] _camera_frame_selected_accels;
  534. public string[] _camera_frame_all_accels;
  535. // Engine connections
  536. public Gee.ArrayList<RuntimeInstance> _runtimes;
  537. public RuntimeInstance _compiler;
  538. public RuntimeInstance _editor;
  539. public RuntimeInstance _game;
  540. public RuntimeInstance _thumbnail;
  541. // Level data
  542. public DatabaseEditor _database_editor;
  543. public Database _database;
  544. public Project _project;
  545. public ProjectStore _project_store;
  546. public Level _level;
  547. public DataCompiler _data_compiler;
  548. // Widgets
  549. public Gtk.CssProvider _css_provider;
  550. public ProjectBrowser _project_browser;
  551. public EditorViewport _editor_viewport;
  552. public LevelTreeView _level_treeview;
  553. public LevelLayersTreeView _level_layers_treeview;
  554. public PropertiesView _properties_view;
  555. public PreferencesDialog _preferences_dialog;
  556. public DeployDialog _deploy_dialog;
  557. public TextureSettingsDialog _texture_settings_dialog;
  558. public UnitEditor _unit_editor_dialog;
  559. public StateMachineEditor _state_machine_editor;
  560. public ObjectEditor _object_editor;
  561. public ThumbnailCache _thumbnail_cache;
  562. public Gtk.Stack _project_stack;
  563. public Gtk.Stack _editor_stack;
  564. public Gtk.Stack _inspector_stack;
  565. public Toolbar _toolbar;
  566. public Gtk.Image _game_run_stop_image;
  567. public Gtk.Button _game_run;
  568. public Gtk.Notebook _level_tree_view_notebook;
  569. public Gtk.Notebook _console_notebook;
  570. public Gtk.Notebook _project_notebook;
  571. public Gtk.Notebook _inspector_notebook;
  572. public Gtk.Paned _editor_pane;
  573. public Gtk.Paned _content_pane;
  574. public Gtk.Paned _inspector_pane;
  575. public Gtk.Paned _main_pane;
  576. public Statusbar _statusbar;
  577. public Gtk.Box _main_vbox;
  578. public Gtk.FileFilter _file_filter;
  579. public Gtk.ComboBoxText _combo;
  580. public NewProject _new_project;
  581. public ProjectsList _projects_list;
  582. public Gtk.Stack _main_stack;
  583. public Gtk.HeaderBar _header_bar;
  584. public LevelEditorWindow _level_editor_window;
  585. public uint _save_timer_id;
  586. public signal void ui_read_selection(Guid?[] selection);
  587. public LevelEditorApplication()
  588. {
  589. Object(application_id: "org.crownengine.Crown"
  590. , flags: GLib.ApplicationFlags.FLAGS_NONE
  591. );
  592. GLib.Environment.set_prgname(this.application_id); // FIXME: Drop after GTK4 port.
  593. }
  594. public Theme theme_name_to_enum(string theme)
  595. {
  596. if (theme == "dark")
  597. return Theme.DARK;
  598. else if (theme == "light")
  599. return Theme.LIGHT;
  600. else
  601. return Theme.COUNT;
  602. }
  603. public void set_theme_from_name(string theme_name)
  604. {
  605. Theme theme = theme_name_to_enum(theme_name);
  606. set_theme(theme);
  607. }
  608. public void set_theme(Theme theme)
  609. {
  610. if (theme == Theme.COUNT)
  611. return;
  612. string css = "/org/crownengine/Crown/ui/style-%s.css".printf(theme == Theme.DARK ? "dark" : "light");
  613. _css_provider.load_from_resource(css);
  614. }
  615. public override void startup()
  616. {
  617. base.startup();
  618. Intl.setlocale(LocaleCategory.ALL, "C");
  619. _css_provider = new Gtk.CssProvider();
  620. var default_screen = Gdk.Display.get_default().get_default_screen();
  621. Gtk.StyleContext.add_provider_for_screen(default_screen
  622. , _css_provider
  623. , Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
  624. );
  625. try {
  626. _settings = SJSON.load_from_path(_settings_file.get_path());
  627. } catch (JsonSyntaxError e) {
  628. loge(e.message);
  629. }
  630. try {
  631. _window_state = SJSON.load_from_path(_window_state_file.get_path());
  632. } catch (JsonSyntaxError e) {
  633. loge(e.message);
  634. }
  635. this.add_action_entries(action_entries_file, this);
  636. this.add_action_entries(action_entries_edit, this);
  637. this.add_action_entries(action_entries_create, this);
  638. this.add_action_entries(action_entries_camera, this);
  639. this.add_action_entries(action_entries_view, this);
  640. this.add_action_entries(action_entries_debug, this);
  641. this.add_action_entries(action_entries_help, this);
  642. this.add_action_entries(action_entries_project, this);
  643. this.add_action_entries(action_entries_package, this);
  644. this.add_action_entries(action_entries_unit, this);
  645. this.set_accels_for_action("app.new-level", { "<Primary>N" });
  646. this.set_accels_for_action("app.open-level", new string[] { "<Primary>O" });
  647. this.set_accels_for_action("app.save", new string[] { "<Primary>S" });
  648. this.set_accels_for_action("app.save-as", new string[] { "<Shift><Primary>S" });
  649. this.set_accels_for_action("app.import-null", new string[] { "<Primary>I" });
  650. this.set_accels_for_action("app.close-project", new string[] { "<Primary>W" });
  651. this.set_accels_for_action("app.quit", new string[] { "<Primary>Q" });
  652. this.set_accels_for_action("database.undo", new string[] { "<Primary>Z" });
  653. this.set_accels_for_action("database.redo", new string[] { "<Shift><Primary>Z" });
  654. this.set_accels_for_action("database.duplicate", new string[] { "<Primary>D" });
  655. this.set_accels_for_action("database.delete", new string[] { "Delete" });
  656. this.set_accels_for_action("app.tool(0)", new string[] { "Q" });
  657. this.set_accels_for_action("app.tool(1)", new string[] { "W" });
  658. this.set_accels_for_action("app.tool(2)", new string[] { "E" });
  659. this.set_accels_for_action("app.tool(3)", new string[] { "R" });
  660. this.set_accels_for_action("app.grid-size(0)", new string[] { "<Primary>G" });
  661. this.set_accels_for_action("app.rotation-snap-size(0)", new string[] { "<Primary>H" });
  662. this.set_accels_for_action("viewport.camera-view(0)", new string[] { "KP_5" });
  663. this.set_accels_for_action("viewport.camera-view(1)", new string[] { "KP_1" });
  664. this.set_accels_for_action("viewport.camera-view(2)", new string[] { "<Primary>KP_1" });
  665. this.set_accels_for_action("viewport.camera-view(3)", new string[] { "KP_3" });
  666. this.set_accels_for_action("viewport.camera-view(4)", new string[] { "<Primary>KP_3" });
  667. this.set_accels_for_action("viewport.camera-view(5)", new string[] { "KP_7" });
  668. this.set_accels_for_action("viewport.camera-view(6)", new string[] { "<Primary>KP_7" });
  669. this.set_accels_for_action("viewport.camera-frame-selected", new string[] { "F" });
  670. this.set_accels_for_action("app.camera-frame-all", new string[] { "A" });
  671. this.set_accels_for_action("app.console", new string[] { "<Primary>grave" });
  672. this.set_accels_for_action("win.fullscreen", new string[] { "F11" });
  673. this.set_accels_for_action("app.test-level", new string[] { "F5" });
  674. this.set_accels_for_action("app.build-data", new string[] { "<Primary>B" });
  675. this.set_accels_for_action("app.reload-all", new string[] { "F7" });
  676. this.set_accels_for_action("app.manual", new string[] { "F1" });
  677. _tool_place_accels = this.get_accels_for_action("app.tool(0)");
  678. _tool_move_accels = this.get_accels_for_action("app.tool(1)");
  679. _tool_rotate_accels = this.get_accels_for_action("app.tool(2)");
  680. _tool_scale_accels = this.get_accels_for_action("app.tool(3)");
  681. _delete_accels = this.get_accels_for_action("app.delete");
  682. _camera_view_perspective_accels = this.get_accels_for_action("viewport.camera-view(0)");
  683. _camera_view_front_accels = this.get_accels_for_action("viewport.camera-view(1)");
  684. _camera_view_back_accels = this.get_accels_for_action("viewport.camera-view(2)");
  685. _camera_view_right_accels = this.get_accels_for_action("viewport.camera-view(3)");
  686. _camera_view_left_accels = this.get_accels_for_action("viewport.camera-view(4)");
  687. _camera_view_top_accels = this.get_accels_for_action("viewport.camera-view(5)");
  688. _camera_view_bottom_accels = this.get_accels_for_action("viewport.camera-view(6)");
  689. _camera_frame_selected_accels = this.get_accels_for_action("viewport.camera-frame-selected");
  690. _camera_frame_all_accels = this.get_accels_for_action("app.camera-frame-all");
  691. _runtimes = new Gee.ArrayList<RuntimeInstance>();
  692. _compiler = new RuntimeInstance("data_compiler");
  693. _compiler.message_received.connect(on_message_received);
  694. _compiler.connected.connect(on_runtime_connected);
  695. _compiler.disconnected.connect(on_runtime_disconnected);
  696. _compiler.disconnected_unexpected.connect(on_data_compiler_disconnected_unexpected);
  697. _data_compiler = new DataCompiler(_compiler);
  698. _data_compiler.start.connect(on_data_compiler_start);
  699. _data_compiler.finished.connect(on_data_compiler_finished);
  700. _project = new Project();
  701. _project.set_toolchain_dir(_toolchain_dir.get_path());
  702. _project.register_importer("Sprite", { "png" }, SpriteResource.import, on_import_result, 0.0);
  703. _project.register_importer("Mesh", { "mesh", "fbx" }, MeshResource.import, on_import_result, 1.0);
  704. _project.register_importer("Sound", { "wav", "ogg" }, SoundResource.import, on_import_result, 2.0);
  705. _project.register_importer("Texture", { "dds", "exr", "jpg", "ktx", "png", "pvr", "tga", }, TextureResource.import, on_import_result, 2.0);
  706. _project.register_importer("Font", { "ttf", "otf" }, FontResource.import, on_import_result, 3.0);
  707. _project.project_reset.connect(on_project_reset);
  708. _project.project_loaded.connect(on_project_loaded);
  709. _preferences_dialog = new PreferencesDialog();
  710. _preferences_dialog.delete_event.connect(_preferences_dialog.hide_on_delete);
  711. _preferences_dialog.decode(_settings);
  712. _database_editor = new DatabaseEditor(_project, (uint)_preferences_dialog._undo_redo_max_size.value * 1024 * 1024);
  713. _database_editor.undo.connect((id) => { _statusbar.set_temporary_message("Undo: " + ActionNames[id]); });
  714. _database_editor.redo.connect((id) => { _statusbar.set_temporary_message("Redo: " + ActionNames[id]); });
  715. _database_editor.selection_changed.connect(on_selection_changed);
  716. _editor_viewport = new EditorViewport("editor"
  717. , _database_editor
  718. , _project
  719. , LEVEL_EDITOR_BOOT_DIR
  720. , EDITOR_ADDRESS
  721. , EDITOR_TCP_PORT
  722. );
  723. _editor = _editor_viewport._runtime;
  724. _editor.message_received.connect(on_message_received);
  725. _editor.connected.connect(on_editor_connected);
  726. _editor.disconnected.connect(on_runtime_disconnected);
  727. _editor.disconnected_unexpected.connect(on_editor_disconnected_unexpected);
  728. _runtimes.add(_editor);
  729. _preferences_dialog.set_runtime(_editor);
  730. set_theme_from_name(_preferences_dialog._theme_combo.value);
  731. _game = new RuntimeInstance("game");
  732. _game.message_received.connect(on_message_received);
  733. _game.connected.connect(on_game_connected);
  734. _game.disconnected.connect(on_game_disconnected);
  735. _game.disconnected_unexpected.connect(on_game_disconnected);
  736. _runtimes.add(_game);
  737. _thumbnail = new RuntimeInstance("thumbnail");
  738. _thumbnail.message_received.connect(on_message_received);
  739. _thumbnail.connected.connect(on_runtime_connected);
  740. _thumbnail.disconnected.connect(on_runtime_disconnected);
  741. _thumbnail.disconnected_unexpected.connect(on_runtime_disconnected_unexpected);
  742. _runtimes.add(_thumbnail);
  743. _database = _database_editor._database;
  744. _database.objects_created.connect(on_objects_created);
  745. _database.objects_destroyed.connect(on_objects_destroyed);
  746. _database.objects_changed.connect(on_objects_changed);
  747. _database.object_type_added.connect(on_object_type_added);
  748. _properties_view = new PropertiesView(_database_editor);
  749. create_object_types(_database);
  750. _properties_view.register_object_type(OBJECT_TYPE_UNIT, new UnitView(_database));
  751. _level = new Level(_database, _editor);
  752. // Editor state
  753. _grid_size = 1.0;
  754. _rotation_snap = 15.0;
  755. _show_grid = true;
  756. _snap_to_grid = false;
  757. _debug_render_world = false;
  758. _debug_physics_world = false;
  759. _tool_type = ToolType.MOVE;
  760. _tool_type_prev = _tool_type;
  761. _snap_mode = SnapMode.RELATIVE;
  762. _reference_system = ReferenceSystem.LOCAL;
  763. // Project state
  764. _placeable_type = "";
  765. _placeable_name = "";
  766. _project_store = new ProjectStore(_project);
  767. // Widgets
  768. _combo = new Gtk.ComboBoxText();
  769. _combo.append("editor", "Editor");
  770. _combo.append("game", "Game");
  771. _combo.set_active_id("editor");
  772. _combo.set_size_request(50, -1);
  773. _console_view = new ConsoleView(_project, _combo, _preferences_dialog);
  774. _thumbnail_cache = new ThumbnailCache(_project, _thumbnail, (uint)_preferences_dialog._thumbnail_cache_max_size.value * 1024 * 1024);
  775. _project_browser = new ProjectBrowser(_project_store, _thumbnail_cache);
  776. _level_treeview = new LevelTreeView(_database, _level);
  777. _level_treeview.selection_changed.connect(on_level_treeview_selection_changed);
  778. this.ui_read_selection.connect(_level_treeview.read_selection);
  779. this.ui_read_selection.connect(_properties_view.set_objects);
  780. _database.objects_created.connect(_level_treeview.on_objects_created);
  781. _database.objects_destroyed.connect(_level_treeview.on_objects_destroyed);
  782. _database.objects_changed.connect(_level_treeview.on_objects_changed);
  783. _level_layers_treeview = new LevelLayersTreeView(_database, _level);
  784. _level_tree_view_notebook = new Gtk.Notebook();
  785. _level_tree_view_notebook.show_border = false;
  786. _level_tree_view_notebook.append_page(_level_treeview, new Gtk.Image.from_icon_name("level-tree", Gtk.IconSize.SMALL_TOOLBAR));
  787. _level_tree_view_notebook.append_page(_level_layers_treeview, new Gtk.Image.from_icon_name("level-layers", Gtk.IconSize.SMALL_TOOLBAR));
  788. _inspector_notebook = new Gtk.Notebook();
  789. _inspector_notebook.show_border = false;
  790. _inspector_notebook.append_page(_properties_view, new Gtk.Label.with_mnemonic("Properties"));
  791. _inspector_pane = new Gtk.Paned(Gtk.Orientation.VERTICAL);
  792. _inspector_pane.pack1(_level_tree_view_notebook, true, false);
  793. _inspector_pane.pack2(_inspector_notebook, false, false);
  794. _project_stack = make_compiler_stack(_project_browser);
  795. _editor_stack = make_compiler_stack(_editor_viewport);
  796. _inspector_stack = make_compiler_stack(_inspector_pane);
  797. // Game run/stop button.
  798. _game_run_stop_image = new Gtk.Image.from_icon_name("game-run", Gtk.IconSize.MENU);
  799. _game_run_stop_image.margin_bottom
  800. = _game_run_stop_image.margin_end
  801. = _game_run_stop_image.margin_start
  802. = _game_run_stop_image.margin_top
  803. = 8
  804. ;
  805. _game_run = new Gtk.Button();
  806. _game_run.add(_game_run_stop_image);
  807. _game_run.get_style_context().add_class("suggested-action");
  808. _game_run.get_style_context().add_class("image-button");
  809. _game_run.action_name = "app.test-level";
  810. _game_run.can_focus = false;
  811. _toolbar = new Toolbar();
  812. _editor_viewport._overlay.add_overlay(_toolbar);
  813. _console_notebook = new Gtk.Notebook();
  814. _console_notebook.show_border = false;
  815. _console_notebook.append_page(_console_view, new Gtk.Label.with_mnemonic("Console"));
  816. _project_notebook = new Gtk.Notebook();
  817. _project_notebook.show_border = false;
  818. _project_notebook.append_page(_project_stack, new Gtk.Label.with_mnemonic("Project"));
  819. _content_pane = new Gtk.Paned(Gtk.Orientation.VERTICAL);
  820. _content_pane.pack1(_editor_stack, true, false);
  821. _content_pane.pack2(_console_notebook, false, false);
  822. _editor_pane = new Gtk.Paned(Gtk.Orientation.HORIZONTAL);
  823. _editor_pane.pack1(_project_notebook, false, false);
  824. _editor_pane.pack2(_content_pane, true, false);
  825. _main_pane = new Gtk.Paned(Gtk.Orientation.HORIZONTAL);
  826. _main_pane.pack1(_editor_pane, true, false);
  827. _main_pane.pack2(_inspector_stack, false, false);
  828. _statusbar = new Statusbar();
  829. _main_vbox = new Gtk.Box(Gtk.Orientation.VERTICAL, 0);
  830. _main_vbox.pack_start(_main_pane, true, true, 0);
  831. _main_vbox.pack_start(_statusbar, false, false, 0);
  832. _main_vbox.set_visible(true);
  833. _file_filter = new Gtk.FileFilter();
  834. _file_filter.set_filter_name("Level (*.level)");
  835. _file_filter.add_pattern("*.level");
  836. _user = new User();
  837. _new_project = new NewProject(_user, _project);
  838. _new_project.fill_templates_list(_templates_dir.get_path());
  839. _projects_list = new ProjectsList(_user);
  840. _projects_list.set_visible(true); // To make Gtk.Stack work...
  841. _main_stack = new Gtk.Stack();
  842. _main_stack.add_named(new Gtk.Label("Waiting for %s...".printf(CROWN_SUBPROCESS_LAUNCHER)), PANEL_WAITING);
  843. _main_stack.add_named(_projects_list, PANEL_PROJECTS_LIST);
  844. _main_stack.add_named(_new_project, PANEL_NEW_PROJECT);
  845. _main_stack.add_named(_main_vbox, PANEL_EDITOR);
  846. _header_bar = new Gtk.HeaderBar();
  847. _header_bar.show_close_button = true;
  848. _header_bar.has_subtitle = false;
  849. _header_bar.pack_start(_game_run);
  850. // Delete expired logs
  851. if (_preferences_dialog._log_delete_after_days.value != 0) {
  852. try {
  853. FileEnumerator enumerator = _logs_dir.enumerate_children("standard::*"
  854. , FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  855. );
  856. GLib.FileInfo info = null;
  857. while ((info = enumerator.next_file()) != null) {
  858. if (info.get_file_type() != GLib.FileType.REGULAR)
  859. continue; // Skip anything but regular files
  860. // Parse DateTime from log filename
  861. int year = 1970;
  862. int month = 1;
  863. int day = 1;
  864. if (info.get_name().scanf("%d-%d-%d.log", &year, &month, &day) != 3)
  865. continue; // Skip malformed filenames
  866. GLib.DateTime time_log = new GLib.DateTime.local(year, month, day, 0, 0, 0.0);
  867. if (time_log == null)
  868. continue; // Skip invalid dates
  869. GLib.DateTime time_now = new GLib.DateTime.now_local();
  870. if (time_now.difference(time_log) <= GLib.TimeSpan.DAY*_preferences_dialog._log_delete_after_days.value)
  871. continue; // Skip if date is within range
  872. // Delete
  873. GLib.File log_file = _logs_dir.resolve_relative_path(info.get_name());
  874. log_file.delete();
  875. }
  876. } catch (GLib.Error e) {
  877. loge(e.message);
  878. }
  879. }
  880. _user.load(_user_file.get_path());
  881. _console_view._entry_history.load(_console_history_file.get_path());
  882. show_panel(PANEL_WAITING);
  883. this.set_menubar(make_menubar());
  884. }
  885. public override void activate()
  886. {
  887. if (_level_editor_window == null) {
  888. _level_editor_window = new LevelEditorWindow(this, _header_bar);
  889. if (_window_state.has_key("level_editor_window"))
  890. _level_editor_window.decode((Hashtable)_window_state["level_editor_window"]);
  891. _level_editor_window.add(_main_stack);
  892. _level_editor_window.insert_action_group("viewport", _editor_viewport._action_group);
  893. _level_editor_window.insert_action_group("database", _database_editor._action_group);
  894. try {
  895. _level_editor_window.icon = Gtk.IconTheme.get_default().load_icon(CROWN_EDITOR_ICON_NAME, 256, 0);
  896. } catch (Error e) {
  897. loge(e.message);
  898. }
  899. }
  900. this.active_window.show_all();
  901. // Register a callback to be called when SubprocessLauncher service 'appears'.
  902. _launcher_watch_id = GLib.Bus.watch_name(GLib.BusType.SESSION
  903. , CROWN_SUBPROCESS_LAUNCHER
  904. , GLib.BusNameWatcherFlags.NONE
  905. , on_subprocess_launcher_appeared
  906. );
  907. }
  908. public void on_subprocess_launcher_appeared(GLib.DBusConnection connection, string name, string name_owner)
  909. {
  910. try {
  911. GLib.Bus.unwatch_name(_launcher_watch_id);
  912. // Connect to SubprocessLauncher service.
  913. _subprocess_launcher = GLib.Bus.get_proxy_sync(GLib.BusType.SESSION
  914. , CROWN_SUBPROCESS_LAUNCHER
  915. , "/org/crownengine/subprocess_launcher"
  916. );
  917. if (_source_dir == null) {
  918. show_panel(PANEL_PROJECTS_LIST);
  919. } else {
  920. show_panel(PANEL_EDITOR);
  921. restart_backend.begin();
  922. }
  923. } catch (IOError e) {
  924. loge(e.message);
  925. }
  926. }
  927. public override bool local_command_line(ref unowned string[] args, out int exit_status)
  928. {
  929. if (args.length > 1) {
  930. if (!GLib.FileUtils.test(args[1], FileTest.EXISTS) || !GLib.FileUtils.test(args[1], FileTest.IS_DIR)) {
  931. loge("Source directory does not exist or it is not a directory");
  932. exit_status = 1;
  933. return true;
  934. }
  935. _source_dir = args[1];
  936. }
  937. if (args.length > 2) {
  938. // Validation is done below after the Project object instantiation
  939. _level_resource = args[2];
  940. }
  941. exit_status = 0;
  942. return false;
  943. }
  944. public override int command_line(ApplicationCommandLine command_line)
  945. {
  946. this.activate();
  947. return 0;
  948. }
  949. public RuntimeInstance? current_selected_runtime()
  950. {
  951. if (_combo.get_active_id() == "editor")
  952. return _editor;
  953. else if (_combo.get_active_id() == "game")
  954. return _game;
  955. else
  956. return null;
  957. }
  958. public void on_runtime_connected(RuntimeInstance ri, string address, int port)
  959. {
  960. ri._revision = _data_compiler._revision;
  961. logi("Connected to %s@%s:%d".printf(ri._name, address, port));
  962. }
  963. public void on_runtime_disconnected(RuntimeInstance ri)
  964. {
  965. logi("Disconnected from %s".printf(ri._name));
  966. }
  967. public void on_runtime_disconnected_unexpected(RuntimeInstance ri)
  968. {
  969. logw("Disconnected from %s unexpectedly".printf(ri._name));
  970. }
  971. public async void on_data_compiler_disconnected_unexpected(RuntimeInstance ri)
  972. {
  973. on_runtime_disconnected_unexpected(ri);
  974. yield stop_heads();
  975. // Reset the callback
  976. _data_compiler.compile_finished(false, 0);
  977. _project_stack.set_visible_child_name(COMPILER_CRASHED);
  978. _editor_stack.set_visible_child_name(COMPILER_CRASHED);
  979. _inspector_stack.set_visible_child_name(COMPILER_CRASHED);
  980. }
  981. public void on_data_compiler_start()
  982. {
  983. _statusbar.set_status("Compiling data...");
  984. }
  985. public void on_data_compiler_finished(bool success)
  986. {
  987. _statusbar.clear_status();
  988. if (!success) {
  989. _statusbar.set_temporary_message("Failed to compile data");
  990. return;
  991. }
  992. _project.data_compiled();
  993. }
  994. public void on_editor_connected(RuntimeInstance ri, string address, int port)
  995. {
  996. on_runtime_connected(ri, address, port);
  997. // Update editor view with current editor state.
  998. _level.send_level();
  999. _database_editor.send_selection(_editor);
  1000. send_state();
  1001. _preferences_dialog.apply();
  1002. _editor.send(DeviceApi.frame());
  1003. }
  1004. public void on_editor_disconnected_unexpected(RuntimeInstance ri)
  1005. {
  1006. on_runtime_disconnected_unexpected(ri);
  1007. }
  1008. public void on_game_connected(RuntimeInstance ri, string address, int port)
  1009. {
  1010. on_runtime_connected(ri, address, port);
  1011. _combo.set_active_id("game");
  1012. }
  1013. public void on_game_disconnected(RuntimeInstance ri)
  1014. {
  1015. on_runtime_disconnected(ri);
  1016. _combo.set_active_id("editor");
  1017. _game_run_stop_image.set_from_icon_name("game-run", Gtk.IconSize.MENU);
  1018. }
  1019. public void on_message_received(RuntimeInstance ri, ConsoleClient client, uint8[] json)
  1020. {
  1021. try {
  1022. Hashtable msg = JSON.decode(json) as Hashtable;
  1023. handle_message(ri, client, (string)msg["type"], msg);
  1024. } catch (JsonSyntaxError e) {
  1025. loge(e.message);
  1026. }
  1027. }
  1028. public void handle_message(RuntimeInstance ri, ConsoleClient client, string msg_type, Hashtable msg)
  1029. {
  1030. if (msg_type == "message") {
  1031. string system = ri._name + ": " + (string)msg["system"];
  1032. log(system, (string)msg["severity"], (string)msg["message"]);
  1033. } else if (msg_type == "add_file") {
  1034. string path = (string)msg["path"];
  1035. uint64 size = uint64.parse((string)msg["size"]);
  1036. uint64 mtime = uint64.parse((string)msg["mtime"]);
  1037. _project.add_file(path, size, mtime);
  1038. } else if (msg_type == "remove_file") {
  1039. string path = (string)msg["path"];
  1040. _database.set(0, GUID_ZERO, path, null);
  1041. _project.remove_file(path);
  1042. } else if (msg_type == "add_tree") {
  1043. string path = (string)msg["path"];
  1044. _project.add_tree(path);
  1045. } else if (msg_type == "remove_tree") {
  1046. string path = (string)msg["path"];
  1047. _project.remove_tree(path);
  1048. } else if (msg_type == "change_file") {
  1049. string path = (string)msg["path"];
  1050. uint64 size = uint64.parse((string)msg["size"]);
  1051. uint64 mtime = uint64.parse((string)msg["mtime"]);
  1052. _database.set(0, GUID_ZERO, path, null);
  1053. _project.change_file(path, size, mtime);
  1054. } else if (msg_type == "compile") {
  1055. _data_compiler.message(msg);
  1056. } else if (msg_type == "refresh") {
  1057. ri.refresh_finished((bool)msg["success"]);
  1058. } else if (msg_type == "refresh_list") {
  1059. _data_compiler.refresh_list_finished((Gee.ArrayList<Value?>)msg["list"]);
  1060. } else if (msg_type == "unit_spawned") {
  1061. Guid id = Guid.parse((string)msg["id"]);
  1062. string name = (string)msg["name"];
  1063. Gee.ArrayList<Value?> pos = (Gee.ArrayList<Value?>)msg["position"];
  1064. Gee.ArrayList<Value?> rot = (Gee.ArrayList<Value?>)msg["rotation"];
  1065. Gee.ArrayList<Value?> scl = (Gee.ArrayList<Value?>)msg["scale"];
  1066. _level.on_unit_spawned(id
  1067. , name
  1068. , Vector3.from_array(pos)
  1069. , Quaternion.from_array(rot)
  1070. , Vector3.from_array(scl)
  1071. );
  1072. _database_editor.selection_set({ id });
  1073. _database.add_restore_point((int)ActionType.CREATE_OBJECTS, new Guid?[] { id }, ActionTypeFlags.FROM_SERVER);
  1074. } else if (msg_type == "sound_spawned") {
  1075. Guid id = Guid.parse((string)msg["id"]);
  1076. string name = (string)msg["name"];
  1077. Gee.ArrayList<Value?> pos = (Gee.ArrayList<Value?>)msg["position"];
  1078. Gee.ArrayList<Value?> rot = (Gee.ArrayList<Value?>)msg["rotation"];
  1079. Gee.ArrayList<Value?> scl = (Gee.ArrayList<Value?>)msg["scale"];
  1080. double range = (double)msg["range"];
  1081. double volume = (double)msg["volume"];
  1082. bool loop = (bool)msg["loop"];
  1083. _level.on_sound_spawned(id
  1084. , name
  1085. , Vector3.from_array(pos)
  1086. , Quaternion.from_array(rot)
  1087. , Vector3.from_array(scl)
  1088. , range
  1089. , volume
  1090. , loop
  1091. );
  1092. _database.add_restore_point((int)ActionType.CREATE_OBJECTS, new Guid?[] { id }, ActionTypeFlags.FROM_SERVER);
  1093. } else if (msg_type == "move_objects") {
  1094. Hashtable ids = (Hashtable)msg["ids"];
  1095. Hashtable new_positions = (Hashtable)msg["new_positions"];
  1096. Hashtable new_rotations = (Hashtable)msg["new_rotations"];
  1097. Hashtable new_scales = (Hashtable)msg["new_scales"];
  1098. Gee.ArrayList<string> keys = new Gee.ArrayList<string>.wrap(ids.keys.to_array());
  1099. keys.sort(Gee.Functions.get_compare_func_for(typeof(string)));
  1100. Guid?[] n_ids = new Guid?[keys.size];
  1101. Vector3[] n_positions = new Vector3[keys.size];
  1102. Quaternion[] n_rotations = new Quaternion[keys.size];
  1103. Vector3[] n_scales = new Vector3[keys.size];
  1104. for (int i = 0; i < keys.size; ++i) {
  1105. string k = keys[i];
  1106. n_ids[i] = Guid.parse((string)ids[k]);
  1107. n_positions[i] = Vector3.from_array((Gee.ArrayList<Value?>)(new_positions[k]));
  1108. n_rotations[i] = Quaternion.from_array((Gee.ArrayList<Value?>)new_rotations[k]);
  1109. n_scales[i] = Vector3.from_array((Gee.ArrayList<Value?>)new_scales[k]);
  1110. }
  1111. _level.on_move_objects(n_ids, n_positions, n_rotations, n_scales);
  1112. _database.add_restore_point((int)ActionType.CHANGE_OBJECTS, n_ids, ActionTypeFlags.FROM_SERVER);
  1113. } else if (msg_type == "selection") {
  1114. Hashtable objects = (Hashtable)msg["objects"];
  1115. Gee.ArrayList<string> keys = new Gee.ArrayList<string>.wrap(objects.keys.to_array());
  1116. keys.sort(Gee.Functions.get_compare_func_for(typeof(string)));
  1117. Guid?[] ids = new Guid?[keys.size];
  1118. for (int i = 0; i < keys.size; ++i) {
  1119. string k = keys[i];
  1120. ids[i] = Guid.parse((string)objects[k]);
  1121. }
  1122. _database_editor.selection_read(ids);
  1123. ui_read_selection(_database_editor._selection.to_array());
  1124. } else if (msg_type == "camera") {
  1125. if (ri == _editor)
  1126. _level.on_camera(msg);
  1127. } else if (msg_type == "error") {
  1128. loge((string)msg["message"]);
  1129. } else if (msg_type == "thumbnail") {
  1130. string resource_type = (string)msg["resource_type"];
  1131. string resource_name = (string)msg["resource_name"];
  1132. string path = (string)msg["path"];
  1133. _thumbnail_cache.thumbnail_ready(resource_type, resource_name, path);
  1134. } else {
  1135. loge("Unknown message type: " + msg_type);
  1136. }
  1137. }
  1138. public void append_editor_state(StringBuilder sb)
  1139. {
  1140. // This state is common to any project.
  1141. sb.append(LevelEditorApi.set_grid_size(_grid_size));
  1142. sb.append(LevelEditorApi.set_rotation_snap(_rotation_snap));
  1143. sb.append(LevelEditorApi.enable_show_grid(_show_grid));
  1144. sb.append(LevelEditorApi.enable_snap_to_grid(_snap_to_grid));
  1145. sb.append(LevelEditorApi.enable_debug_render_world(_debug_render_world));
  1146. sb.append(LevelEditorApi.enable_debug_physics_world(_debug_physics_world));
  1147. sb.append(LevelEditorApi.set_tool_type(_tool_type));
  1148. sb.append(LevelEditorApi.set_snap_mode(_snap_mode));
  1149. sb.append(LevelEditorApi.set_reference_system(_reference_system));
  1150. }
  1151. public void append_project_state(StringBuilder sb)
  1152. {
  1153. // This state is not guaranteed to be applicable to any project.
  1154. if (_placeable_type != "")
  1155. sb.append(LevelEditorApi.set_placeable(_placeable_type, _placeable_name));
  1156. }
  1157. public void send_state()
  1158. {
  1159. StringBuilder sb = new StringBuilder();
  1160. append_editor_state(sb);
  1161. append_project_state(sb);
  1162. _editor.send_script(sb.str);
  1163. }
  1164. public void on_objects_created(Guid?[] object_ids, uint32 flags)
  1165. {
  1166. if ((flags & ActionTypeFlags.FROM_SERVER) == 0) {
  1167. StringBuilder sb = new StringBuilder();
  1168. _level.generate_spawn_objects(sb, object_ids);
  1169. if (sb.len > 0) {
  1170. _editor.send_script(sb.str);
  1171. _editor_viewport.frame();
  1172. }
  1173. }
  1174. ui_read_selection(_database_editor._selection.to_array());
  1175. update_active_window_title();
  1176. }
  1177. public void on_objects_destroyed(Guid?[] object_ids, uint32 flags = 0)
  1178. {
  1179. if ((flags & ActionTypeFlags.FROM_SERVER) == 0) {
  1180. StringBuilder sb = new StringBuilder();
  1181. _level.generate_destroy_objects(sb, object_ids);
  1182. if (sb.len > 0) {
  1183. _editor.send_script(sb.str);
  1184. _editor_viewport.frame();
  1185. }
  1186. }
  1187. ui_read_selection(_database_editor._selection.to_array());
  1188. update_active_window_title();
  1189. }
  1190. public void on_objects_changed(Guid?[] object_ids, uint32 flags = 0)
  1191. {
  1192. if ((flags & ActionTypeFlags.FROM_SERVER) == 0) {
  1193. StringBuilder sb = new StringBuilder();
  1194. _level.generate_change_objects(sb, object_ids);
  1195. if (sb.len > 0) {
  1196. _editor.send_script(sb.str);
  1197. _editor_viewport.frame();
  1198. }
  1199. }
  1200. ui_read_selection(_database_editor._selection.to_array());
  1201. update_active_window_title();
  1202. }
  1203. public void on_object_type_added(ObjectTypeInfo info)
  1204. {
  1205. if ((info.flags & ObjectTypeFlags.UNIT_COMPONENT) != 0) {
  1206. Unit.register_component_type(info.name, info.user_data != null ? info.user_data : "");
  1207. _properties_view.register_object_type(info.name, null);
  1208. } else if (info.name != OBJECT_TYPE_UNIT) { // FIXME
  1209. _properties_view.register_object_type(info.name, null);
  1210. }
  1211. }
  1212. public async bool restart_backend()
  1213. {
  1214. yield stop_backend();
  1215. // Spawn the data compiler.
  1216. string args[] =
  1217. {
  1218. ENGINE_EXE,
  1219. "--source-dir",
  1220. _project.source_dir(),
  1221. "--data-dir",
  1222. _project.data_dir(),
  1223. "--map-source-dir",
  1224. "core",
  1225. _project.toolchain_dir(),
  1226. "--server",
  1227. "--wait-console"
  1228. };
  1229. try {
  1230. _compiler._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1231. } catch (Error e) {
  1232. loge(e.message);
  1233. }
  1234. _project_stack.set_visible_child_name(COMPILER_CONNECTING);
  1235. _editor_stack.set_visible_child_name(COMPILER_CONNECTING);
  1236. _inspector_stack.set_visible_child_name(COMPILER_CONNECTING);
  1237. int tries = yield _compiler.connect_async(DATA_COMPILER_ADDRESS
  1238. , DATA_COMPILER_TCP_PORT
  1239. , DATA_COMPILER_CONNECTION_TRIES
  1240. , DATA_COMPILER_CONNECTION_INTERVAL
  1241. );
  1242. if (tries == DATA_COMPILER_CONNECTION_TRIES) {
  1243. loge("Cannot connect to data_compiler");
  1244. return false;
  1245. }
  1246. _project_stack.set_visible_child_name(COMPILER_COMPILING_DATA);
  1247. _editor_stack.set_visible_child_name(COMPILER_COMPILING_DATA);
  1248. _inspector_stack.set_visible_child_name(COMPILER_COMPILING_DATA);
  1249. // Compile data.
  1250. bool success = yield _data_compiler.compile(_project.data_dir(), _project.platform());
  1251. if (!success) {
  1252. _project_stack.set_visible_child_name(COMPILER_FAILED_COMPILATION);
  1253. _editor_stack.set_visible_child_name(COMPILER_FAILED_COMPILATION);
  1254. _inspector_stack.set_visible_child_name(COMPILER_FAILED_COMPILATION);
  1255. return success;
  1256. }
  1257. // If successful, start the level editor.
  1258. _project_stack.set_visible_child_name("child");
  1259. _editor_stack.set_visible_child_name("child");
  1260. _inspector_stack.set_visible_child_name("child");
  1261. yield _editor_viewport.restart_runtime();
  1262. yield start_thumbnail();
  1263. _project_stack.set_visible_child(_project_browser);
  1264. _inspector_stack.set_visible_child(_inspector_pane);
  1265. _project_browser.select_project_root();
  1266. return success;
  1267. }
  1268. public async void stop_heads()
  1269. {
  1270. yield _game.stop();
  1271. yield _thumbnail.stop();
  1272. yield _editor_viewport.stop_runtime();
  1273. }
  1274. public async void stop_backend()
  1275. {
  1276. _project_stack.set_visible_child_name(BACKEND_STOPPING);
  1277. _editor_stack.set_visible_child_name(BACKEND_STOPPING);
  1278. _inspector_stack.set_visible_child_name(BACKEND_STOPPING);
  1279. yield stop_heads();
  1280. yield stop_data_compiler();
  1281. }
  1282. public async void stop_data_compiler()
  1283. {
  1284. if (_compiler.is_connected())
  1285. _project.reset_files();
  1286. yield _compiler.stop();
  1287. }
  1288. public int dump_test_level()
  1289. {
  1290. try {
  1291. // Save temporary package to reference test level.
  1292. Gee.ArrayList<Value?> level = new Gee.ArrayList<Value?>();
  1293. level.add("_level_editor_test");
  1294. Hashtable package = new Hashtable();
  1295. package["level"] = level;
  1296. SJSON.save(package, _project._level_editor_test_package.get_path());
  1297. } catch (JsonWriteError e) {
  1298. return -1;
  1299. }
  1300. // Save test level to file.
  1301. return _database.dump(_project._level_editor_test_level.get_path(), _level._id);
  1302. }
  1303. public async void start_game(StartGame sg)
  1304. {
  1305. if (sg == StartGame.TEST && dump_test_level() != 0)
  1306. return;
  1307. bool success = yield _data_compiler.compile(_project.data_dir(), _project.platform());
  1308. _project.delete_garbage();
  1309. if (!success) {
  1310. _game_run_stop_image.set_from_icon_name("game-run", Gtk.IconSize.MENU);
  1311. return;
  1312. }
  1313. // Spawn the game.
  1314. string args[] =
  1315. {
  1316. ENGINE_EXE,
  1317. "--data-dir",
  1318. _project.data_dir(),
  1319. "--console-port",
  1320. GAME_TCP_PORT.to_string(),
  1321. "--wait-console",
  1322. "--lua-string",
  1323. sg == StartGame.TEST ? "TEST=true" : ""
  1324. };
  1325. try {
  1326. _game._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1327. } catch (Error e) {
  1328. loge(e.message);
  1329. }
  1330. // Try to connect to the game.
  1331. int tries = yield _game.connect_async(GAME_ADDRESS
  1332. , GAME_TCP_PORT
  1333. , GAME_CONNECTION_TRIES
  1334. , GAME_CONNECTION_INTERVAL
  1335. );
  1336. if (tries == GAME_CONNECTION_TRIES) {
  1337. loge("Cannot connect to game");
  1338. return;
  1339. }
  1340. }
  1341. public async void start_thumbnail()
  1342. {
  1343. string args[] =
  1344. {
  1345. ENGINE_EXE,
  1346. "--data-dir",
  1347. _project.data_dir(),
  1348. "--boot-dir",
  1349. THUMBNAIL_BOOT_DIR,
  1350. "--console-port",
  1351. THUMBNAIL_TCP_PORT.to_string(),
  1352. "--wait-console",
  1353. "--pumped",
  1354. "--hidden"
  1355. };
  1356. try {
  1357. _thumbnail._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1358. } catch (Error e) {
  1359. loge(e.message);
  1360. }
  1361. // Try to connect to the game.
  1362. int tries = yield _thumbnail.connect_async(THUMBNAIL_ADDRESS
  1363. , THUMBNAIL_TCP_PORT
  1364. , THUMBNAIL_CONNECTION_TRIES
  1365. , THUMBNAIL_CONNECTION_INTERVAL
  1366. );
  1367. if (tries == THUMBNAIL_CONNECTION_TRIES) {
  1368. loge("Cannot connect to thumbnail");
  1369. return;
  1370. }
  1371. }
  1372. public void on_tool(GLib.SimpleAction action, GLib.Variant? param)
  1373. {
  1374. ToolType type = (ToolType)param.get_int32();
  1375. if (type == ToolType.PLACE) {
  1376. // Store previous tool for it to be restored later.
  1377. if (_tool_type != ToolType.PLACE)
  1378. _tool_type_prev = _tool_type;
  1379. }
  1380. _tool_type = type;
  1381. _editor_viewport.grab_focus();
  1382. send_state();
  1383. _editor_viewport.frame();
  1384. action.set_state(param);
  1385. }
  1386. public void on_cancel_place(GLib.SimpleAction action, GLib.Variant? param)
  1387. {
  1388. if (_tool_type != ToolType.PLACE)
  1389. return;
  1390. activate_action("tool", new GLib.Variant.int32(_tool_type_prev));
  1391. }
  1392. public void on_snap(GLib.SimpleAction action, GLib.Variant? param)
  1393. {
  1394. _snap_mode = (SnapMode)param.get_int32();
  1395. send_state();
  1396. _editor_viewport.frame();
  1397. action.set_state(param);
  1398. }
  1399. public void on_reference_system(GLib.SimpleAction action, GLib.Variant? param)
  1400. {
  1401. _reference_system = (ReferenceSystem)param.get_int32();
  1402. send_state();
  1403. _editor_viewport.frame();
  1404. action.set_state(param);
  1405. }
  1406. public void on_grid_size(GLib.SimpleAction action, GLib.Variant? param)
  1407. {
  1408. int32 new_size = param.get_int32();
  1409. if (new_size != 0) {
  1410. _grid_size = (double)new_size / 10.0;
  1411. send_state();
  1412. _editor_viewport.frame();
  1413. action.set_state(param);
  1414. return;
  1415. }
  1416. // Custom grid size.
  1417. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Grid size"
  1418. , this.active_window
  1419. , Gtk.DialogFlags.MODAL
  1420. , "Cancel"
  1421. , Gtk.ResponseType.CANCEL
  1422. , "Ok"
  1423. , Gtk.ResponseType.OK
  1424. , null
  1425. );
  1426. InputDouble sb = new InputDouble(_grid_size, 0.1, 1000);
  1427. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  1428. dg.get_content_area().add(sb);
  1429. dg.response.connect((response_id) => {
  1430. if (response_id == Gtk.ResponseType.OK) {
  1431. _grid_size = sb.value;
  1432. send_state();
  1433. _editor_viewport.frame();
  1434. action.set_state(param);
  1435. }
  1436. dg.destroy();
  1437. });
  1438. dg.show_all();
  1439. }
  1440. public void update_active_window_title()
  1441. {
  1442. string title = "";
  1443. if (_level._name != null) {
  1444. if (_database.changed())
  1445. title += " • ";
  1446. title += (_level._name == LEVEL_EMPTY) ? "untitled" : _level._name;
  1447. title += " - ";
  1448. }
  1449. title += CROWN_EDITOR_NAME;
  1450. if (this.active_window.title != title)
  1451. this.active_window.title = title;
  1452. }
  1453. public void load_level(string name)
  1454. {
  1455. if (name == _level._name)
  1456. return;
  1457. if (_level.load(name) != 0) {
  1458. loge("Unable to load level %s".printf(name));
  1459. return;
  1460. }
  1461. if (_editor.is_connected()) {
  1462. _level.send_level();
  1463. send_state();
  1464. _editor_viewport.frame();
  1465. }
  1466. update_active_window_title();
  1467. _level_treeview.set_level(_level);
  1468. }
  1469. public bool do_save(string path)
  1470. {
  1471. string resource_filename = _project.resource_filename(path);
  1472. string resource_path = ResourceId.normalize(resource_filename);
  1473. string resource_name = ResourceId.name(resource_path);
  1474. if (_level.save(resource_name) != 0) {
  1475. Gtk.MessageDialog md = new Gtk.MessageDialog(this.active_window
  1476. , Gtk.DialogFlags.MODAL
  1477. , Gtk.MessageType.ERROR
  1478. , Gtk.ButtonsType.NONE
  1479. , "Unable to save level '%s'".printf(resource_name)
  1480. );
  1481. md.add_button("_Ok", Gtk.ResponseType.OK);
  1482. md.set_default_response(Gtk.ResponseType.OK);
  1483. md.response.connect(() => { md.destroy(); });
  1484. md.show_all();
  1485. return false;
  1486. }
  1487. _statusbar.set_temporary_message("Saved %s".printf(_level._path));
  1488. update_active_window_title();
  1489. return true;
  1490. }
  1491. public void save_as(string? filename, string? success_action = null, GLib.Variant? variant = null)
  1492. {
  1493. string path = filename;
  1494. if (path != null) {
  1495. if (do_save(path) && success_action != null)
  1496. GLib.Application.get_default().activate_action(success_action, variant);
  1497. } else {
  1498. SaveResourceDialog srd = new SaveResourceDialog("Save As..."
  1499. , this.active_window
  1500. , OBJECT_TYPE_LEVEL
  1501. , ""
  1502. , _project
  1503. );
  1504. srd.safer_response.connect((response_id, path) => {
  1505. if (response_id == Gtk.ResponseType.ACCEPT && path != null) {
  1506. if (do_save(path) && success_action != null)
  1507. GLib.Application.get_default().activate_action(success_action, variant);
  1508. }
  1509. srd.destroy();
  1510. });
  1511. srd.show_all();
  1512. }
  1513. }
  1514. public void save(string? success_action = null, GLib.Variant? variant = null)
  1515. {
  1516. save_as(_level._path, success_action, variant);
  1517. }
  1518. public bool save_timeout()
  1519. {
  1520. if (_level._path != null)
  1521. save();
  1522. return GLib.Source.CONTINUE;
  1523. }
  1524. public Hashtable encode()
  1525. {
  1526. Hashtable json_obj = new Hashtable();
  1527. json_obj["level_editor_window"] = ((LevelEditorWindow)this.active_window).encode();
  1528. return json_obj;
  1529. }
  1530. public override void shutdown()
  1531. {
  1532. // Disable auto-save.
  1533. if (_save_timer_id > 0)
  1534. GLib.Source.remove(_save_timer_id);
  1535. // Save editor settings.
  1536. _user.save(_user_file.get_path());
  1537. _preferences_dialog.encode(_settings);
  1538. try {
  1539. SJSON.save(_settings, _settings_file.get_path());
  1540. } catch (JsonWriteError e) {
  1541. loge(e.message);
  1542. }
  1543. try {
  1544. SJSON.save(encode(), _window_state_file.get_path());
  1545. } catch (JsonWriteError e) {
  1546. loge(e.message);
  1547. }
  1548. _console_view._entry_history.save(_console_history_file.get_path());
  1549. if (_preferences_dialog != null)
  1550. _preferences_dialog.destroy();
  1551. base.shutdown();
  1552. }
  1553. public void do_new_level()
  1554. {
  1555. if (_level.create(LEVEL_EMPTY) != 0) {
  1556. loge("Unable to create a new level.");
  1557. return;
  1558. }
  1559. if (_editor.is_connected()) {
  1560. _level.send_level();
  1561. send_state();
  1562. _editor_viewport.frame();
  1563. }
  1564. update_active_window_title();
  1565. _level_treeview.set_level(_level);
  1566. }
  1567. public void on_new_level(GLib.SimpleAction action, GLib.Variant? param)
  1568. {
  1569. if (!_database.changed()) {
  1570. do_new_level();
  1571. } else {
  1572. Gtk.Dialog dlg = new_level_changed_dialog(this.active_window);
  1573. dlg.response.connect((response_id) => {
  1574. if (response_id == Gtk.ResponseType.NO)
  1575. do_new_level();
  1576. else if (response_id == Gtk.ResponseType.YES)
  1577. save("new-level");
  1578. dlg.destroy();
  1579. });
  1580. dlg.show_all();
  1581. }
  1582. }
  1583. public void do_open_level(string path)
  1584. {
  1585. string resource_filename = _project.resource_filename(path);
  1586. string resource_path = ResourceId.normalize(resource_filename);
  1587. string resource_name = ResourceId.name(resource_path);
  1588. load_level(resource_name);
  1589. }
  1590. public void on_open_level_from_menubar(GLib.SimpleAction action, GLib.Variant? param)
  1591. {
  1592. OpenResourceDialog dlg = new OpenResourceDialog("Open Level..."
  1593. , this.active_window
  1594. , OBJECT_TYPE_LEVEL
  1595. , _project
  1596. );
  1597. dlg.safer_response.connect((response_id, path) => {
  1598. if (response_id == Gtk.ResponseType.ACCEPT && path != null)
  1599. do_open_level(path);
  1600. dlg.destroy();
  1601. });
  1602. dlg.show_all();
  1603. }
  1604. public void on_open_level(GLib.SimpleAction action, GLib.Variant? param)
  1605. {
  1606. string level_name = param.get_string();
  1607. if (level_name != "" && level_name == _level._name)
  1608. return;
  1609. if (!_database.changed()) {
  1610. if (level_name != "")
  1611. load_level(level_name);
  1612. else // Action invoked from menubar File > Open Level...
  1613. on_open_level_from_menubar(action, param);
  1614. } else {
  1615. Gtk.Dialog dlg = new_level_changed_dialog(this.active_window);
  1616. dlg.response.connect((response_id) => {
  1617. if (response_id == Gtk.ResponseType.NO) {
  1618. if (level_name != "")
  1619. load_level(level_name);
  1620. else // Action invoked from menubar File > Open Level...
  1621. on_open_level_from_menubar(action, param);
  1622. } else if (response_id == Gtk.ResponseType.YES) {
  1623. save("open-level", param);
  1624. }
  1625. dlg.destroy();
  1626. });
  1627. dlg.show_all();
  1628. }
  1629. }
  1630. public void do_open_project(string source_dir, string? level_name)
  1631. {
  1632. if (_project.source_dir() == source_dir) {
  1633. logi("Project `%s` is open already.".printf(source_dir));
  1634. return;
  1635. }
  1636. logi("Loading project: `%s`...".printf(source_dir));
  1637. if (_project.load(source_dir) != 0) {
  1638. Gtk.MessageDialog md = new Gtk.MessageDialog(this.active_window
  1639. , Gtk.DialogFlags.MODAL
  1640. , Gtk.MessageType.INFO
  1641. , Gtk.ButtonsType.OK
  1642. , "The folder `%s` does not appear to be a valid Crown project.".printf(source_dir)
  1643. );
  1644. md.set_default_response(Gtk.ResponseType.OK);
  1645. md.response.connect(() => { md.destroy(); });
  1646. md.show_all();
  1647. return;
  1648. }
  1649. this.show_panel(PANEL_EDITOR, Gtk.StackTransitionType.NONE);
  1650. _user.add_or_touch_recent_project(source_dir, source_dir);
  1651. _console_view.reset();
  1652. logi("Project `%s` loaded.".printf(source_dir));
  1653. if (level_name == null)
  1654. do_new_level();
  1655. else
  1656. load_level(level_name);
  1657. restart_backend.begin();
  1658. }
  1659. public void open_project(string source_dir, string? level_name = null)
  1660. {
  1661. if (source_dir != "") {
  1662. do_open_project(source_dir, level_name);
  1663. } else {
  1664. Gtk.FileChooserDialog dlg = new_open_project_dialog(this.active_window);
  1665. dlg.response.connect((response_id) => {
  1666. if (response_id == Gtk.ResponseType.ACCEPT)
  1667. do_open_project(dlg.get_file().get_path(), level_name);
  1668. dlg.destroy();
  1669. });
  1670. dlg.show_all();
  1671. }
  1672. }
  1673. public void on_open_project(GLib.SimpleAction action, GLib.Variant? param)
  1674. {
  1675. string source_dir = "";
  1676. string level_name = LEVEL_EMPTY;
  1677. if (param != null) {
  1678. source_dir = (string)param.get_child_value(0);
  1679. level_name = (string)param.get_child_value(1);
  1680. }
  1681. if (!_database.changed()) {
  1682. open_project(source_dir);
  1683. } else {
  1684. Gtk.Dialog dlg = new_level_changed_dialog(this.active_window);
  1685. dlg.response.connect((response_id) => {
  1686. if (response_id == Gtk.ResponseType.NO)
  1687. open_project(source_dir, level_name);
  1688. else if (response_id == Gtk.ResponseType.YES)
  1689. save("open-project", new GLib.Variant.tuple({source_dir, level_name}));
  1690. dlg.destroy();
  1691. });
  1692. dlg.show_all();
  1693. }
  1694. }
  1695. public void on_open_projects_list(GLib.SimpleAction action, GLib.Variant? param)
  1696. {
  1697. show_panel(PANEL_PROJECTS_LIST);
  1698. }
  1699. public void do_new_project()
  1700. {
  1701. reset_project();
  1702. stop_backend.begin((obj, res) => {
  1703. stop_backend.end(res);
  1704. show_panel(PANEL_NEW_PROJECT);
  1705. });
  1706. }
  1707. public void on_new_project(GLib.SimpleAction action, GLib.Variant? param)
  1708. {
  1709. if (!_database.changed()) {
  1710. do_new_project();
  1711. } else {
  1712. Gtk.Dialog dlg = new_level_changed_dialog(this.active_window);
  1713. dlg.response.connect((response_id) => {
  1714. if (response_id == Gtk.ResponseType.NO)
  1715. do_new_project();
  1716. else if (response_id == Gtk.ResponseType.YES)
  1717. save("new-project");
  1718. dlg.destroy();
  1719. });
  1720. dlg.show_all();
  1721. }
  1722. }
  1723. public void on_add_project(GLib.SimpleAction action, GLib.Variant? param)
  1724. {
  1725. Gtk.FileChooserDialog dlg = new_open_project_dialog(this.active_window);
  1726. dlg.response.connect((response_id) => {
  1727. if (response_id == Gtk.ResponseType.ACCEPT) {
  1728. string source_dir = dlg.get_file().get_path();
  1729. _user.add_or_touch_recent_project(source_dir, source_dir);
  1730. }
  1731. dlg.destroy();
  1732. });
  1733. dlg.show_all();
  1734. }
  1735. public void on_remove_project(GLib.SimpleAction action, GLib.Variant? param)
  1736. {
  1737. string source_dir = param.get_string();
  1738. Gtk.MessageDialog md = new Gtk.MessageDialog(this.active_window
  1739. , Gtk.DialogFlags.MODAL
  1740. , Gtk.MessageType.WARNING
  1741. , Gtk.ButtonsType.NONE
  1742. , "Remove \"%s\" from the list?\n\nThis action removes the project from the list only, files on disk will not be deleted.".printf(source_dir)
  1743. );
  1744. md.add_button("_Cancel", Gtk.ResponseType.CANCEL);
  1745. md.add_button("_Remove", Gtk.ResponseType.YES);
  1746. md.set_default_response(Gtk.ResponseType.CANCEL);
  1747. md.response.connect((response_id) => {
  1748. if (response_id == Gtk.ResponseType.YES) {
  1749. _user.remove_recent_project(source_dir);
  1750. }
  1751. md.destroy();
  1752. });
  1753. md.show_all();
  1754. }
  1755. public void on_save(GLib.SimpleAction action, GLib.Variant? param)
  1756. {
  1757. save();
  1758. }
  1759. public void on_save_as(GLib.SimpleAction action, GLib.Variant? param)
  1760. {
  1761. save_as(null);
  1762. }
  1763. public void on_import_result(ImportResult result)
  1764. {
  1765. if (result == ImportResult.ERROR) {
  1766. loge("Failed to import resource(s)");
  1767. return;
  1768. } else if (result == ImportResult.SUCCESS) {
  1769. compile_and_reload.begin();
  1770. }
  1771. ui_read_selection(_database_editor._selection.to_array());
  1772. }
  1773. public void on_import(GLib.SimpleAction action, GLib.Variant? param)
  1774. {
  1775. string? destination_dir = null;
  1776. string[] filenames = {};
  1777. if (param != null) {
  1778. destination_dir = (string)param.get_child_value(0);
  1779. filenames = (string[])param.get_child_value(1);
  1780. }
  1781. _project.import(destination_dir
  1782. , filenames
  1783. , on_import_result
  1784. , _database
  1785. , this.active_window
  1786. );
  1787. }
  1788. public void on_preferences(GLib.SimpleAction action, GLib.Variant? param)
  1789. {
  1790. _preferences_dialog.set_transient_for(_level_editor_window);
  1791. _preferences_dialog.show_all();
  1792. _preferences_dialog.present();
  1793. }
  1794. public void on_deploy(GLib.SimpleAction action, GLib.Variant? param)
  1795. {
  1796. if (_deploy_dialog == null) {
  1797. _deploy_dialog = new DeployDialog(_project, _editor);
  1798. _deploy_dialog.set_transient_for(_level_editor_window);
  1799. _deploy_dialog.delete_event.connect(_deploy_dialog.hide_on_delete);
  1800. }
  1801. _deploy_dialog.show_all();
  1802. _deploy_dialog.present();
  1803. }
  1804. public void on_texture_settings(GLib.SimpleAction action, GLib.Variant? param)
  1805. {
  1806. string texture_name = param.get_string();
  1807. if (_texture_settings_dialog == null) {
  1808. _texture_settings_dialog = new TextureSettingsDialog(_project, _database);
  1809. _texture_settings_dialog.set_transient_for(_level_editor_window);
  1810. _texture_settings_dialog.delete_event.connect(_texture_settings_dialog.hide_on_delete);
  1811. _texture_settings_dialog.texture_saved.connect(() => {
  1812. compile_and_reload.begin();
  1813. });
  1814. }
  1815. _texture_settings_dialog.show_all();
  1816. _texture_settings_dialog.present();
  1817. _texture_settings_dialog.set_texture(texture_name);
  1818. }
  1819. public void on_state_machine_editor(GLib.SimpleAction action, GLib.Variant? param)
  1820. {
  1821. string state_machine_name = param.get_string();
  1822. if (_state_machine_editor == null) {
  1823. _state_machine_editor = new StateMachineEditor(this
  1824. , _project
  1825. , "core/editors/state_machine_editor"
  1826. , "127.0.0.1"
  1827. , 10844
  1828. , (uint)_preferences_dialog._undo_redo_max_size.value * 1024 * 1024
  1829. );
  1830. _state_machine_editor.set_transient_for(_level_editor_window);
  1831. _state_machine_editor.saved.connect(() => {
  1832. compile_and_reload.begin();
  1833. });
  1834. _runtimes.add(_state_machine_editor._runtime);
  1835. this.add_window(_state_machine_editor);
  1836. }
  1837. _state_machine_editor.show_all();
  1838. _state_machine_editor.present();
  1839. _state_machine_editor.set_state_machine(state_machine_name);
  1840. }
  1841. public void on_open_object(GLib.SimpleAction action, GLib.Variant? param)
  1842. {
  1843. string resource_type = (string)param.get_child_value(0);
  1844. string resource_name = (string)param.get_child_value(1);
  1845. if (_object_editor == null) {
  1846. _object_editor = new ObjectEditor(this
  1847. , _project
  1848. , (uint)_preferences_dialog._undo_redo_max_size.value * 1024 * 1024
  1849. );
  1850. _object_editor.set_transient_for(_level_editor_window);
  1851. _object_editor.saved.connect(() => {
  1852. compile_and_reload.begin();
  1853. });
  1854. this.add_window(_object_editor);
  1855. }
  1856. _object_editor.show_all();
  1857. _object_editor.present();
  1858. _object_editor.set_object(resource_type, resource_name);
  1859. }
  1860. public void on_reveal(GLib.SimpleAction action, GLib.Variant? param)
  1861. {
  1862. string type = (string)param.get_child_value(0);
  1863. string name = (string)param.get_child_value(1);
  1864. if (!_project_notebook.is_visible())
  1865. _project_notebook.show_all();
  1866. _project_browser.reveal(type, name);
  1867. }
  1868. public Gtk.Dialog new_level_changed_dialog(Gtk.Window? parent)
  1869. {
  1870. return new_resource_changed_dialog(parent, "Level");
  1871. }
  1872. public Gtk.FileChooserDialog new_open_project_dialog(Gtk.Window? parent)
  1873. {
  1874. return new Gtk.FileChooserDialog("Open Project..."
  1875. , parent
  1876. , Gtk.FileChooserAction.SELECT_FOLDER
  1877. , "Cancel"
  1878. , Gtk.ResponseType.CANCEL
  1879. , "Open"
  1880. , Gtk.ResponseType.ACCEPT
  1881. );
  1882. }
  1883. public void reset_project()
  1884. {
  1885. _placeable_type = OBJECT_TYPE_UNIT;
  1886. _placeable_name = "core/units/primitives/cube";
  1887. _database_editor.clear_selection();
  1888. _level.reset();
  1889. _project.reset();
  1890. this.active_window.title = CROWN_EDITOR_NAME;
  1891. }
  1892. public void do_close_project()
  1893. {
  1894. reset_project();
  1895. stop_backend.begin((obj, res) => {
  1896. stop_backend.end(res);
  1897. show_panel(PANEL_PROJECTS_LIST);
  1898. });
  1899. }
  1900. public void on_close_project(GLib.SimpleAction action, GLib.Variant? param)
  1901. {
  1902. if (!_database.changed()) {
  1903. do_close_project();
  1904. } else {
  1905. Gtk.Dialog dlg = new_level_changed_dialog(this.active_window);
  1906. dlg.response.connect((response_id) => {
  1907. if (response_id == Gtk.ResponseType.NO)
  1908. do_close_project();
  1909. else if (response_id == Gtk.ResponseType.YES)
  1910. save("close-project");
  1911. dlg.destroy();
  1912. });
  1913. dlg.show_all();
  1914. }
  1915. }
  1916. public void stop_backend_and_quit()
  1917. {
  1918. reset_project();
  1919. stop_backend.begin((obj, res) => {
  1920. stop_backend.end(res);
  1921. this.quit();
  1922. });
  1923. }
  1924. public void on_quit(GLib.SimpleAction action, GLib.Variant? param)
  1925. {
  1926. if (!_database.changed()) {
  1927. stop_backend_and_quit();
  1928. } else {
  1929. Gtk.Dialog dlg = new_level_changed_dialog(this.active_window);
  1930. dlg.response.connect((response_id) => {
  1931. if (response_id == Gtk.ResponseType.NO)
  1932. stop_backend_and_quit();
  1933. else if (response_id == Gtk.ResponseType.YES)
  1934. save("quit");
  1935. dlg.destroy();
  1936. });
  1937. dlg.show_all();
  1938. }
  1939. }
  1940. public static bool is_image_file(string path)
  1941. {
  1942. return path.has_suffix(".png")
  1943. || path.has_suffix(".tga")
  1944. ;
  1945. }
  1946. public void on_open_resource(GLib.SimpleAction action, GLib.Variant? param)
  1947. {
  1948. if (param == null)
  1949. return;
  1950. GLib.AppInfo? app = null;
  1951. string resource_path = param.get_string();
  1952. string? resource_type = ResourceId.type(resource_path);
  1953. string? resource_name = ResourceId.name(resource_path);
  1954. if (resource_type == null || resource_name == null)
  1955. return;
  1956. if (resource_type == OBJECT_TYPE_LEVEL) {
  1957. activate_action("open-level", resource_name);
  1958. return;
  1959. } else if (resource_type == OBJECT_TYPE_TEXTURE) {
  1960. activate_action("texture-settings", resource_name);
  1961. return;
  1962. } else if (resource_type == OBJECT_TYPE_UNIT) {
  1963. activate_action("open-unit", resource_name);
  1964. return;
  1965. } else if (resource_type == OBJECT_TYPE_STATE_MACHINE) {
  1966. activate_action("state-machine-editor", resource_name);
  1967. return;
  1968. } else if (resource_type == "lua") {
  1969. app = _preferences_dialog._lua_external_tool_button.get_app_info();
  1970. } else if (is_image_file(resource_path)) {
  1971. app = _preferences_dialog._image_external_tool_button.get_app_info();
  1972. } else if (_database.has_type(StringId64(resource_type))) {
  1973. activate_action("open-object", new GLib.Variant.tuple({ resource_type, resource_name }));
  1974. return;
  1975. }
  1976. GLib.File file = GLib.File.new_for_path(_project.absolute_path(resource_path));
  1977. try {
  1978. if (app == null)
  1979. app = file.query_default_handler();
  1980. } catch (GLib.Error e) {
  1981. // Ignore.
  1982. }
  1983. if (app == null)
  1984. app = GLib.AppInfo.get_default_for_type("text/plain", false);
  1985. if (app != null) {
  1986. GLib.List<GLib.File> files = new GLib.List<GLib.File>();
  1987. files.append(file);
  1988. try {
  1989. app.launch(files, null);
  1990. } catch (GLib.Error e) {
  1991. open_text_editor(file.get_path());
  1992. }
  1993. } else {
  1994. open_text_editor(file.get_path());
  1995. }
  1996. }
  1997. public void copy_string(string str)
  1998. {
  1999. var clip = Gtk.Clipboard.get_default(Gdk.Display.get_default());
  2000. clip.set_text(str, str.length);
  2001. #if !CROWN_PLATFORM_WINDOWS
  2002. clip.store();
  2003. #endif
  2004. }
  2005. public void on_copy_path(GLib.SimpleAction action, GLib.Variant? param)
  2006. {
  2007. string path = param.get_string();
  2008. copy_string(_project.absolute_path(path));
  2009. }
  2010. public void on_copy_name(GLib.SimpleAction action, GLib.Variant? param)
  2011. {
  2012. copy_string(param.get_string());
  2013. }
  2014. public void on_show_grid(GLib.SimpleAction action, GLib.Variant? param)
  2015. {
  2016. _show_grid = !action.get_state().get_boolean();
  2017. send_state();
  2018. _editor_viewport.frame();
  2019. action.set_state(new GLib.Variant.boolean(_show_grid));
  2020. }
  2021. public void on_rotation_snap_size(GLib.SimpleAction action, GLib.Variant? param)
  2022. {
  2023. int32 new_size = param.get_int32();
  2024. if (new_size != 0) {
  2025. _rotation_snap = (double)new_size;
  2026. send_state();
  2027. _editor_viewport.frame();
  2028. action.set_state(param);
  2029. return;
  2030. }
  2031. // Custom rotation size.
  2032. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Rotation snap"
  2033. , this.active_window
  2034. , Gtk.DialogFlags.MODAL
  2035. , "Cancel"
  2036. , Gtk.ResponseType.CANCEL
  2037. , "Ok"
  2038. , Gtk.ResponseType.OK
  2039. , null
  2040. );
  2041. InputDouble sb = new InputDouble(_rotation_snap, 1.0, 180.0);
  2042. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  2043. dg.get_content_area().add(sb);
  2044. dg.response.connect((response_id) => {
  2045. if (response_id == Gtk.ResponseType.OK) {
  2046. _rotation_snap = sb.value;
  2047. send_state();
  2048. _editor_viewport.frame();
  2049. action.set_state(param);
  2050. }
  2051. dg.destroy();
  2052. });
  2053. dg.show_all();
  2054. }
  2055. public void on_spawn_primitive(GLib.SimpleAction action, GLib.Variant? param)
  2056. {
  2057. GLib.Variant[] paramz;
  2058. if (action.name == "primitive-cube")
  2059. paramz = { OBJECT_TYPE_UNIT, "core/units/primitives/cube" };
  2060. else if (action.name == "primitive-sphere")
  2061. paramz = { OBJECT_TYPE_UNIT, "core/units/primitives/sphere" };
  2062. else if (action.name == "primitive-cone")
  2063. paramz = { OBJECT_TYPE_UNIT, "core/units/primitives/cone" };
  2064. else if (action.name == "primitive-cylinder")
  2065. paramz = { OBJECT_TYPE_UNIT, "core/units/primitives/cylinder" };
  2066. else if (action.name == "primitive-plane")
  2067. paramz = { OBJECT_TYPE_UNIT, "core/units/primitives/plane" };
  2068. else if (action.name == "camera")
  2069. paramz = { OBJECT_TYPE_UNIT, "core/units/camera" };
  2070. else if (action.name == "light")
  2071. paramz = { OBJECT_TYPE_UNIT, "core/units/light" };
  2072. else if (action.name == "sound-source")
  2073. paramz = { OBJECT_TYPE_SOUND, "sound" };
  2074. else
  2075. paramz = { OBJECT_TYPE_UNIT, "core/units/primitives/cube" };
  2076. activate_action("set-placeable", new GLib.Variant.tuple(paramz));
  2077. }
  2078. public void on_spawn_unit(GLib.SimpleAction action, GLib.Variant? param)
  2079. {
  2080. string? unit_name;
  2081. if (action.name == "empty-unit")
  2082. unit_name = null;
  2083. else if (action.name == "shading-environment")
  2084. unit_name = "core/renderer/default_shading_environment";
  2085. else
  2086. unit_name = null;
  2087. _level.spawn_unit(unit_name);
  2088. _editor_viewport.frame();
  2089. }
  2090. public void on_camera_frame_all(GLib.SimpleAction action, GLib.Variant? param)
  2091. {
  2092. Gee.ArrayList<Guid?> all_objects = new Gee.ArrayList<Guid?>();
  2093. _level.objects(ref all_objects);
  2094. _editor.send_script(LevelEditorApi.frame_objects(all_objects.to_array()));
  2095. _editor_viewport.frame();
  2096. }
  2097. public void on_project_browser(GLib.SimpleAction action, GLib.Variant? param)
  2098. {
  2099. if (_project_notebook.is_visible()) {
  2100. _project_notebook.hide();
  2101. } else {
  2102. _project_notebook.show_all();
  2103. }
  2104. }
  2105. public void on_console(GLib.SimpleAction action, GLib.Variant? param)
  2106. {
  2107. if (_console_notebook.is_visible()) {
  2108. if (_console_view._entry.has_focus)
  2109. _console_notebook.hide();
  2110. else
  2111. _console_view._entry.grab_focus_without_selecting();
  2112. } else {
  2113. _console_notebook.show_all();
  2114. _console_view._entry.grab_focus_without_selecting();
  2115. }
  2116. }
  2117. public void on_statusbar(GLib.SimpleAction action, GLib.Variant? param)
  2118. {
  2119. if (_statusbar.is_visible()) {
  2120. _statusbar.hide();
  2121. } else {
  2122. _statusbar.show_all();
  2123. }
  2124. }
  2125. public void on_inspector(GLib.SimpleAction action, GLib.Variant? param)
  2126. {
  2127. if (_inspector_stack.is_visible()) {
  2128. _inspector_stack.hide();
  2129. } else {
  2130. _inspector_stack.show_all();
  2131. }
  2132. }
  2133. public void on_restart_backend(GLib.SimpleAction action, GLib.Variant? param)
  2134. {
  2135. restart_backend.begin((obj, res) => {
  2136. restart_backend.end(res);
  2137. });
  2138. }
  2139. public void on_restart_editor_view(GLib.SimpleAction action, GLib.Variant? param)
  2140. {
  2141. _editor_viewport.restart_runtime.begin((obj, res) => {
  2142. _editor_viewport.restart_runtime.end(res);
  2143. });
  2144. }
  2145. public void on_build_data(GLib.SimpleAction action, GLib.Variant? param)
  2146. {
  2147. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  2148. _data_compiler.compile.end(res);
  2149. });
  2150. }
  2151. public void on_reload_all(GLib.SimpleAction action, GLib.Variant? param)
  2152. {
  2153. compile_and_reload.begin();
  2154. }
  2155. public async bool refresh_all_clients()
  2156. {
  2157. bool success = true;
  2158. foreach (var ri in _runtimes)
  2159. if (ri.is_connected() && !yield ri.refresh(_data_compiler))
  2160. success = false;
  2161. if (success) {
  2162. _project_browser.queue_draw();
  2163. // Apply editor changes to reloaded units.
  2164. var sb = new GLib.StringBuilder();
  2165. Gee.ArrayList<Guid?> unit_ids = new Gee.ArrayList<Guid?>();
  2166. _level.units(ref unit_ids);
  2167. Unit.generate_change_commands(sb, unit_ids.to_array(), _database);
  2168. foreach (var id in unit_ids)
  2169. sb.append(LevelEditorApi.unit_freeze(id));
  2170. _editor.send_script(sb.str);
  2171. _editor_viewport.frame();
  2172. }
  2173. return success;
  2174. }
  2175. public void on_snap_to_grid(GLib.SimpleAction action, GLib.Variant? param)
  2176. {
  2177. _snap_to_grid = !action.get_state().get_boolean();
  2178. send_state();
  2179. _editor_viewport.frame();
  2180. action.set_state(new GLib.Variant.boolean(_snap_to_grid));
  2181. }
  2182. public void on_debug_render_world(GLib.SimpleAction action, GLib.Variant? param)
  2183. {
  2184. _debug_render_world = !action.get_state().get_boolean();
  2185. send_state();
  2186. _editor_viewport.frame();
  2187. action.set_state(new GLib.Variant.boolean(_debug_render_world));
  2188. }
  2189. public void on_debug_physics_world(GLib.SimpleAction action, GLib.Variant? param)
  2190. {
  2191. _debug_physics_world = !action.get_state().get_boolean();
  2192. send_state();
  2193. _editor_viewport.frame();
  2194. action.set_state(new GLib.Variant.boolean(_debug_physics_world));
  2195. }
  2196. public void on_run_game(GLib.SimpleAction action, GLib.Variant? param)
  2197. {
  2198. // Trigger a 'focus_out_event' on the currently focused
  2199. // widget within the active_window, if any. This will
  2200. // force 'focus' to commit its pending changes to the
  2201. // database so we do not miss any modifications before
  2202. // launching the game.
  2203. Gtk.Widget? focus = this.active_window.get_focus();
  2204. _editor_viewport.grab_focus();
  2205. if (focus != null)
  2206. focus.grab_focus();
  2207. var icon_displayed = _game_run_stop_image.icon_name;
  2208. _game.stop.begin((obj, res) => {
  2209. _game.stop.end(res);
  2210. if (icon_displayed == "game-run") {
  2211. // Always change icon state regardless of failures.
  2212. _game_run_stop_image.set_from_icon_name("game-stop", Gtk.IconSize.MENU);
  2213. start_game.begin(action.name == "test-level" ? StartGame.TEST : StartGame.NORMAL);
  2214. }
  2215. });
  2216. }
  2217. public void do_rename(Guid object_id, string new_name)
  2218. {
  2219. if (new_name != "" && _database.name(object_id) != new_name) {
  2220. _database.set_name(object_id, new_name);
  2221. _database.add_restore_point((int)ActionType.CHANGE_OBJECTS, new Guid?[] { object_id });
  2222. }
  2223. }
  2224. public void on_rename(GLib.SimpleAction action, GLib.Variant? param)
  2225. {
  2226. Guid object_id = Guid.parse((string)param.get_child_value(0));
  2227. string new_name = (string)param.get_child_value(1);
  2228. if (new_name != "") {
  2229. do_rename(object_id, new_name);
  2230. } else {
  2231. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("New Name"
  2232. , this.active_window
  2233. , Gtk.DialogFlags.MODAL
  2234. , "Cancel"
  2235. , Gtk.ResponseType.CANCEL
  2236. , "Ok"
  2237. , Gtk.ResponseType.OK
  2238. , null
  2239. );
  2240. InputString sb = new InputString();
  2241. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  2242. sb.value = _database.name(object_id);
  2243. dg.get_content_area().add(sb);
  2244. dg.response.connect((response_id) => {
  2245. if (response_id == Gtk.ResponseType.OK)
  2246. do_rename(object_id, sb.text.strip());
  2247. dg.destroy();
  2248. });
  2249. dg.show_all();
  2250. }
  2251. }
  2252. public void on_manual(GLib.SimpleAction action, GLib.Variant? param)
  2253. {
  2254. try {
  2255. AppInfo.launch_default_for_uri(CROWN_LATEST_DOCS_URL, null);
  2256. } catch (Error e) {
  2257. loge(e.message);
  2258. }
  2259. }
  2260. public void on_report_issue(GLib.SimpleAction action, GLib.Variant? param)
  2261. {
  2262. try {
  2263. AppInfo.launch_default_for_uri("https://github.com/crownengine/crown/issues", null);
  2264. } catch (Error e) {
  2265. loge(e.message);
  2266. }
  2267. }
  2268. public void on_browse_logs(GLib.SimpleAction action, GLib.Variant? param)
  2269. {
  2270. open_directory(_logs_dir.get_path());
  2271. }
  2272. public void on_changelog(GLib.SimpleAction action, GLib.Variant? param)
  2273. {
  2274. try {
  2275. AppInfo.launch_default_for_uri(CROWN_LATEST_CHANGELOG_URL, null);
  2276. } catch (Error e) {
  2277. loge(e.message);
  2278. }
  2279. }
  2280. public void on_donate(GLib.SimpleAction action, GLib.Variant? param)
  2281. {
  2282. try {
  2283. AppInfo.launch_default_for_uri(CROWN_FUND_URL, null);
  2284. } catch (Error e) {
  2285. loge(e.message);
  2286. }
  2287. }
  2288. public void on_credits(GLib.SimpleAction action, GLib.Variant? param)
  2289. {
  2290. try {
  2291. AppInfo.launch_default_for_uri(CROWN_CREDITS_URL, null);
  2292. } catch (Error e) {
  2293. loge(e.message);
  2294. }
  2295. }
  2296. public void do_delete_file(string resource_path)
  2297. {
  2298. string path = _project.absolute_path(resource_path);
  2299. try {
  2300. GLib.File.new_for_path(path).delete();
  2301. } catch (Error e) {
  2302. loge(e.message);
  2303. }
  2304. }
  2305. public void on_delete_file(GLib.SimpleAction action, GLib.Variant? param)
  2306. {
  2307. if (param == null)
  2308. return;
  2309. string resource_path = param.get_string();
  2310. string? resource_type = ResourceId.type(resource_path);
  2311. string? resource_name = ResourceId.name(resource_path);
  2312. if (resource_type != null && resource_name != null) {
  2313. if (resource_name == _level._name) {
  2314. if (!_database.changed()) {
  2315. do_delete_file(resource_path);
  2316. GLib.Application.get_default().activate_action("new-level", null);
  2317. } else {
  2318. Gtk.Dialog dlg = new_level_changed_dialog(this.active_window);
  2319. dlg.response.connect((response_id) => {
  2320. if (response_id == Gtk.ResponseType.NO) {
  2321. do_delete_file(resource_path);
  2322. do_new_level();
  2323. } else if (response_id == Gtk.ResponseType.YES) {
  2324. save("new-level");
  2325. }
  2326. dlg.destroy();
  2327. });
  2328. dlg.show_all();
  2329. }
  2330. } else {
  2331. do_delete_file(resource_path);
  2332. }
  2333. }
  2334. }
  2335. public void do_delete_directory(string dir_name)
  2336. {
  2337. if (dir_name == "")
  2338. return;
  2339. var path = _project.absolute_path(dir_name);
  2340. try {
  2341. _project.delete_tree(GLib.File.new_for_path(path));
  2342. } catch (Error e) {
  2343. loge(e.message);
  2344. }
  2345. }
  2346. public void on_delete_directory(GLib.SimpleAction action, GLib.Variant? param)
  2347. {
  2348. string dir_name = param.get_string();
  2349. Gtk.MessageDialog md = new Gtk.MessageDialog(this.active_window
  2350. , Gtk.DialogFlags.MODAL
  2351. , Gtk.MessageType.WARNING
  2352. , Gtk.ButtonsType.NONE
  2353. , "Delete Folder " + dir_name + "?"
  2354. );
  2355. Gtk.Widget btn;
  2356. md.add_button("_Cancel", Gtk.ResponseType.CANCEL);
  2357. btn = md.add_button("_Delete", Gtk.ResponseType.YES);
  2358. btn.get_style_context().add_class("destructive-action");
  2359. md.set_default_response(Gtk.ResponseType.CANCEL);
  2360. md.response.connect((response_id) => {
  2361. if (response_id == Gtk.ResponseType.YES)
  2362. do_delete_directory(dir_name);
  2363. md.destroy();
  2364. });
  2365. md.show_all();
  2366. }
  2367. public void do_create_directory(string parent_dir_name, string dir_name)
  2368. {
  2369. if (dir_name == "")
  2370. return;
  2371. var path = _project.absolute_path(GLib.Path.build_filename(parent_dir_name, dir_name));
  2372. try {
  2373. GLib.File.new_for_path(path).make_directory();
  2374. } catch (Error e) {
  2375. loge(e.message);
  2376. }
  2377. }
  2378. public void on_create_directory(GLib.SimpleAction action, GLib.Variant? param)
  2379. {
  2380. string parent_dir_name = (string)param.get_child_value(0);
  2381. string dir_name = (string)param.get_child_value(1);
  2382. if (dir_name != "") {
  2383. do_create_directory(parent_dir_name, dir_name);
  2384. } else {
  2385. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Folder Name"
  2386. , this.active_window
  2387. , Gtk.DialogFlags.MODAL
  2388. , "Cancel"
  2389. , Gtk.ResponseType.CANCEL
  2390. , "Ok"
  2391. , Gtk.ResponseType.OK
  2392. , null
  2393. );
  2394. InputString sb = new InputString();
  2395. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  2396. dg.get_content_area().add(sb);
  2397. dg.response.connect((response_id) => {
  2398. if (response_id == Gtk.ResponseType.OK)
  2399. do_create_directory(parent_dir_name, sb.text.strip());
  2400. dg.destroy();
  2401. });
  2402. dg.show_all();
  2403. }
  2404. }
  2405. public async bool compile_and_reload()
  2406. {
  2407. if (yield _data_compiler.compile(_project.data_dir(), _project.platform()))
  2408. return yield refresh_all_clients();
  2409. else
  2410. return false;
  2411. }
  2412. public void do_create_script(string dir_name, string script_name, bool empty)
  2413. {
  2414. if (script_name == "")
  2415. return;
  2416. int ec = _project.create_script(dir_name, script_name, empty);
  2417. if (ec < 0) {
  2418. loge("Failed to create script %s".printf(script_name));
  2419. return;
  2420. }
  2421. compile_and_reload.begin();
  2422. }
  2423. public void on_create_script(GLib.SimpleAction action, GLib.Variant? param)
  2424. {
  2425. string dir_name = (string)param.get_child_value(0);
  2426. string script_name = (string)param.get_child_value(1);
  2427. bool empty = (bool)param.get_child_value(2);
  2428. if (script_name != "") {
  2429. do_create_script(dir_name, script_name, empty);
  2430. } else {
  2431. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Script Name"
  2432. , this.active_window
  2433. , Gtk.DialogFlags.MODAL
  2434. , "Cancel"
  2435. , Gtk.ResponseType.CANCEL
  2436. , "Ok"
  2437. , Gtk.ResponseType.OK
  2438. , null
  2439. );
  2440. InputString sb = new InputString();
  2441. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  2442. dg.get_content_area().add(sb);
  2443. dg.response.connect((response_id) => {
  2444. if (response_id == Gtk.ResponseType.OK)
  2445. do_create_script(dir_name, sb.text.strip(), empty);
  2446. dg.destroy();
  2447. });
  2448. dg.show_all();
  2449. }
  2450. }
  2451. public void do_create_unit(string dir_name, string unit_name)
  2452. {
  2453. if (unit_name == "")
  2454. return;
  2455. int ec = _project.create_unit(dir_name, unit_name);
  2456. if (ec < 0) {
  2457. loge("Failed to create unit %s".printf(unit_name));
  2458. return;
  2459. }
  2460. compile_and_reload.begin();
  2461. }
  2462. public void on_create_unit(GLib.SimpleAction action, GLib.Variant? param)
  2463. {
  2464. string dir_name = (string)param.get_child_value(0);
  2465. string unit_name = (string)param.get_child_value(1);
  2466. if (unit_name != "") {
  2467. do_create_unit(dir_name, unit_name);
  2468. } else {
  2469. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Unit Name"
  2470. , this.active_window
  2471. , Gtk.DialogFlags.MODAL
  2472. , "Cancel"
  2473. , Gtk.ResponseType.CANCEL
  2474. , "Ok"
  2475. , Gtk.ResponseType.OK
  2476. , null
  2477. );
  2478. InputString sb = new InputString();
  2479. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  2480. dg.get_content_area().add(sb);
  2481. dg.response.connect((response_id) => {
  2482. if (response_id == Gtk.ResponseType.OK)
  2483. do_create_unit(dir_name, sb.text.strip());
  2484. dg.destroy();
  2485. });
  2486. dg.show_all();
  2487. }
  2488. }
  2489. public void do_create_state_machine(string dir_name, string state_machine_name, string skeleton_name)
  2490. {
  2491. if (state_machine_name == "")
  2492. return;
  2493. int ec = _project.create_state_machine(dir_name, state_machine_name, skeleton_name != "" ? skeleton_name : null);
  2494. if (ec < 0) {
  2495. loge("Failed to create state machine %s".printf(state_machine_name));
  2496. return;
  2497. }
  2498. compile_and_reload.begin();
  2499. }
  2500. public void on_create_state_machine(GLib.SimpleAction action, GLib.Variant? param)
  2501. {
  2502. string dir_name = (string)param.get_child_value(0);
  2503. string state_machine_name = (string)param.get_child_value(1);
  2504. string skeleton_name = (string)param.get_child_value(2);
  2505. if (state_machine_name != "") {
  2506. do_create_state_machine(dir_name, state_machine_name, skeleton_name);
  2507. } else {
  2508. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("State Machine Name"
  2509. , this.active_window
  2510. , Gtk.DialogFlags.MODAL
  2511. , "Cancel"
  2512. , Gtk.ResponseType.CANCEL
  2513. , "Ok"
  2514. , Gtk.ResponseType.OK
  2515. , null
  2516. );
  2517. InputString sb = new InputString();
  2518. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  2519. dg.get_content_area().add(sb);
  2520. dg.response.connect((response_id) => {
  2521. if (response_id == Gtk.ResponseType.OK)
  2522. do_create_state_machine(dir_name, sb.text.strip(), skeleton_name);
  2523. dg.destroy();
  2524. });
  2525. dg.show_all();
  2526. }
  2527. }
  2528. public void do_create_material(string dir_name, string material_name)
  2529. {
  2530. if (material_name == "")
  2531. return;
  2532. int ec = _project.create_material(dir_name, material_name);
  2533. if (ec < 0) {
  2534. loge("Failed to create material %s".printf(material_name));
  2535. return;
  2536. }
  2537. compile_and_reload.begin();
  2538. }
  2539. public void on_create_material(GLib.SimpleAction action, GLib.Variant? param)
  2540. {
  2541. string dir_name = (string)param.get_child_value(0);
  2542. string material_name = (string)param.get_child_value(1);
  2543. if (material_name != "") {
  2544. do_create_material(dir_name, material_name);
  2545. } else {
  2546. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Material Name"
  2547. , this.active_window
  2548. , Gtk.DialogFlags.MODAL
  2549. , "Cancel"
  2550. , Gtk.ResponseType.CANCEL
  2551. , "Ok"
  2552. , Gtk.ResponseType.OK
  2553. , null
  2554. );
  2555. InputString sb = new InputString();
  2556. sb.activate.connect(() => { dg.response(Gtk.ResponseType.OK); });
  2557. dg.get_content_area().add(sb);
  2558. dg.response.connect((response_id) => {
  2559. if (response_id == Gtk.ResponseType.OK)
  2560. do_create_material(dir_name, sb.text.strip());
  2561. dg.destroy();
  2562. });
  2563. dg.show_all();
  2564. }
  2565. }
  2566. public void on_open_containing(GLib.SimpleAction action, GLib.Variant? param)
  2567. {
  2568. string path = param.get_string();
  2569. GLib.File abs_path = GLib.File.new_for_path(_project.absolute_path(path));
  2570. GLib.File? abs_parent = abs_path.get_parent();
  2571. string abs_parent_path = abs_parent != null
  2572. ? abs_parent.get_path()
  2573. : abs_path.get_path()
  2574. ;
  2575. open_directory(abs_parent_path);
  2576. }
  2577. public void delete_tree(GLib.File file) throws Error
  2578. {
  2579. GLib.FileEnumerator fe = file.enumerate_children("standard::*"
  2580. , GLib.FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  2581. );
  2582. GLib.FileInfo info = null;
  2583. while ((info = fe.next_file()) != null) {
  2584. GLib.File subfile = file.resolve_relative_path(info.get_name());
  2585. if (info.get_file_type() == GLib.FileType.DIRECTORY)
  2586. delete_tree(subfile);
  2587. else
  2588. subfile.delete();
  2589. }
  2590. file.delete();
  2591. }
  2592. public Gtk.Dialog new_package_dir_exists_dialog(string package_dir)
  2593. {
  2594. Gtk.MessageDialog md = new Gtk.MessageDialog(_deploy_dialog
  2595. , Gtk.DialogFlags.MODAL
  2596. , Gtk.MessageType.QUESTION
  2597. , Gtk.ButtonsType.NONE
  2598. , "A file named `%s` already exists.\nOverwrite?".printf(package_dir)
  2599. );
  2600. md.set_default_response(Gtk.ResponseType.NO);
  2601. Gtk.Widget btn;
  2602. md.add_button("_No", Gtk.ResponseType.NO);
  2603. btn = md.add_button("_Yes", Gtk.ResponseType.YES);
  2604. btn.get_style_context().add_class("destructive-action");
  2605. return md;
  2606. }
  2607. public GLib.File deploy_package_dir(out string config_path, string output_path, string app_identifier, TargetPlatform platform, TargetArch arch, TargetConfig config)
  2608. {
  2609. string platform_name[] =
  2610. {
  2611. "android", // TargetArch.ANDROID
  2612. "html5", // TargetArch.HTML5
  2613. "linux", // TargetArch.LINUX
  2614. "windows" // TargetArch.WINDOWS
  2615. };
  2616. string arch_name[] =
  2617. {
  2618. "x86", // TargetArch.X86
  2619. "x64", // TargetArch.X64
  2620. "arm", // TargetArch.ARM
  2621. "arm64", // TargetArch.ARM64
  2622. "wasm" // TargetArch.WASM
  2623. };
  2624. string config_name[] =
  2625. {
  2626. "release", // TargetConfig.RELEASE
  2627. "development", // TargetConfig.DEVELOPMENT
  2628. #if CROWN_DEBUG
  2629. "debug" // TargetConfig.DEBUG
  2630. #endif
  2631. };
  2632. string platform_path = Path.build_path(Path.DIR_SEPARATOR_S, output_path, platform_name[platform], arch_name[arch]);
  2633. config_path = Path.build_path(Path.DIR_SEPARATOR_S, platform_path, config_name[config]);
  2634. return GLib.File.new_for_path(Path.build_path(Path.DIR_SEPARATOR_S, config_path, app_identifier));
  2635. }
  2636. public void do_create_package_android(GLib.File package_dir
  2637. , string config_path
  2638. , string output_path
  2639. , int config
  2640. , string app_title
  2641. , string app_identifier
  2642. , int app_version_code
  2643. , string app_version_name
  2644. , string keystore_path
  2645. , string keystore_pass
  2646. , string key_alias
  2647. , string key_pass
  2648. , int arch
  2649. , string apk_name
  2650. )
  2651. {
  2652. string config_name[] =
  2653. {
  2654. "release",
  2655. "development",
  2656. #if CROWN_DEBUG
  2657. "debug"
  2658. #endif
  2659. };
  2660. AndroidDeployer android = new AndroidDeployer();
  2661. android.check_config();
  2662. logi("Creating Android package (%s)...".printf(arch == TargetArch.ARM ? "ARMv7-A" : "ARMv8-A"));
  2663. var activity_name = "MainActivity";
  2664. var package_path = package_dir.get_path();
  2665. // Architecture-agnostic paths.
  2666. var manifests_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "manifests");
  2667. var java_sources_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "java");
  2668. var app_sources_path = Path.build_path(Path.DIR_SEPARATOR_S, java_sources_path, app_identifier.replace(".", "/"));
  2669. var assets_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "assets");
  2670. var res_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "res");
  2671. var bin_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "bin");
  2672. var obj_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "obj");
  2673. var res_layout_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "layout");
  2674. var res_values_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "values");
  2675. var res_drawable_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "drawable");
  2676. var manifest_xml_path = Path.build_path(Path.DIR_SEPARATOR_S, manifests_path, "AndroidManifest.xml");
  2677. var strings_xml_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "values", "strings.xml");
  2678. var activity_java_path = Path.build_path(Path.DIR_SEPARATOR_S, app_sources_path, "%s.java".printf(activity_name));
  2679. var android_jar_path = Path.build_path(Path.DIR_SEPARATOR_S, android._sdk_path, "platforms", "android-" + android._sdk_api_level, "android.jar");
  2680. var libcrown_src_name = "libcrown-" + config_name[config] + ".so";
  2681. var libcpp_name = "libc++_shared.so";
  2682. var signed_apk = Path.build_path(Path.DIR_SEPARATOR_S, bin_path, apk_name + ".signed.apk");
  2683. var unaligned_apk = Path.build_path(Path.DIR_SEPARATOR_S, bin_path, apk_name + ".unaligned.apk");
  2684. var final_apk = Path.build_path(Path.DIR_SEPARATOR_S, config_path, apk_name + ".apk");
  2685. #if CROWN_PLATFORM_LINUX
  2686. string host_platform = "linux-x86_64";
  2687. #elif CROWN_PLATFORM_WINDOWS
  2688. string host_platform = "windows-x86_64";
  2689. #endif
  2690. // Architecture-specific paths.
  2691. string dc_platform = null;
  2692. string bin_folder = null;
  2693. string apk_arch = null;
  2694. string llvm_arch = null;
  2695. if (arch == TargetArch.ARM) {
  2696. dc_platform = "android";
  2697. bin_folder = "android-arm";
  2698. apk_arch = "armeabi-v7a";
  2699. llvm_arch = "arm-linux-androideabi";
  2700. } else if (arch == TargetArch.ARM64) {
  2701. dc_platform = "android-arm64";
  2702. bin_folder = "android-arm64";
  2703. apk_arch = "arm64-v8a";
  2704. llvm_arch = "aarch64-linux-android";
  2705. } else {
  2706. loge("Invalid architecture");
  2707. return;
  2708. }
  2709. var libcrown_src_path = Path.build_path(Path.DIR_SEPARATOR_S, "..", "..", bin_folder, "bin", libcrown_src_name);
  2710. var libcpp_src_path = Path.build_path(Path.DIR_SEPARATOR_S
  2711. , android._ndk_root_path
  2712. , "toolchains"
  2713. , "llvm"
  2714. , "prebuilt"
  2715. , host_platform
  2716. , "sysroot"
  2717. , "usr"
  2718. , "lib"
  2719. , llvm_arch
  2720. , libcpp_name
  2721. );
  2722. var lib_path_relative = Path.build_path(Path.DIR_SEPARATOR_S, "lib", apk_arch);
  2723. var lib_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, lib_path_relative);
  2724. var libcrown_path_relative = Path.build_path(Path.DIR_SEPARATOR_S, lib_path_relative, "libcrown.so");
  2725. var libcpp_path_relative = Path.build_path(Path.DIR_SEPARATOR_S, lib_path_relative, libcpp_name);
  2726. var libcrown_dst_path = Path.build_path(Path.DIR_SEPARATOR_S, lib_path, "libcrown.so");
  2727. var libcpp_dst_path = Path.build_path(Path.DIR_SEPARATOR_S, lib_path, "libc++_shared.so");
  2728. // Create Android project skeleton.
  2729. try {
  2730. GLib.File.new_for_path(manifests_path).make_directory();
  2731. GLib.File.new_for_path(app_sources_path).make_directory_with_parents();
  2732. GLib.File.new_for_path(lib_path).make_directory_with_parents();
  2733. GLib.File.new_for_path(assets_path).make_directory();
  2734. GLib.File.new_for_path(bin_path).make_directory();
  2735. GLib.File.new_for_path(obj_path).make_directory();
  2736. GLib.File.new_for_path(res_layout_path).make_directory_with_parents();
  2737. GLib.File.new_for_path(res_values_path).make_directory();
  2738. GLib.File.new_for_path(res_drawable_path).make_directory();
  2739. } catch (Error e) {
  2740. loge(e.message);
  2741. }
  2742. // Compile game data.
  2743. try {
  2744. GLib.File.new_for_path(libcrown_src_path).copy(GLib.File.new_for_path(libcrown_dst_path), GLib.FileCopyFlags.NONE);
  2745. GLib.File.new_for_path(libcpp_src_path).copy(GLib.File.new_for_path(libcpp_dst_path), GLib.FileCopyFlags.NONE);
  2746. string[] args;
  2747. // Populate Android assets folder with data.
  2748. args = new string[]
  2749. {
  2750. ENGINE_EXE,
  2751. "--source-dir",
  2752. _project.source_dir(),
  2753. "--map-source-dir",
  2754. "core",
  2755. _project.toolchain_dir(),
  2756. "--bundle-dir",
  2757. assets_path,
  2758. "--compile",
  2759. "--bundle",
  2760. "--platform",
  2761. dc_platform
  2762. };
  2763. uint32 pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  2764. int exit_status = _subprocess_launcher.wait(pid);
  2765. if (exit_status != 0) {
  2766. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  2767. return;
  2768. }
  2769. } catch (Error e) {
  2770. loge(e.message);
  2771. return;
  2772. }
  2773. // Create Android manifest.
  2774. string android_manifest = "";
  2775. android_manifest += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
  2776. android_manifest += "\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"";
  2777. android_manifest += "\n package=\"%s\"".printf(app_identifier);
  2778. android_manifest += "\n android:versionCode=\"%u\"".printf(app_version_code);
  2779. android_manifest += "\n android:versionName=\"%s\">".printf(app_version_name);
  2780. android_manifest += "\n";
  2781. android_manifest += "\n <uses-sdk android:minSdkVersion=\"23\" />";
  2782. android_manifest += "\n";
  2783. android_manifest += "\n <!-- For ConsoleServer -->";
  2784. android_manifest += "\n <uses-permission android:name=\"android.permission.INTERNET\" />";
  2785. android_manifest += "\n";
  2786. android_manifest += "\n <application";
  2787. android_manifest += "\n android:hasCode=\"true\"";
  2788. android_manifest += "\n android:label=\"%s\">".printf(app_title);
  2789. android_manifest += "\n <activity";
  2790. android_manifest += "\n android:name=\"%s.%s\"".printf(app_identifier, activity_name);
  2791. android_manifest += "\n android:configChanges=\"orientation|keyboardHidden\"";
  2792. android_manifest += "\n android:label=\"@string/activity_label\"";
  2793. android_manifest += "\n android:screenOrientation=\"landscape\"";
  2794. android_manifest += "\n android:theme=\"@android:style/Theme.NoTitleBar.Fullscreen\">";
  2795. android_manifest += "\n";
  2796. android_manifest += "\n <!-- Tell NativeActivity the name of our .so -->";
  2797. android_manifest += "\n <meta-data";
  2798. android_manifest += "\n android:name=\"android.app.lib_name\"";
  2799. android_manifest += "\n android:value=\"crown\" />";
  2800. android_manifest += "\n";
  2801. android_manifest += "\n <intent-filter>";
  2802. android_manifest += "\n <action android:name=\"android.intent.action.MAIN\" />";
  2803. android_manifest += "\n <action android:name=\"android.intent.action.VIEW\" />";
  2804. android_manifest += "\n <category android:name=\"android.intent.category.LAUNCHER\" />";
  2805. android_manifest += "\n </intent-filter>";
  2806. android_manifest += "\n </activity>";
  2807. android_manifest += "\n </application>";
  2808. android_manifest += "\n</manifest>";
  2809. android_manifest += "\n";
  2810. GLib.FileStream? fs = FileStream.open(manifest_xml_path, "w");
  2811. if (fs == null) {
  2812. loge("Failed to open '%s'".printf(manifest_xml_path));
  2813. return;
  2814. }
  2815. fs.write(android_manifest.data);
  2816. // Create Android strings.xml.
  2817. string android_strings = "";
  2818. android_strings += "<resources>";
  2819. android_strings += "\n<string name=\"activity_label\">%s</string>".printf(app_title);
  2820. android_strings += "\n</resources>";
  2821. android_strings += "\n";
  2822. fs = FileStream.open(strings_xml_path, "w");
  2823. if (fs == null) {
  2824. loge("Failed to open '%s'".printf(strings_xml_path));
  2825. return;
  2826. }
  2827. fs.write(android_strings.data);
  2828. // Create Android activity.
  2829. string android_activity = "";
  2830. android_activity += "package %s;".printf(app_identifier);
  2831. android_activity += "\n";
  2832. android_activity += "\nimport android.app.NativeActivity;";
  2833. android_activity += "\nimport android.os.Bundle;";
  2834. android_activity += "\nimport android.view.View;";
  2835. android_activity += "\n";
  2836. android_activity += "\npublic class %s extends NativeActivity".printf(activity_name);
  2837. android_activity += "\n{";
  2838. android_activity += "\n static";
  2839. android_activity += "\n {";
  2840. android_activity += "\n System.loadLibrary(\"crown\");";
  2841. android_activity += "\n }";
  2842. android_activity += "\n";
  2843. android_activity += "\n @Override";
  2844. android_activity += "\n public void onCreate(Bundle savedInstanceState) {";
  2845. android_activity += "\n super.onCreate(savedInstanceState);";
  2846. android_activity += "\n // Init additional stuff here (Ads etc.)";
  2847. android_activity += "\n }";
  2848. android_activity += "\n";
  2849. android_activity += "\n @Override";
  2850. android_activity += "\n public void onDestroy() {";
  2851. android_activity += "\n // Destroy additional stuff here (Ads etc)";
  2852. android_activity += "\n super.onDestroy();";
  2853. android_activity += "\n }";
  2854. android_activity += "\n";
  2855. android_activity += "\n @Override";
  2856. android_activity += "\n public void onWindowFocusChanged(boolean hasFocus) {";
  2857. android_activity += "\n super.onWindowFocusChanged(hasFocus);";
  2858. android_activity += "\n if (hasFocus) {";
  2859. android_activity += "\n hideSystemUI();";
  2860. android_activity += "\n }";
  2861. android_activity += "\n }";
  2862. android_activity += "\n";
  2863. android_activity += "\n public void hideSystemUI() {";
  2864. android_activity += "\n // Enables regular immersive mode.";
  2865. android_activity += "\n // For \"lean back\" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.";
  2866. android_activity += "\n // Or for \"sticky immersive,\" replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY";
  2867. android_activity += "\n View decorView = getWindow().getDecorView();";
  2868. android_activity += "\n decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE";
  2869. android_activity += "\n // Set the content to appear under the system bars so that the";
  2870. android_activity += "\n // content doesn't resize when the system bars hide and show.";
  2871. android_activity += "\n | View.SYSTEM_UI_FLAG_LAYOUT_STABLE";
  2872. android_activity += "\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION";
  2873. android_activity += "\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN";
  2874. android_activity += "\n // Hide the nav bar and status bar";
  2875. android_activity += "\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION";
  2876. android_activity += "\n | View.SYSTEM_UI_FLAG_FULLSCREEN";
  2877. android_activity += "\n );";
  2878. android_activity += "\n }";
  2879. android_activity += "\n";
  2880. android_activity += "\n public void showSystemUI() {";
  2881. android_activity += "\n // Shows the system bars by removing all the flags";
  2882. android_activity += "\n // except for the ones that make the content appear under the system bars.";
  2883. android_activity += "\n View decorView = getWindow().getDecorView();";
  2884. android_activity += "\n decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE";
  2885. android_activity += "\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION";
  2886. android_activity += "\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN";
  2887. android_activity += "\n );";
  2888. android_activity += "\n }";
  2889. android_activity += "\n}";
  2890. android_activity += "\n";
  2891. fs = FileStream.open(activity_java_path, "w");
  2892. if (fs == null) {
  2893. loge("Failed to open '%s'".printf(activity_java_path));
  2894. return;
  2895. }
  2896. fs.write(android_activity.data);
  2897. // Compile java NativeActivity.
  2898. Thread<int> javac = new Thread<int>("javac", () => {
  2899. try {
  2900. string[] args = new string[]
  2901. {
  2902. android._javac_path,
  2903. "-verbose",
  2904. "-source",
  2905. "8", // https://docs.oracle.com/javase/1.5.0/docs/relnotes/version-5.0.html
  2906. "-target",
  2907. "8", // https://docs.oracle.com/javase/1.5.0/docs/relnotes/version-5.0.html
  2908. "-d",
  2909. obj_path,
  2910. "-classpath",
  2911. "java",
  2912. "-bootclasspath",
  2913. android_jar_path,
  2914. activity_java_path
  2915. };
  2916. var sl = new GLib.SubprocessLauncher(subprocess_flags());
  2917. sl.spawnv(args);
  2918. } catch (Error e) {
  2919. loge(e.message);
  2920. return -1;
  2921. }
  2922. return 0;
  2923. });
  2924. javac.join();
  2925. // Generate Android APK.
  2926. new Thread<int>("post-javac", () => {
  2927. // FIXME: just wait() for javac to terminate...
  2928. var class_path = Path.build_path(Path.DIR_SEPARATOR_S
  2929. , obj_path
  2930. , app_identifier.replace(".", "/")
  2931. , "%s.class".printf(activity_name)
  2932. );
  2933. var class_file = GLib.File.new_for_path(class_path);
  2934. // Wait for javac to generate the .class file.
  2935. GLib.Timer timer = new GLib.Timer();
  2936. timer.start();
  2937. while (!class_file.query_exists() && timer.elapsed() < 5) {
  2938. GLib.Thread.usleep(500*1000);
  2939. }
  2940. if (!class_file.query_exists()) {
  2941. loge("Failed to generate .class file");
  2942. return -1;
  2943. }
  2944. // Generate remaining APK stuff.
  2945. string[] args;
  2946. uint32 pid;
  2947. int exit_status;
  2948. try {
  2949. args = new string[]
  2950. {
  2951. android._d8_path,
  2952. "--output",
  2953. bin_path,
  2954. class_path,
  2955. "--no-desugaring"
  2956. };
  2957. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  2958. exit_status = _subprocess_launcher.wait(pid);
  2959. if (exit_status != 0) {
  2960. loge("Failed to generate dex file. exit_status %d".printf(exit_status));
  2961. return -1;
  2962. }
  2963. args = new string[]
  2964. {
  2965. android._aapt_path,
  2966. "package",
  2967. "-f",
  2968. "-m",
  2969. "-F",
  2970. unaligned_apk,
  2971. "-M",
  2972. manifest_xml_path,
  2973. "-S",
  2974. res_path,
  2975. "-A",
  2976. assets_path,
  2977. "-I",
  2978. android_jar_path
  2979. };
  2980. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  2981. exit_status = _subprocess_launcher.wait(pid);
  2982. if (exit_status != 0) {
  2983. loge("Failed to do something with the APK. exit_status %d".printf(exit_status));
  2984. return -1;
  2985. }
  2986. args = new string[]
  2987. {
  2988. android._aapt_path,
  2989. "add",
  2990. unaligned_apk,
  2991. "classes.dex"
  2992. };
  2993. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, bin_path);
  2994. exit_status = _subprocess_launcher.wait(pid);
  2995. if (exit_status != 0) {
  2996. loge("Failed to add classes.dex to APK. exit_status %d".printf(exit_status));
  2997. return -1;
  2998. }
  2999. args = new string[]
  3000. {
  3001. android._aapt_path,
  3002. "add",
  3003. unaligned_apk,
  3004. libcrown_path_relative.replace("\\", "/"),
  3005. libcpp_path_relative.replace("\\", "/")
  3006. };
  3007. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, package_path);
  3008. exit_status = _subprocess_launcher.wait(pid);
  3009. if (exit_status != 0) {
  3010. loge("Failed to add libs to APK. exit_status %d".printf(exit_status));
  3011. return -1;
  3012. }
  3013. args = new string[]
  3014. {
  3015. android._jarsigner_path,
  3016. "-keystore",
  3017. keystore_path,
  3018. "-storepass",
  3019. keystore_pass,
  3020. "-keypass",
  3021. key_pass,
  3022. "-signedjar",
  3023. signed_apk,
  3024. unaligned_apk,
  3025. key_alias
  3026. };
  3027. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3028. exit_status = _subprocess_launcher.wait(pid);
  3029. if (exit_status != 0) {
  3030. loge("Failed sign APK. exit_status %d".printf(exit_status));
  3031. return -1;
  3032. }
  3033. args = new string[]
  3034. {
  3035. android._zipalign_path,
  3036. "-f",
  3037. "4",
  3038. signed_apk,
  3039. final_apk
  3040. };
  3041. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3042. exit_status = _subprocess_launcher.wait(pid);
  3043. if (exit_status != 0) {
  3044. loge("Failed align APK. exit_status %d".printf(exit_status));
  3045. return -1;
  3046. }
  3047. } catch (Error e) {
  3048. loge(e.message);
  3049. loge("Failed to deploy '%s'".printf(app_title));
  3050. return -1;
  3051. }
  3052. logi("Done: #FILE(%s)".printf(config_path));
  3053. return 0;
  3054. });
  3055. }
  3056. public void on_create_package_android(GLib.SimpleAction action, GLib.Variant? param)
  3057. {
  3058. var output_path = (string)param.get_child_value(0);
  3059. var config = (int)param.get_child_value(1);
  3060. var app_title = (string)param.get_child_value(2);
  3061. var app_identifier = (string)param.get_child_value(3);
  3062. var app_version_code = (int)param.get_child_value(4);
  3063. var app_version_name = (string)param.get_child_value(5);
  3064. var keystore_path = (string)param.get_child_value(6);
  3065. var keystore_pass = (string)param.get_child_value(7);
  3066. var key_alias = (string)param.get_child_value(8);
  3067. var key_pass = (string)param.get_child_value(9);
  3068. var arch = (int)param.get_child_value(10);
  3069. var apk_name = app_identifier + "-" + app_version_name;
  3070. string config_path;
  3071. GLib.File package_dir = deploy_package_dir(out config_path
  3072. , output_path
  3073. , apk_name
  3074. , TargetPlatform.ANDROID
  3075. , arch
  3076. , (TargetConfig)config
  3077. );
  3078. if (package_dir.query_exists()) {
  3079. Gtk.Dialog dlg = new_package_dir_exists_dialog(package_dir.get_basename());
  3080. dlg.response.connect((response_id) => {
  3081. if (response_id == Gtk.ResponseType.YES) {
  3082. try {
  3083. delete_tree(package_dir);
  3084. package_dir.make_directory_with_parents();
  3085. do_create_package_android(package_dir
  3086. , config_path
  3087. , output_path
  3088. , config
  3089. , app_title
  3090. , app_identifier
  3091. , app_version_code
  3092. , app_version_name
  3093. , keystore_path
  3094. , keystore_pass
  3095. , key_alias
  3096. , key_pass
  3097. , arch
  3098. , apk_name
  3099. );
  3100. } catch (Error e) {
  3101. loge(e.message);
  3102. }
  3103. }
  3104. dlg.destroy();
  3105. });
  3106. dlg.show_all();
  3107. } else {
  3108. try {
  3109. package_dir.make_directory_with_parents();
  3110. do_create_package_android(package_dir
  3111. , config_path
  3112. , output_path
  3113. , config
  3114. , app_title
  3115. , app_identifier
  3116. , app_version_code
  3117. , app_version_name
  3118. , keystore_path
  3119. , keystore_pass
  3120. , key_alias
  3121. , key_pass
  3122. , arch
  3123. , apk_name
  3124. );
  3125. } catch (Error e) {
  3126. loge(e.message);
  3127. }
  3128. }
  3129. }
  3130. public void do_create_package_html5(GLib.File package_dir
  3131. , string output_path
  3132. , int config
  3133. , string app_title
  3134. , string exe_name
  3135. )
  3136. {
  3137. string config_name[] =
  3138. {
  3139. "release",
  3140. "development",
  3141. #if CROWN_DEBUG
  3142. "debug"
  3143. #endif
  3144. };
  3145. HTML5Deployer html5 = new HTML5Deployer();
  3146. html5.check_config();
  3147. logi("Creating HTML5 package...");
  3148. string package_path = package_dir.get_path();
  3149. // Create data bundle.
  3150. try {
  3151. string[] args;
  3152. string tmp_bundle_dir = GLib.DirUtils.make_tmp("XXXXXX");
  3153. args = new string[]
  3154. {
  3155. ENGINE_EXE,
  3156. "--source-dir",
  3157. _project.source_dir(),
  3158. "--map-source-dir",
  3159. "core",
  3160. _project.toolchain_dir(),
  3161. "--bundle-dir",
  3162. tmp_bundle_dir,
  3163. "--compile",
  3164. "--bundle",
  3165. "--platform",
  3166. "html5"
  3167. };
  3168. var pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3169. var exit_status = _subprocess_launcher.wait(pid);
  3170. if (exit_status != 0) {
  3171. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  3172. return;
  3173. }
  3174. // Copy runtime executables to package folder.
  3175. var runtime_name_src = "crown-%s".printf(config_name[config]);
  3176. var runtime_path_src = Path.build_path(Path.DIR_SEPARATOR_S, "..", "..", "wasm", "bin", runtime_name_src);
  3177. var runtime_name_dst = Path.build_filename(package_path, runtime_name_src);
  3178. var src = File.new_for_path(runtime_path_src + ".js");
  3179. var dst = File.new_for_path(runtime_name_dst + ".js");
  3180. src.copy(dst, FileCopyFlags.OVERWRITE);
  3181. try {
  3182. src = File.new_for_path(runtime_path_src + ".worker.js");
  3183. dst = File.new_for_path(runtime_name_dst + ".worker.js");
  3184. src.copy(dst, FileCopyFlags.OVERWRITE);
  3185. } catch (GLib.Error e) {
  3186. // NOOP: newer emscripten versions embed .worker.js into main .js.
  3187. }
  3188. src = File.new_for_path(runtime_path_src + ".wasm");
  3189. dst = File.new_for_path(runtime_name_dst + ".wasm");
  3190. src.copy(dst, FileCopyFlags.OVERWRITE);
  3191. // Package bundle data with emscripten's file_packager.
  3192. args = new string[]
  3193. {
  3194. Path.build_path(Path.DIR_SEPARATOR_S, html5._emscripten_sdk_path, "tools", "file_packager"),
  3195. Path.build_path(Path.DIR_SEPARATOR_S, package_path, "data.bin"),
  3196. "--preload",
  3197. "./data",
  3198. "--js-output=" + Path.build_path(Path.DIR_SEPARATOR_S, package_path, "data.js")
  3199. };
  3200. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, tmp_bundle_dir);
  3201. exit_status = _subprocess_launcher.wait(pid);
  3202. delete_tree(GLib.File.new_for_path(tmp_bundle_dir));
  3203. if (exit_status != 0) {
  3204. loge("Failed to package data.js. exit_status %d".printf(exit_status));
  3205. return;
  3206. }
  3207. // Generate index.html.
  3208. var index_html_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "index.html");
  3209. string index_html = "";
  3210. index_html += "\n<!doctype html>";
  3211. index_html += "\n<html lang=\"en-us\">";
  3212. index_html += "\n<head>";
  3213. index_html += "\n<meta charset=\"utf-8\">";
  3214. index_html += "\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
  3215. index_html += "\n<style>";
  3216. index_html += "\n body {";
  3217. index_html += "\n margin: 0px;";
  3218. index_html += "\n background-color: black;";
  3219. index_html += "\n }";
  3220. index_html += "\n .app {";
  3221. index_html += "\n display: block;";
  3222. index_html += "\n border: 0px;";
  3223. index_html += "\n margin: 0px;";
  3224. index_html += "\n position: absolute;";
  3225. index_html += "\n top: 0;";
  3226. index_html += "\n left: 0;";
  3227. index_html += "\n width: 100%;";
  3228. index_html += "\n height: 100%;";
  3229. index_html += "\n background-color: black;";
  3230. index_html += "\n }";
  3231. index_html += "\n</style>";
  3232. index_html += "\n</head>";
  3233. index_html += "\n<body>";
  3234. index_html += "\n<canvas class=\"app\" id=\"canvas\" oncontextmenu=\"event.preventDefault()\" tabindex=-1></canvas>";
  3235. index_html += "\n<script type='text/javascript'>";
  3236. index_html += "\n var Module = {";
  3237. index_html += "\n preRun: [],";
  3238. index_html += "\n postRun: [],";
  3239. index_html += "\n canvas: (() => {";
  3240. index_html += "\n var canvas = document.getElementById('canvas');";
  3241. index_html += "\n canvas.addEventListener(\"webglcontextlost\", (e) => {";
  3242. index_html += "\n alert('WebGL context lost. You will need to reload the page.');";
  3243. index_html += "\n e.preventDefault();";
  3244. index_html += "\n }, false);";
  3245. index_html += "\n return canvas;";
  3246. index_html += "\n })(),";
  3247. index_html += "\n setStatus: (text) => { },";
  3248. index_html += "\n monitorRunDependencies: (left) => { }";
  3249. index_html += "\n };";
  3250. index_html += "\n window.onerror = (event) => {";
  3251. index_html += "\n console.error('onerror: ' + event.message);";
  3252. index_html += "\n };";
  3253. index_html += "\n</script>";
  3254. index_html += "\n<script async type=\"text/javascript\" src=\"data.js\"></script>";
  3255. index_html += "\n<script async type=\"text/javascript\" src=\"%s.js\"></script>".printf(runtime_name_src);
  3256. index_html += "\n</body>";
  3257. index_html += "\n</html>";
  3258. index_html += "\n";
  3259. GLib.FileStream? fs = FileStream.open(index_html_path, "w");
  3260. if (fs == null) {
  3261. loge("Failed to open '%s'".printf(index_html_path));
  3262. return;
  3263. }
  3264. fs.write(index_html.data);
  3265. } catch (Error e) {
  3266. loge(e.message);
  3267. loge("Failed to deploy '%s'".printf(app_title));
  3268. return;
  3269. }
  3270. logi("Done: #FILE(%s)".printf(package_path));
  3271. }
  3272. public void on_create_package_html5(GLib.SimpleAction action, GLib.Variant? param)
  3273. {
  3274. var output_path = (string)param.get_child_value(0);
  3275. var config = (int)param.get_child_value(1);
  3276. var app_title = (string)param.get_child_value(2);
  3277. var exe_name = app_title.replace(" ", "_").down();
  3278. string config_path;
  3279. GLib.File package_dir = deploy_package_dir(out config_path
  3280. , output_path
  3281. , exe_name
  3282. , TargetPlatform.HTML5
  3283. , TargetArch.WASM
  3284. , (TargetConfig)config
  3285. );
  3286. if (package_dir.query_exists()) {
  3287. Gtk.Dialog dlg = new_package_dir_exists_dialog(package_dir.get_basename());
  3288. dlg.response.connect((response_id) => {
  3289. if (response_id == Gtk.ResponseType.YES) {
  3290. try {
  3291. delete_tree(package_dir);
  3292. package_dir.make_directory_with_parents();
  3293. do_create_package_html5(package_dir, output_path, config, app_title, exe_name);
  3294. } catch (Error e) {
  3295. loge(e.message);
  3296. }
  3297. }
  3298. dlg.destroy();
  3299. });
  3300. dlg.show_all();
  3301. } else {
  3302. try {
  3303. package_dir.make_directory_with_parents();
  3304. do_create_package_html5(package_dir, output_path, config, app_title, exe_name);
  3305. } catch (Error e) {
  3306. loge(e.message);
  3307. }
  3308. }
  3309. }
  3310. public void do_create_package_linux(GLib.File package_dir
  3311. , string output_path
  3312. , int config
  3313. , string app_title
  3314. , string exe_name
  3315. )
  3316. {
  3317. string config_name[] =
  3318. {
  3319. "release",
  3320. "development",
  3321. #if CROWN_DEBUG
  3322. "debug"
  3323. #endif
  3324. };
  3325. logi("Creating Linux package...");
  3326. string package_path = package_dir.get_path();
  3327. // Create data bundle.
  3328. try {
  3329. string args[] =
  3330. {
  3331. ENGINE_EXE,
  3332. "--source-dir",
  3333. _project.source_dir(),
  3334. "--map-source-dir",
  3335. "core",
  3336. _project.toolchain_dir(),
  3337. "--bundle-dir",
  3338. package_path,
  3339. "--compile",
  3340. "--bundle",
  3341. "--platform",
  3342. "linux"
  3343. };
  3344. uint32 compiler = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3345. int exit_status = _subprocess_launcher.wait(compiler);
  3346. if (exit_status != 0) {
  3347. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  3348. return;
  3349. }
  3350. GLib.File engine_exe_src = File.new_for_path(EXE_PREFIX + "crown-%s".printf(config_name[config]) + EXE_SUFFIX);
  3351. GLib.File engine_exe_dst = File.new_for_path(Path.build_filename(package_path, exe_name + EXE_SUFFIX));
  3352. engine_exe_src.copy(engine_exe_dst, FileCopyFlags.OVERWRITE);
  3353. } catch (Error e) {
  3354. loge(e.message);
  3355. loge("Failed to deploy '%s'".printf(app_title));
  3356. return;
  3357. }
  3358. logi("Done: #FILE(%s)".printf(package_path));
  3359. }
  3360. public void on_create_package_linux(GLib.SimpleAction action, GLib.Variant? param)
  3361. {
  3362. var output_path = (string)param.get_child_value(0);
  3363. var config = (int)param.get_child_value(1);
  3364. var app_title = (string)param.get_child_value(2);
  3365. var exe_name = app_title.replace(" ", "_").down();
  3366. string config_path;
  3367. GLib.File package_dir = deploy_package_dir(out config_path
  3368. , output_path
  3369. , exe_name
  3370. , TargetPlatform.LINUX
  3371. , TargetArch.X64
  3372. , (TargetConfig)config
  3373. );
  3374. if (package_dir.query_exists()) {
  3375. Gtk.Dialog dlg = new_package_dir_exists_dialog(package_dir.get_basename());
  3376. dlg.response.connect((response_id) => {
  3377. if (response_id == Gtk.ResponseType.YES) {
  3378. try {
  3379. delete_tree(package_dir);
  3380. package_dir.make_directory_with_parents();
  3381. do_create_package_linux(package_dir, output_path, config, app_title, exe_name);
  3382. } catch (Error e) {
  3383. loge(e.message);
  3384. }
  3385. }
  3386. dlg.destroy();
  3387. });
  3388. dlg.show_all();
  3389. } else {
  3390. try {
  3391. package_dir.make_directory_with_parents();
  3392. do_create_package_linux(package_dir, output_path, config, app_title, exe_name);
  3393. } catch (Error e) {
  3394. loge(e.message);
  3395. }
  3396. }
  3397. }
  3398. void do_create_package_windows(GLib.File package_dir
  3399. , string output_path
  3400. , int config
  3401. , string app_title
  3402. , string exe_name
  3403. )
  3404. {
  3405. string config_name[] =
  3406. {
  3407. "release",
  3408. "development",
  3409. #if CROWN_DEBUG
  3410. "debug"
  3411. #endif
  3412. };
  3413. logi("Creating Windows package");
  3414. string package_path = package_dir.get_path();
  3415. // Create data bundle.
  3416. try {
  3417. string args[] =
  3418. {
  3419. ENGINE_EXE,
  3420. "--source-dir",
  3421. _project.source_dir(),
  3422. "--map-source-dir",
  3423. "core",
  3424. _project.toolchain_dir(),
  3425. "--bundle-dir",
  3426. package_path,
  3427. "--compile",
  3428. "--bundle",
  3429. "--platform",
  3430. "windows"
  3431. };
  3432. uint32 compiler = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3433. int exit_status = _subprocess_launcher.wait(compiler);
  3434. if (exit_status != 0) {
  3435. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  3436. return;
  3437. }
  3438. GLib.File engine_exe_src = File.new_for_path(EXE_PREFIX + "crown-%s".printf(config_name[config]) + EXE_SUFFIX);
  3439. GLib.File engine_exe_dst = File.new_for_path(Path.build_filename(package_path, exe_name + EXE_SUFFIX));
  3440. engine_exe_src.copy(engine_exe_dst, FileCopyFlags.OVERWRITE);
  3441. string openal_name = "openal-release.dll";
  3442. GLib.File openal_dll_src = File.new_for_path(openal_name);
  3443. GLib.File openal_dll_dst = File.new_for_path(Path.build_filename(package_path, openal_name));
  3444. openal_dll_src.copy(openal_dll_dst, FileCopyFlags.OVERWRITE);
  3445. try {
  3446. string lua_name = "lua51.dll";
  3447. GLib.File lua_dll_src = File.new_for_path(lua_name);
  3448. GLib.File lua_dll_dst = File.new_for_path(Path.build_filename(package_path, lua_name));
  3449. lua_dll_src.copy(lua_dll_dst, FileCopyFlags.OVERWRITE);
  3450. } catch (Error e) {
  3451. // Ignore: runtime's MinGW builds statically link luajit.
  3452. }
  3453. } catch (Error e) {
  3454. loge("%s".printf(e.message));
  3455. loge("Failed to deploy '%s'".printf(app_title));
  3456. return;
  3457. }
  3458. logi("Done: #FILE(%s)".printf(package_path));
  3459. }
  3460. public void on_create_package_windows(GLib.SimpleAction action, GLib.Variant? param)
  3461. {
  3462. var output_path = (string)param.get_child_value(0);
  3463. var config = (int)param.get_child_value(1);
  3464. var app_title = (string)param.get_child_value(2);
  3465. var exe_name = app_title.replace(" ", "_").down();
  3466. string config_path;
  3467. GLib.File package_dir = deploy_package_dir(out config_path
  3468. , output_path
  3469. , exe_name
  3470. , TargetPlatform.WINDOWS
  3471. , TargetArch.X64
  3472. , (TargetConfig)config
  3473. );
  3474. if (package_dir.query_exists()) {
  3475. Gtk.Dialog dlg = new_package_dir_exists_dialog(package_dir.get_basename());
  3476. dlg.response.connect((response_id) => {
  3477. if (response_id == Gtk.ResponseType.YES) {
  3478. try {
  3479. delete_tree(package_dir);
  3480. package_dir.make_directory_with_parents();
  3481. do_create_package_windows(package_dir, output_path, config, app_title, exe_name);
  3482. } catch (Error e) {
  3483. loge(e.message);
  3484. }
  3485. }
  3486. dlg.destroy();
  3487. });
  3488. dlg.show_all();
  3489. } else {
  3490. try {
  3491. package_dir.make_directory_with_parents();
  3492. do_create_package_windows(package_dir, output_path, config, app_title, exe_name);
  3493. } catch (Error e) {
  3494. loge(e.message);
  3495. }
  3496. }
  3497. }
  3498. public void on_unit_save_as_prefab(GLib.SimpleAction action, GLib.Variant? param)
  3499. {
  3500. string guid = (string)param.get_child_value(0);
  3501. string name = (string)param.get_child_value(1);
  3502. SaveResourceDialog srd = new SaveResourceDialog("Save Prefab As..."
  3503. , this.active_window
  3504. , OBJECT_TYPE_UNIT
  3505. , name
  3506. , _project
  3507. );
  3508. srd.safer_response.connect((response_id, path) => {
  3509. if (response_id == Gtk.ResponseType.ACCEPT && path != null) {
  3510. string prefab_filename = _project.resource_filename(path);
  3511. string prefab_path = ResourceId.normalize(prefab_filename);
  3512. string prefab_name = ResourceId.name(prefab_path);
  3513. Guid unit_id = Guid.parse(guid);
  3514. if (Unit(_database, unit_id).prefab() == prefab_name) {
  3515. Gtk.MessageDialog md = new Gtk.MessageDialog(this.active_window
  3516. , Gtk.DialogFlags.MODAL
  3517. , Gtk.MessageType.ERROR
  3518. , Gtk.ButtonsType.NONE
  3519. , "Cannot save prefab '%s' over itself".printf(prefab_name)
  3520. );
  3521. md.add_button("_Ok", Gtk.ResponseType.OK);
  3522. md.set_default_response(Gtk.ResponseType.OK);
  3523. md.response.connect(() => { md.destroy(); });
  3524. md.show_all();
  3525. } else if (_database.has_object(unit_id)) {
  3526. Guid prefab_id = Guid.new_guid();
  3527. Database new_database = new Database(_project);
  3528. _database.duplicate(unit_id, prefab_id, new_database);
  3529. new_database.save(path, prefab_id);
  3530. compile_and_reload.begin((obj, res) => {
  3531. if (compile_and_reload.end(res)) {
  3532. _level.replace_unit(unit_id, prefab_name);
  3533. }
  3534. });
  3535. }
  3536. }
  3537. srd.destroy();
  3538. });
  3539. srd.show_all();
  3540. srd.present();
  3541. }
  3542. public void on_open_unit(GLib.SimpleAction action, GLib.Variant? param)
  3543. {
  3544. string unit_name = param.get_string();
  3545. if (_unit_editor_dialog == null) {
  3546. _unit_editor_dialog = new UnitEditor(this
  3547. , _project
  3548. , "core/editors/level_editor"
  3549. , "127.0.0.1"
  3550. , 10444
  3551. , (uint)_preferences_dialog._undo_redo_max_size.value * 1024 * 1024
  3552. );
  3553. _unit_editor_dialog.set_transient_for(_level_editor_window);
  3554. _unit_editor_dialog.saved.connect(on_unit_editor_saved);
  3555. _runtimes.add(_unit_editor_dialog._runtime);
  3556. }
  3557. _unit_editor_dialog.show_all();
  3558. _unit_editor_dialog.present();
  3559. _unit_editor_dialog.set_unit(unit_name);
  3560. }
  3561. public void on_unit_editor_saved()
  3562. {
  3563. compile_and_reload.begin((obj, res) => {
  3564. if (compile_and_reload.end(res)) {
  3565. ui_read_selection(_database_editor._selection.to_array());
  3566. }
  3567. });
  3568. }
  3569. public void set_autosave_timer(uint minutes)
  3570. {
  3571. if (_save_timer_id > 0)
  3572. GLib.Source.remove(_save_timer_id);
  3573. _save_timer_id = GLib.Timeout.add_seconds(minutes*60, save_timeout);
  3574. }
  3575. public void menu_set_enabled(bool enabled, GLib.ActionEntry[] entries, string[]? whitelist = null)
  3576. {
  3577. for (int ii = 0; ii < entries.length; ++ii) {
  3578. string action_name = entries[ii].name;
  3579. int jj = 0;
  3580. if (whitelist != null) {
  3581. for (; jj < whitelist.length; ++jj) {
  3582. if (action_name == whitelist[jj])
  3583. break;
  3584. }
  3585. }
  3586. if (whitelist == null || whitelist != null && jj == whitelist.length) {
  3587. GLib.SimpleAction sa = this.lookup_action(action_name) as GLib.SimpleAction;
  3588. if (sa != null)
  3589. sa.set_enabled(enabled);
  3590. }
  3591. }
  3592. }
  3593. public void set_conflicting_accels(bool on)
  3594. {
  3595. if (on) {
  3596. this.set_accels_for_action("app.tool(0)", _tool_place_accels);
  3597. this.set_accels_for_action("app.tool(1)", _tool_move_accels);
  3598. this.set_accels_for_action("app.tool(2)", _tool_rotate_accels);
  3599. this.set_accels_for_action("app.tool(3)", _tool_scale_accels);
  3600. this.set_accels_for_action("app.delete", _delete_accels);
  3601. this.set_accels_for_action("viewport.camera-view(0)", _camera_view_perspective_accels);
  3602. this.set_accels_for_action("viewport.camera-view(1)", _camera_view_front_accels);
  3603. this.set_accels_for_action("viewport.camera-view(2)", _camera_view_back_accels);
  3604. this.set_accels_for_action("viewport.camera-view(3)", _camera_view_right_accels);
  3605. this.set_accels_for_action("viewport.camera-view(4)", _camera_view_left_accels);
  3606. this.set_accels_for_action("viewport.camera-view(5)", _camera_view_top_accels);
  3607. this.set_accels_for_action("viewport.camera-view(6)", _camera_view_bottom_accels);
  3608. this.set_accels_for_action("viewport.camera-frame-selected", _camera_frame_selected_accels);
  3609. this.set_accels_for_action("app.camera-frame-all", _camera_frame_all_accels);
  3610. } else {
  3611. this.set_accels_for_action("app.tool(0)", {});
  3612. this.set_accels_for_action("app.tool(1)", {});
  3613. this.set_accels_for_action("app.tool(2)", {});
  3614. this.set_accels_for_action("app.tool(3)", {});
  3615. this.set_accels_for_action("app.delete", {});
  3616. this.set_accels_for_action("viewport.camera-view(0)", {});
  3617. this.set_accels_for_action("viewport.camera-view(1)", {});
  3618. this.set_accels_for_action("viewport.camera-view(2)", {});
  3619. this.set_accels_for_action("viewport.camera-view(3)", {});
  3620. this.set_accels_for_action("viewport.camera-view(4)", {});
  3621. this.set_accels_for_action("viewport.camera-view(5)", {});
  3622. this.set_accels_for_action("viewport.camera-view(6)", {});
  3623. this.set_accels_for_action("viewport.camera-frame-selected", {});
  3624. this.set_accels_for_action("app.camera-frame-all", {});
  3625. }
  3626. }
  3627. public void entry_any_focus_in(Gtk.Widget widget)
  3628. {
  3629. set_conflicting_accels(false);
  3630. }
  3631. public void entry_any_focus_out(Gtk.Widget widget)
  3632. {
  3633. set_conflicting_accels(true);
  3634. }
  3635. public void show_panel(string name, Gtk.StackTransitionType stt = Gtk.StackTransitionType.NONE)
  3636. {
  3637. _main_stack.set_visible_child_full(name, stt);
  3638. if (name == PANEL_EDITOR) {
  3639. // FIXME: save/restore last known window state
  3640. int win_w;
  3641. int win_h;
  3642. this.active_window.get_size(out win_w, out win_h);
  3643. _editor_pane.set_position(320);
  3644. _content_pane.set_position(win_h - 250);
  3645. _inspector_pane.set_position(win_h - 600);
  3646. _main_pane.set_position(win_w - 375);
  3647. menu_set_enabled(true, action_entries_file);
  3648. menu_set_enabled(true, action_entries_edit);
  3649. menu_set_enabled(true, action_entries_create);
  3650. menu_set_enabled(true, action_entries_camera);
  3651. menu_set_enabled(true, action_entries_view);
  3652. menu_set_enabled(true, action_entries_debug);
  3653. menu_set_enabled(true, action_entries_help);
  3654. } else if (name == PANEL_PROJECTS_LIST
  3655. || name == PANEL_NEW_PROJECT
  3656. ) {
  3657. menu_set_enabled(false, action_entries_file, {"new-project", "add-project", "open-project", "open-project-null", "open-projects-list", "remove-project", "quit"});
  3658. menu_set_enabled(false, action_entries_edit);
  3659. menu_set_enabled(false, action_entries_create);
  3660. menu_set_enabled(false, action_entries_camera);
  3661. menu_set_enabled(false, action_entries_view);
  3662. menu_set_enabled(false, action_entries_debug);
  3663. menu_set_enabled(true, action_entries_help);
  3664. }
  3665. }
  3666. public void on_set_placeable(GLib.SimpleAction action, GLib.Variant? param)
  3667. {
  3668. _placeable_type = (string)param.get_child_value(0);
  3669. _placeable_name = (string)param.get_child_value(1);
  3670. _editor.send_script(LevelEditorApi.set_placeable(_placeable_type, _placeable_name));
  3671. activate_action("tool", new GLib.Variant.int32(ToolType.PLACE));
  3672. }
  3673. public void on_project_reset()
  3674. {
  3675. if (!_project.is_loaded())
  3676. return;
  3677. // Save per-project data.
  3678. try {
  3679. string path = GLib.Path.build_filename(_project.user_dir(), "project_store.sjson");
  3680. SJSON.save(_project_store.encode(), path);
  3681. } catch (JsonWriteError e) {
  3682. loge(e.message);
  3683. }
  3684. // Destroy dialogs.
  3685. _texture_settings_dialog = null;
  3686. _deploy_dialog = null;
  3687. }
  3688. public void on_project_loaded()
  3689. {
  3690. // Load per-project data.
  3691. try {
  3692. string path = GLib.Path.build_filename(_project.user_dir(), "project_store.sjson");
  3693. _project_store.decode(SJSON.load_from_path(path));
  3694. }
  3695. catch (JsonSyntaxError e) {
  3696. // No-op.
  3697. }
  3698. }
  3699. public SelectResourceDialog new_select_resource_dialog(string resource_type)
  3700. {
  3701. return new SelectResourceDialog(resource_type, _project_store, this.active_window);
  3702. }
  3703. public void on_level_treeview_selection_changed(Gee.ArrayList<Guid?> selection)
  3704. {
  3705. _database_editor.selection_read(selection.to_array());
  3706. ui_read_selection.disconnect(_level_treeview.read_selection);
  3707. ui_read_selection(_database_editor._selection.to_array());
  3708. ui_read_selection.connect(_level_treeview.read_selection);
  3709. _database_editor.send_selection(_editor);
  3710. _editor_viewport.frame();
  3711. }
  3712. public void on_selection_changed()
  3713. {
  3714. ui_read_selection(_database_editor._selection.to_array());
  3715. _database_editor.send_selection(_editor);
  3716. _editor_viewport.frame();
  3717. }
  3718. }
  3719. // Global paths
  3720. public static GLib.File _toolchain_dir;
  3721. public static GLib.File _templates_dir;
  3722. public static GLib.File _data_dir;
  3723. public static GLib.File _config_dir;
  3724. public static GLib.File _cache_dir;
  3725. public static GLib.File _logs_dir;
  3726. public static GLib.File _thumbnails_dir;
  3727. public static GLib.File _thumbnails_normal_dir;
  3728. public static GLib.File _documents_dir;
  3729. public static GLib.File _log_file;
  3730. public static GLib.File _settings_file;
  3731. public static GLib.File _user_file;
  3732. public static GLib.File _console_history_file;
  3733. public static GLib.File _window_state_file;
  3734. public static GLib.FileStream _log_stream;
  3735. public static ConsoleView _console_view;
  3736. public static bool _console_view_valid = false;
  3737. public static string _log_prefix;
  3738. public static SubprocessLauncher _subprocess_launcher;
  3739. public static void log(string system, string severity, string message)
  3740. {
  3741. GLib.DateTime now = new GLib.DateTime.now_local();
  3742. int now_us = now.get_microsecond();
  3743. string now_str = now.format("%H:%M:%S");
  3744. string plain_text_line = "%s.%06d %.4s %s: %s\n".printf(now_str
  3745. , now_us
  3746. , severity.ascii_up()
  3747. , system
  3748. , message
  3749. );
  3750. if (_log_stream != null) {
  3751. _log_stream.puts(plain_text_line);
  3752. _log_stream.flush();
  3753. }
  3754. if (_console_view_valid) {
  3755. string line = "%s: %s\n".printf(system, message);
  3756. string time = "%s.%06d ".printf(now_str, now_us);
  3757. _console_view.log(time, severity, line);
  3758. }
  3759. }
  3760. public static void logi(string message)
  3761. {
  3762. log(_log_prefix, "info", message);
  3763. }
  3764. public static void logw(string message)
  3765. {
  3766. log(_log_prefix, "warning", message);
  3767. }
  3768. public static void loge(string message)
  3769. {
  3770. log(_log_prefix, "error", message);
  3771. }
  3772. public void open_directory(string directory)
  3773. {
  3774. #if CROWN_PLATFORM_LINUX
  3775. try {
  3776. GLib.AppInfo.launch_default_for_uri("file://" + directory, null);
  3777. } catch (Error e) {
  3778. loge(e.message);
  3779. }
  3780. #else
  3781. GLib.SubprocessLauncher sl = new GLib.SubprocessLauncher(subprocess_flags());
  3782. try {
  3783. sl.spawnv({ "explorer.exe", directory, null });
  3784. } catch (Error e) {
  3785. loge(e.message);
  3786. }
  3787. #endif
  3788. }
  3789. public void open_text_editor(string path)
  3790. {
  3791. #if CROWN_PLATFORM_WINDOWS
  3792. GLib.SubprocessLauncher sl = new GLib.SubprocessLauncher(subprocess_flags());
  3793. try {
  3794. sl.spawnv({ "notepad.exe", path, null });
  3795. } catch (Error e) {
  3796. loge(e.message);
  3797. }
  3798. #endif
  3799. }
  3800. public static GLib.SubprocessFlags subprocess_flags()
  3801. {
  3802. GLib.SubprocessFlags flags = SubprocessFlags.NONE;
  3803. #if !CROWN_DEBUG
  3804. flags |= SubprocessFlags.STDOUT_SILENCE | SubprocessFlags.STDERR_SILENCE;
  3805. #endif
  3806. return flags;
  3807. }
  3808. public static bool is_directory_empty(string path)
  3809. {
  3810. GLib.File file = GLib.File.new_for_path(path);
  3811. try {
  3812. FileEnumerator enumerator = file.enumerate_children("standard::*"
  3813. , FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  3814. );
  3815. return enumerator.next_file() == null;
  3816. } catch (GLib.Error e) {
  3817. loge(e.message);
  3818. }
  3819. return false;
  3820. }
  3821. public void device_frame_delayed(uint delay_ms, RuntimeInstance runtime)
  3822. {
  3823. // FIXME: find a way to time exactly when it is effective to queue a redraw.
  3824. // See: https://blogs.gnome.org/jnelson/2010/10/13/those-realize-map-widget-signals/
  3825. GLib.Timeout.add_full(GLib.Priority.DEFAULT, delay_ms, () => {
  3826. runtime.send(DeviceApi.frame());
  3827. return GLib.Source.REMOVE;
  3828. });
  3829. }
  3830. public static int main(string[] args)
  3831. {
  3832. // If args does not contain --child, spawn the launcher.
  3833. int ii;
  3834. for (ii = 0; ii < args.length; ++ii) {
  3835. if (args[ii] == "--launcher") {
  3836. break;
  3837. }
  3838. }
  3839. if (ii == args.length) {
  3840. _log_prefix = "editor";
  3841. } else {
  3842. _log_prefix = "launcher";
  3843. // Remove --child from args for backward compatibility.
  3844. if (args.length > 1)
  3845. args = args[0 : args.length - 1];
  3846. }
  3847. // Redirect GLib logs to internal log*().
  3848. GLib.set_print_handler((msg) => { logi(msg); });
  3849. GLib.set_printerr_handler((msg) => { loge(msg); });
  3850. GLib.Log.set_writer_func((log_level, fields) => {
  3851. foreach (var field in fields) {
  3852. if (field.key == "MESSAGE") {
  3853. switch (log_level) {
  3854. case LEVEL_DEBUG:
  3855. #if CROWN_DEBUG
  3856. logi((string)field.value);
  3857. #endif
  3858. break;
  3859. case LEVEL_INFO:
  3860. case LEVEL_MESSAGE:
  3861. logi((string)field.value);
  3862. break;
  3863. case LEVEL_CRITICAL:
  3864. case LEVEL_WARNING:
  3865. logw((string)field.value);
  3866. break;
  3867. case LEVEL_ERROR:
  3868. loge((string)field.value);
  3869. break;
  3870. default:
  3871. logw((string)field.value);
  3872. break;
  3873. }
  3874. return GLib.LogWriterOutput.HANDLED;
  3875. }
  3876. }
  3877. return GLib.LogWriterOutput.UNHANDLED;
  3878. });
  3879. // Global paths
  3880. _data_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_data_dir(), "crown"));
  3881. try {
  3882. _data_dir.make_directory();
  3883. } catch (Error e) {
  3884. /* Nobody cares */
  3885. }
  3886. _config_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_config_dir(), "crown"));
  3887. try {
  3888. _config_dir.make_directory();
  3889. } catch (Error e) {
  3890. /* Nobody cares */
  3891. }
  3892. _cache_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_cache_dir(), "crown"));
  3893. try {
  3894. _cache_dir.make_directory();
  3895. } catch (Error e) {
  3896. /* Nobody cares */
  3897. }
  3898. _logs_dir = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "logs"));
  3899. try {
  3900. _logs_dir.make_directory();
  3901. } catch (Error e) {
  3902. /* Nobody cares */
  3903. }
  3904. _documents_dir = GLib.File.new_for_path(GLib.Environment.get_user_special_dir(GLib.UserDirectory.DOCUMENTS));
  3905. _thumbnails_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_cache_dir(), "thumbnails"));
  3906. try {
  3907. _thumbnails_dir.make_directory();
  3908. } catch (Error e) {
  3909. /* Nobody cares */
  3910. }
  3911. _thumbnails_normal_dir = GLib.File.new_for_path(GLib.Path.build_filename(_thumbnails_dir.get_path(), "normal"));
  3912. try {
  3913. _thumbnails_normal_dir.make_directory();
  3914. } catch (Error e) {
  3915. /* Nobody cares */
  3916. }
  3917. _log_file = GLib.File.new_for_path(GLib.Path.build_filename(_logs_dir.get_path(), new GLib.DateTime.now_local().format("%Y-%m-%d") + ".log"));
  3918. _log_stream = GLib.FileStream.open(_log_file.get_path(), "a");
  3919. if (_log_prefix == "launcher")
  3920. return launcher_main(args);
  3921. // Spawn launcher process.
  3922. try {
  3923. string[] child_args = args;
  3924. child_args += "--launcher";
  3925. #if CROWN_PLATFORM_WINDOWS
  3926. child_args += ((uint64)OpenProcess(0x00100000 /* SYNCHRONIZE */, true, GetCurrentProcessId())).to_string();
  3927. #elif CROWN_PLATFORM_LINUX
  3928. child_args += ((uint64)getpid()).to_string();
  3929. #endif
  3930. GLib.Pid launcher_pid;
  3931. GLib.Process.spawn_async(null
  3932. , child_args
  3933. , null
  3934. , 0
  3935. , null
  3936. , out launcher_pid
  3937. );
  3938. } catch (GLib.SpawnError e) {
  3939. loge("%s".printf(e.message));
  3940. return 1;
  3941. }
  3942. _settings_file = GLib.File.new_for_path(GLib.Path.build_filename(_config_dir.get_path(), "settings.sjson"));
  3943. _window_state_file = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "window.sjson"));
  3944. _user_file = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "user.sjson"));
  3945. _console_history_file = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "console_history.txt"));
  3946. // Find toolchain path, more desirable paths come first.
  3947. ii = 0;
  3948. string toolchain_paths[] =
  3949. {
  3950. "../../..", // Relative path in release package.
  3951. "../../../samples", // Relative path in git worktree.
  3952. ".",
  3953. };
  3954. for (ii = 0; ii < toolchain_paths.length; ++ii) {
  3955. string path = Path.build_filename(toolchain_paths[ii], "core");
  3956. if (GLib.FileUtils.test(path, FileTest.EXISTS) && GLib.FileUtils.test(path, FileTest.IS_DIR)) {
  3957. _toolchain_dir = File.new_for_path(path).get_parent();
  3958. break;
  3959. }
  3960. }
  3961. if (ii == toolchain_paths.length) {
  3962. loge("Unable to find the toolchain directory");
  3963. return 1;
  3964. }
  3965. // Find templates path, more desirable paths come first.
  3966. string templates_path[] =
  3967. {
  3968. "../../..", // Relative path in release package or git worktree.
  3969. ".",
  3970. };
  3971. for (ii = 0; ii < templates_path.length; ++ii) {
  3972. string path = Path.build_filename(templates_path[ii], "samples");
  3973. if (GLib.FileUtils.test(path, FileTest.EXISTS) && GLib.FileUtils.test(path, FileTest.IS_DIR)) {
  3974. _templates_dir = File.new_for_path(path);
  3975. break;
  3976. }
  3977. }
  3978. if (ii == templates_path.length) {
  3979. loge("Unable to find the templates directory");
  3980. return 1;
  3981. }
  3982. #if CROWN_PLATFORM_LINUX
  3983. Gdk.set_allowed_backends("x11");
  3984. #endif
  3985. // Use fontconfig backend.
  3986. Pango.FontMap fontmap = Pango.CairoFontMap.new_for_font_type(Cairo.FontType.FT);
  3987. Pango.CairoFontMap.set_default((Pango.CairoFontMap)fontmap);
  3988. LevelEditorApplication app = new LevelEditorApplication();
  3989. return app.run(args);
  3990. }
  3991. } /* namespace Crown */