level_editor.vala 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399
  1. /*
  2. * Copyright (c) 2012-2025 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. using Gdk; // Pixbuf
  6. using Gee;
  7. using Gtk;
  8. namespace Crown
  9. {
  10. const int WINDOW_DEFAULT_WIDTH = 1280;
  11. const int WINDOW_DEFAULT_HEIGHT = 720;
  12. const string CROWN_EDITOR_NAME = "Crown Editor";
  13. const string CROWN_EDITOR_MAIN_WINDOW_TITLE = CROWN_EDITOR_NAME + " " + CROWN_VERSION;
  14. const string CROWN_EDITOR_ICON_NAME = "crown-black-socket";
  15. public enum Theme
  16. {
  17. DARK,
  18. LIGHT,
  19. COUNT
  20. }
  21. public enum ToolType
  22. {
  23. PLACE,
  24. MOVE,
  25. ROTATE,
  26. SCALE,
  27. COUNT
  28. }
  29. public enum SnapMode
  30. {
  31. RELATIVE,
  32. ABSOLUTE
  33. }
  34. public enum ReferenceSystem
  35. {
  36. LOCAL,
  37. WORLD
  38. }
  39. public enum CameraViewType
  40. {
  41. PERSPECTIVE,
  42. FRONT,
  43. BACK,
  44. RIGHT,
  45. LEFT,
  46. TOP,
  47. BOTTOM,
  48. COUNT
  49. }
  50. public enum TargetConfig
  51. {
  52. RELEASE,
  53. DEVELOPMENT,
  54. COUNT;
  55. public string to_key()
  56. {
  57. switch (this) {
  58. case RELEASE:
  59. return "release";
  60. case DEVELOPMENT:
  61. return "development";
  62. default:
  63. return "unknown";
  64. }
  65. }
  66. public string to_label()
  67. {
  68. switch (this) {
  69. case RELEASE:
  70. return "Release";
  71. case DEVELOPMENT:
  72. return "Development";
  73. default:
  74. return "unknown";
  75. }
  76. }
  77. }
  78. public enum TargetPlatform
  79. {
  80. ANDROID,
  81. HTML5,
  82. LINUX,
  83. WINDOWS,
  84. COUNT;
  85. public string to_key()
  86. {
  87. switch (this) {
  88. case ANDROID:
  89. return "android";
  90. case HTML5:
  91. return "html5";
  92. case LINUX:
  93. return "linux";
  94. case WINDOWS:
  95. return "windows";
  96. default:
  97. return "unknown";
  98. }
  99. }
  100. public string to_label()
  101. {
  102. switch (this) {
  103. case ANDROID:
  104. return "Android";
  105. case HTML5:
  106. return "HTML5";
  107. case LINUX:
  108. return "Linux";
  109. case WINDOWS:
  110. return "Windows";
  111. default:
  112. return "Unknown";
  113. }
  114. }
  115. }
  116. public enum TargetArch
  117. {
  118. X86,
  119. X64,
  120. ARM,
  121. ARM64,
  122. WASM
  123. }
  124. public class RuntimeInstance
  125. {
  126. public SubprocessLauncher _subprocess_launcher;
  127. public string _name;
  128. public uint32 _process_id;
  129. public uint _revision;
  130. public GLib.SourceFunc _stop_callback;
  131. public GLib.SourceFunc _refresh_callback;
  132. public bool _refresh_success;
  133. public ConsoleClient _client;
  134. public signal void connected(RuntimeInstance ri, string address, int port);
  135. public signal void disconnected(RuntimeInstance ri);
  136. public signal void disconnected_unexpected(RuntimeInstance ri);
  137. public signal void message_received(RuntimeInstance ri, ConsoleClient client, uint8[] json);
  138. public RuntimeInstance(SubprocessLauncher sl, string name)
  139. {
  140. _subprocess_launcher = sl;
  141. _name = name;
  142. _process_id = uint32.MAX;
  143. _revision = 0;
  144. _stop_callback = null;
  145. _refresh_callback = null;
  146. _refresh_success = false;
  147. _client = new ConsoleClient();
  148. _client.connected.connect(on_client_connected);
  149. _client.message_received.connect(on_client_message_received);
  150. }
  151. private void on_client_connected(string address, int port)
  152. {
  153. connected(this, address, port);
  154. }
  155. private void on_client_disconnected()
  156. {
  157. disconnected(this);
  158. if (_stop_callback != null)
  159. _stop_callback();
  160. }
  161. private void on_client_disconnected_unexpected()
  162. {
  163. disconnected_unexpected(this);
  164. try {
  165. if (_process_id != uint32.MAX) {
  166. _subprocess_launcher.wait(_process_id);
  167. _process_id = uint32.MAX;
  168. }
  169. } catch (GLib.Error e) {
  170. loge(e.message);
  171. }
  172. }
  173. private void on_client_message_received(ConsoleClient client, uint8[] json)
  174. {
  175. message_received(this, client, json);
  176. }
  177. // Tries to connect to the @a client. Return the number of tries after
  178. // it succeeded or @a num_tries if failed.
  179. public async int connect_async(string address, int port, int num_tries, int interval)
  180. {
  181. // It is an error if the client disconnects after here.
  182. _client.disconnected.disconnect(on_client_disconnected);
  183. _client.disconnected.connect(on_client_disconnected_unexpected);
  184. // Try to connect to the client.
  185. int tries;
  186. for (tries = 0; tries < num_tries; ++tries) {
  187. _client.connect(address, port);
  188. if (_client.is_connected())
  189. break;
  190. GLib.Thread.usleep(interval*1000);
  191. }
  192. return tries;
  193. }
  194. public async void stop()
  195. {
  196. if (_client != null) {
  197. // Reset "disconnected" signal.
  198. _client.disconnected.disconnect(on_client_disconnected);
  199. _client.disconnected.disconnect(on_client_disconnected_unexpected);
  200. // Explicit call to this function should not produce error messages.
  201. _client.disconnected.connect(on_client_disconnected);
  202. if (_client.is_connected()) {
  203. _stop_callback = stop.callback;
  204. _client.send(RuntimeApi.quit());
  205. yield; // Wait for _client to disconnect.
  206. _stop_callback = null;
  207. }
  208. }
  209. try {
  210. if (_process_id != uint32.MAX)
  211. _subprocess_launcher.wait(_process_id);
  212. _process_id = uint32.MAX;
  213. } catch (GLib.Error e) {
  214. loge(e.message);
  215. }
  216. }
  217. public void send(string json)
  218. {
  219. _client.send(json);
  220. }
  221. public void send_script(string lua)
  222. {
  223. _client.send_script(lua);
  224. }
  225. public bool is_connected()
  226. {
  227. return _client.is_connected();
  228. }
  229. public async bool refresh(DataCompiler dc)
  230. {
  231. if (_refresh_callback != null)
  232. return false;
  233. if (!is_connected())
  234. return false;
  235. var compiler_revision = dc._revision;
  236. var refresh_list = yield dc.refresh_list(_revision);
  237. _client.send(DeviceApi.refresh(refresh_list));
  238. _client.send(DeviceApi.frame());
  239. _refresh_callback = refresh.callback;
  240. yield; // Wait for client to refresh the resources.
  241. if (_refresh_success)
  242. _revision = compiler_revision;
  243. return _refresh_success;
  244. }
  245. public void refresh_finished(bool success)
  246. {
  247. _refresh_success = success;
  248. if (_refresh_callback != null)
  249. _refresh_callback();
  250. _refresh_callback = null;
  251. }
  252. }
  253. public class LevelEditorWindow : Gtk.ApplicationWindow
  254. {
  255. private const GLib.ActionEntry[] action_entries =
  256. {
  257. { "fullscreen", on_fullscreen, null, null }
  258. };
  259. public bool _fullscreen;
  260. public LevelEditorWindow(Gtk.Application app)
  261. {
  262. Object(application: app);
  263. this.add_action_entries(action_entries, this);
  264. this.title = CROWN_EDITOR_MAIN_WINDOW_TITLE;
  265. this.key_press_event.connect(this.on_key_press);
  266. this.key_release_event.connect(this.on_key_release);
  267. this.window_state_event.connect(this.on_window_state_event);
  268. this.delete_event.connect(this.on_delete_event);
  269. this.focus_out_event.connect(this.on_focus_out);
  270. _fullscreen = false;
  271. this.set_default_size(WINDOW_DEFAULT_WIDTH, WINDOW_DEFAULT_HEIGHT);
  272. }
  273. private void on_fullscreen(GLib.SimpleAction action, GLib.Variant? param)
  274. {
  275. if (_fullscreen)
  276. unfullscreen();
  277. else
  278. fullscreen();
  279. }
  280. private bool on_key_press(Gdk.EventKey ev)
  281. {
  282. LevelEditorApplication app = (LevelEditorApplication)application;
  283. string str = "";
  284. if (ev.keyval == Gdk.Key.Control_L)
  285. str += LevelEditorApi.key_down("ctrl_left");
  286. else if (ev.keyval == Gdk.Key.Shift_L)
  287. str += LevelEditorApi.key_down("shift_left");
  288. else if (ev.keyval == Gdk.Key.Alt_L)
  289. str += LevelEditorApi.key_down("alt_left");
  290. if (str.length != 0) {
  291. app._editor.send_script(str);
  292. app._editor.send(DeviceApi.frame());
  293. }
  294. return Gdk.EVENT_PROPAGATE;
  295. }
  296. private bool on_key_release(Gdk.EventKey ev)
  297. {
  298. LevelEditorApplication app = (LevelEditorApplication)application;
  299. string str = "";
  300. if (ev.keyval == Gdk.Key.Control_L)
  301. str += LevelEditorApi.key_up("ctrl_left");
  302. else if (ev.keyval == Gdk.Key.Shift_L)
  303. str += LevelEditorApi.key_up("shift_left");
  304. else if (ev.keyval == Gdk.Key.Alt_L)
  305. str += LevelEditorApi.key_up("alt_left");
  306. if (str.length != 0) {
  307. app._editor.send_script(str);
  308. app._editor.send(DeviceApi.frame());
  309. }
  310. return Gdk.EVENT_PROPAGATE;
  311. }
  312. private bool on_window_state_event(Gdk.EventWindowState ev)
  313. {
  314. _fullscreen = (ev.new_window_state & Gdk.WindowState.FULLSCREEN) != 0;
  315. return Gdk.EVENT_PROPAGATE;
  316. }
  317. private bool on_delete_event()
  318. {
  319. LevelEditorApplication app = (LevelEditorApplication)application;
  320. if (app.should_quit())
  321. app.stop_backend_and_quit();
  322. return Gdk.EVENT_STOP; // Keep window alive.
  323. }
  324. private bool on_focus_out(Gdk.EventFocus ev)
  325. {
  326. LevelEditorApplication app = (LevelEditorApplication)application;
  327. app._editor.send_script(LevelEditorApi.key_up("ctrl_left"));
  328. app._editor.send_script(LevelEditorApi.key_up("shift_left"));
  329. app._editor.send_script(LevelEditorApi.key_up("alt_left"));
  330. return Gdk.EVENT_PROPAGATE;
  331. }
  332. public Hashtable encode()
  333. {
  334. Hashtable json_obj = new Hashtable();
  335. // This is the appropriate size to save, see:
  336. // https://valadoc.org/gtk+-3.0/Gtk.Window.set_default_size.html
  337. int width;
  338. int height;
  339. this.get_size(out width, out height);
  340. json_obj["width"] = width;
  341. json_obj["height"] = height;
  342. json_obj["maximized"] = this.is_maximized;
  343. json_obj["fullscreen"] = this._fullscreen;
  344. return json_obj;
  345. }
  346. public void decode(Hashtable json_obj)
  347. {
  348. if (json_obj.has_key("width"))
  349. this.default_width = (int)(double)json_obj["width"];
  350. else
  351. this.default_width = WINDOW_DEFAULT_WIDTH;
  352. if (json_obj.has_key("height"))
  353. this.default_height = (int)(double)json_obj["height"];
  354. else
  355. this.default_height = WINDOW_DEFAULT_HEIGHT;
  356. if (json_obj.has_key("maximized")) {
  357. if ((bool)json_obj["maximized"])
  358. this.maximize();
  359. else
  360. this.unmaximize();
  361. }
  362. if (json_obj.has_key("fullscreen")) {
  363. if ((bool)json_obj["fullscreen"])
  364. this.fullscreen();
  365. else
  366. this.unfullscreen();
  367. }
  368. }
  369. }
  370. public enum StartGame
  371. {
  372. NORMAL,
  373. TEST
  374. }
  375. public class LevelEditorApplication : Gtk.Application
  376. {
  377. // Constants
  378. private const GLib.ActionEntry[] action_entries_file =
  379. {
  380. // parameter type
  381. // name activate() | state
  382. // | | | |
  383. { "menu-file", null, null, null },
  384. { "new-level", on_new_level, null, null },
  385. { "open-level", on_open_level, "s", null },
  386. { "new-project", on_new_project, null, null },
  387. { "add-project", on_add_project, null, null },
  388. { "open-project", on_open_project, "s", null },
  389. { "save", on_save, null, null },
  390. { "save-as", on_save_as, null, null },
  391. { "import", on_import, "s", null },
  392. { "import-null", on_import, null, null },
  393. { "preferences", on_preferences, null, null },
  394. { "deploy", on_deploy, null, null },
  395. { "close-project", on_close_project, null, null },
  396. { "quit", on_quit, null, null },
  397. { "open-resource", on_open_resource, "s", null },
  398. { "copy-path", on_copy_path, "s", null },
  399. { "copy-name", on_copy_name, "s", null }
  400. };
  401. private const GLib.ActionEntry[] action_entries_edit =
  402. {
  403. { "menu-edit", null, null, null },
  404. { "undo", on_undo, null, null },
  405. { "redo", on_redo, null, null },
  406. { "duplicate", on_duplicate, null, null },
  407. { "delete", on_delete, null, null },
  408. { "tool", on_tool, "i", "1" }, // See: Crown.ToolType
  409. { "set-placeable", on_set_placeable, "(ss)", null },
  410. { "cancel-place", on_cancel_place, null, null },
  411. { "snap", on_snap, "i", "0" }, // See: Crown.SnapMode
  412. { "reference-system", on_reference_system, "i", "0" }, // See: Crown.ReferenceSystem
  413. { "snap-to-grid", on_snap_to_grid, null, "false" },
  414. { "menu-grid", null, null, null },
  415. { "grid-show", on_show_grid, null, "true" },
  416. { "grid-size", on_grid_size, "i", "10" }, // 10*meters.
  417. { "menu-rotation-snap", null, null, null },
  418. { "rotation-snap-size", on_rotation_snap_size, "i", "15" }
  419. };
  420. private const GLib.ActionEntry[] action_entries_create =
  421. {
  422. { "menu-create", null, null, null },
  423. { "menu-primitives", null, null, null },
  424. { "primitive-cube", on_spawn_primitive, null, null },
  425. { "primitive-sphere", on_spawn_primitive, null, null },
  426. { "primitive-cone", on_spawn_primitive, null, null },
  427. { "primitive-cylinder", on_spawn_primitive, null, null },
  428. { "primitive-plane", on_spawn_primitive, null, null },
  429. { "camera", on_spawn_primitive, null, null },
  430. { "light", on_spawn_primitive, null, null },
  431. { "sound-source", on_spawn_primitive, null, null },
  432. { "unit-empty", on_spawn_unit, null, null }
  433. };
  434. private const GLib.ActionEntry[] action_entries_camera =
  435. {
  436. { "menu-camera", null, null, null },
  437. { "camera-view", on_camera_view, "i", "0" }, // See: Crown.CameraViewType
  438. { "camera-frame-selected", on_camera_frame_selected, null, null },
  439. { "camera-frame-all", on_camera_frame_all, null, null }
  440. };
  441. private const GLib.ActionEntry[] action_entries_view =
  442. {
  443. { "menu-view", null, null, null },
  444. { "resource-chooser", on_resource_chooser, 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. private 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-lua", on_refresh_lua, null, null },
  459. { "restart-editor-view", on_restart_editor_view, null, null }
  460. };
  461. private const GLib.ActionEntry[] action_entries_help =
  462. {
  463. { "menu-help", null, null, null },
  464. { "manual", on_manual, null, null },
  465. { "report-issue", on_report_issue, null, null },
  466. { "browse-logs", on_browse_logs, null, null },
  467. { "changelog", on_changelog, null, null },
  468. { "donate", on_donate, null, null },
  469. { "about", on_about, null, null }
  470. };
  471. private const GLib.ActionEntry[] action_entries_project =
  472. {
  473. { "delete-file", on_delete_file, "s", null },
  474. { "delete-directory", on_delete_directory, "s", null },
  475. { "create-directory", on_create_directory, "(ss)", null },
  476. { "create-script", on_create_script, "(ssb)", null },
  477. { "create-unit", on_create_unit, "(ss)", null },
  478. { "open-containing", on_open_containing, "s", null },
  479. { "texture-settings", on_texture_settings, "s", null }
  480. };
  481. private const GLib.ActionEntry[] action_entries_package =
  482. {
  483. { "create-package-android", on_create_package_android, "(sississsssi)", null },
  484. { "create-package-html5", on_create_package_html5, "(sis)", null },
  485. { "create-package-linux", on_create_package_linux, "(sis)", null },
  486. { "create-package-windows", on_create_package_windows, "(sis)", null }
  487. };
  488. private const GLib.ActionEntry[] action_entries_unit =
  489. {
  490. { "unit-add-component", on_unit_add_component, "s", null },
  491. { "unit-remove-component", on_unit_remove_component, "s", null }
  492. };
  493. // Command line options
  494. private string? _source_dir = null;
  495. private string _level_resource = "";
  496. private User _user;
  497. private Hashtable _settings;
  498. private Hashtable _window_state;
  499. // Subprocess launcher service.
  500. private SubprocessLauncher _subprocess_launcher;
  501. // Editor state
  502. private double _grid_size;
  503. private double _rotation_snap;
  504. private bool _show_grid;
  505. private bool _snap_to_grid;
  506. private bool _debug_render_world;
  507. private bool _debug_physics_world;
  508. private ToolType _tool_type;
  509. private ToolType _tool_type_prev;
  510. private SnapMode _snap_mode;
  511. private ReferenceSystem _reference_system;
  512. // Project state
  513. private string _placeable_type;
  514. private string _placeable_name;
  515. // Accelerators
  516. private string[] _tool_place_accels;
  517. private string[] _tool_move_accels;
  518. private string[] _tool_rotate_accels;
  519. private string[] _tool_scale_accels;
  520. private string[] _delete_accels;
  521. private string[] _camera_view_perspective_accels;
  522. private string[] _camera_view_front_accels;
  523. private string[] _camera_view_back_accels;
  524. private string[] _camera_view_right_accels;
  525. private string[] _camera_view_left_accels;
  526. private string[] _camera_view_top_accels;
  527. private string[] _camera_view_bottom_accels;
  528. private string[] _camera_frame_selected_accels;
  529. private string[] _camera_frame_all_accels;
  530. // Engine connections
  531. private RuntimeInstance _compiler;
  532. public RuntimeInstance _editor;
  533. private RuntimeInstance _resource_preview;
  534. private RuntimeInstance _game;
  535. private RuntimeInstance _thumbnail;
  536. // Level data
  537. private UndoRedo _undo_redo;
  538. private Database _database;
  539. private Project _project;
  540. private ProjectStore _project_store;
  541. private Level _level;
  542. private DataCompiler _data_compiler;
  543. // Widgets
  544. private Gtk.CssProvider _css_provider;
  545. private ProjectBrowser _project_browser;
  546. private EditorView _editor_view;
  547. private EditorView _resource_preview_view;
  548. private LevelTreeView _level_treeview;
  549. private LevelLayersTreeView _level_layers_treeview;
  550. private PropertiesView _properties_view;
  551. private PreferencesDialog _preferences_dialog;
  552. private DeployDialog _deploy_dialog;
  553. private TextureSettingsDialog _texture_settings_dialog;
  554. private ResourceChooser _resource_chooser;
  555. private Gtk.Popover _resource_popover;
  556. private Gtk.Overlay _editor_view_overlay;
  557. private ThumbnailCache _thumbnail_cache;
  558. private Gtk.Stack _project_stack;
  559. private Gtk.Label _project_stack_compiling_data_label;
  560. private Gtk.Label _project_stack_connecting_to_data_compiler_label;
  561. private Gtk.Label _project_stack_compiler_crashed_label;
  562. private Gtk.Label _project_stack_compiler_failed_compilation_label;
  563. private Gtk.Label _project_stack_stopping_backend_label;
  564. private Gtk.Stack _editor_stack;
  565. private Gtk.Label _editor_stack_compiling_data_label;
  566. private Gtk.Label _editor_stack_connecting_to_data_compiler_label;
  567. private Gtk.Label _editor_stack_compiler_crashed_label;
  568. private Gtk.Label _editor_stack_compiler_failed_compilation_label;
  569. private Gtk.Label _editor_stack_disconnected_label;
  570. private Gtk.Label _editor_stack_oops_label;
  571. private Gtk.Label _editor_stack_stopping_backend_label;
  572. public Gtk.Stack _resource_preview_stack;
  573. public Gtk.Label _resource_preview_disconnected_label;
  574. public Gtk.Label _resource_preview_oops_label;
  575. public Gtk.Label _resource_preview_no_preview_label;
  576. private Gtk.Stack _inspector_stack;
  577. private Gtk.Label _inspector_stack_compiling_data_label;
  578. private Gtk.Label _inspector_stack_connecting_to_data_compiler_label;
  579. private Gtk.Label _inspector_stack_compiler_crashed_label;
  580. private Gtk.Label _inspector_stack_compiler_failed_compilation_label;
  581. private Gtk.Label _inspector_stack_stopping_backend_label;
  582. private Gtk.Toolbar _toolbar;
  583. private Gtk.ToolButton _toolbar_run;
  584. private Gtk.Notebook _level_tree_view_notebook;
  585. private Gtk.Notebook _console_notebook;
  586. private Gtk.Notebook _project_notebook;
  587. private Gtk.Notebook _inspector_notebook;
  588. private Gtk.Paned _editor_pane;
  589. private Gtk.Paned _content_pane;
  590. private Gtk.Paned _inspector_pane;
  591. private Gtk.Paned _main_pane;
  592. private Statusbar _statusbar;
  593. private Gtk.Box _main_vbox;
  594. private Gtk.FileFilter _file_filter;
  595. private Gtk.ComboBoxText _combo;
  596. private PanelNewProject _panel_new_project;
  597. private PanelProjectsList _panel_projects_list;
  598. private PanelWelcome _panel_welcome;
  599. private Gtk.Stack _main_stack;
  600. private uint _save_timer_id;
  601. public LevelEditorApplication(SubprocessLauncher subprocess_launcher)
  602. {
  603. Object(application_id: "org.crownengine.Crown"
  604. , flags: GLib.ApplicationFlags.FLAGS_NONE
  605. );
  606. _subprocess_launcher = subprocess_launcher;
  607. }
  608. public Theme theme_name_to_enum(string theme)
  609. {
  610. if (theme == "dark")
  611. return Theme.DARK;
  612. else if (theme == "light")
  613. return Theme.LIGHT;
  614. else
  615. return Theme.COUNT;
  616. }
  617. public void set_theme_from_name(string theme_name)
  618. {
  619. Theme theme = theme_name_to_enum(theme_name);
  620. set_theme(theme);
  621. }
  622. public void set_theme(Theme theme)
  623. {
  624. if (theme == Theme.COUNT)
  625. return;
  626. string css = "/org/crownengine/Crown/ui/style-%s.css".printf(theme == Theme.DARK ? "dark" : "light");
  627. _css_provider.load_from_resource(css);
  628. }
  629. protected override void startup()
  630. {
  631. base.startup();
  632. Intl.setlocale(LocaleCategory.ALL, "C");
  633. _css_provider = new Gtk.CssProvider();
  634. var default_screen = Gdk.Display.get_default().get_default_screen();
  635. Gtk.StyleContext.add_provider_for_screen(default_screen
  636. , _css_provider
  637. , STYLE_PROVIDER_PRIORITY_APPLICATION
  638. );
  639. try {
  640. _settings = SJSON.load_from_path(_settings_file.get_path());
  641. } catch (JsonSyntaxError e) {
  642. loge(e.message);
  643. }
  644. try {
  645. _window_state = SJSON.load_from_path(_window_state_file.get_path());
  646. } catch (JsonSyntaxError e) {
  647. loge(e.message);
  648. }
  649. // HACK: register CrownClamp type within GObject's type system to
  650. // make GtkBuilder able to find it when creating the widget from
  651. // .ui files.
  652. // https://stackoverflow.com/questions/24235937/custom-gtk-widget-with-template-ui
  653. new Clamp().get_type().ensure();
  654. this.add_action_entries(action_entries_file, this);
  655. this.add_action_entries(action_entries_edit, this);
  656. this.add_action_entries(action_entries_create, this);
  657. this.add_action_entries(action_entries_camera, this);
  658. this.add_action_entries(action_entries_view, this);
  659. this.add_action_entries(action_entries_debug, this);
  660. this.add_action_entries(action_entries_help, this);
  661. this.add_action_entries(action_entries_project, this);
  662. this.add_action_entries(action_entries_package, this);
  663. this.add_action_entries(action_entries_unit, this);
  664. _tool_place_accels = this.get_accels_for_action("app.tool(0)");
  665. _tool_move_accels = this.get_accels_for_action("app.tool(1)");
  666. _tool_rotate_accels = this.get_accels_for_action("app.tool(2)");
  667. _tool_scale_accels = this.get_accels_for_action("app.tool(3)");
  668. _delete_accels = this.get_accels_for_action("app.delete");
  669. _camera_view_perspective_accels = this.get_accels_for_action("app.camera-view(0)");
  670. _camera_view_front_accels = this.get_accels_for_action("app.camera-view(1)");
  671. _camera_view_back_accels = this.get_accels_for_action("app.camera-view(2)");
  672. _camera_view_right_accels = this.get_accels_for_action("app.camera-view(3)");
  673. _camera_view_left_accels = this.get_accels_for_action("app.camera-view(4)");
  674. _camera_view_top_accels = this.get_accels_for_action("app.camera-view(5)");
  675. _camera_view_bottom_accels = this.get_accels_for_action("app.camera-view(6)");
  676. _camera_frame_selected_accels = this.get_accels_for_action("app.camera-frame-selected");
  677. _camera_frame_all_accels = this.get_accels_for_action("app.camera-frame-all");
  678. _compiler = new RuntimeInstance(_subprocess_launcher, "data_compiler");
  679. _compiler.message_received.connect(on_message_received);
  680. _compiler.connected.connect(on_runtime_connected);
  681. _compiler.disconnected.connect(on_runtime_disconnected);
  682. _compiler.disconnected_unexpected.connect(on_data_compiler_disconnected_unexpected);
  683. _data_compiler = new DataCompiler(_compiler);
  684. _project = new Project();
  685. _project.set_toolchain_dir(_toolchain_dir.get_path());
  686. _project.register_importer("Sprite", { "png" }, SpriteResource.import, on_import_result, 0.0);
  687. _project.register_importer("Mesh", { "mesh", "fbx" }, MeshResource.import, on_import_result, 1.0);
  688. _project.register_importer("Sound", { "wav" }, SoundResource.import, on_import_result, 2.0);
  689. _project.register_importer("Texture", { "png", "tga", "dds", "ktx", "pvr" }, TextureResource.import, on_import_result, 2.0);
  690. _project.register_importer("Font", { "ttf", "otf" }, FontResource.import, on_import_result, 3.0);
  691. _project.project_reset.connect(on_project_reset);
  692. _project.project_loaded.connect(on_project_loaded);
  693. _editor = new RuntimeInstance(_subprocess_launcher, "editor");
  694. _editor.message_received.connect(on_message_received);
  695. _editor.connected.connect(on_editor_connected);
  696. _editor.disconnected.connect(on_runtime_disconnected);
  697. _editor.disconnected_unexpected.connect(on_editor_disconnected_unexpected);
  698. _preferences_dialog = new PreferencesDialog(_editor);
  699. _preferences_dialog.delete_event.connect(_preferences_dialog.hide_on_delete);
  700. _preferences_dialog.decode(_settings);
  701. set_theme_from_name(_preferences_dialog._theme_combo.value);
  702. _resource_preview = new RuntimeInstance(_subprocess_launcher, "resource_preview");
  703. _resource_preview.message_received.connect(on_message_received);
  704. _resource_preview.connected.connect(on_runtime_connected);
  705. _resource_preview.disconnected.connect(on_runtime_disconnected);
  706. _resource_preview.disconnected_unexpected.connect(on_resource_preview_disconnected_unexpected);
  707. _game = new RuntimeInstance(_subprocess_launcher, "game");
  708. _game.message_received.connect(on_message_received);
  709. _game.connected.connect(on_game_connected);
  710. _game.disconnected.connect(on_game_disconnected);
  711. _game.disconnected_unexpected.connect(on_game_disconnected);
  712. _thumbnail = new RuntimeInstance(_subprocess_launcher, "thumbnail");
  713. _thumbnail.message_received.connect(on_message_received);
  714. _thumbnail.connected.connect(on_runtime_connected);
  715. _thumbnail.disconnected.connect(on_runtime_disconnected);
  716. _thumbnail.disconnected_unexpected.connect(on_runtime_disconnected_unexpected);
  717. _undo_redo = new UndoRedo((uint)_preferences_dialog._undo_redo_max_size.value * 1024 * 1024);
  718. _database = new Database(_project, _undo_redo);
  719. _database.key_changed.connect(() => { update_active_window_title(); });
  720. _database.restore_point_added.connect(on_restore_point_added);
  721. _database.undo_redo.connect(on_undo_redo);
  722. _level = new Level(_database, _editor, _project);
  723. // Editor state
  724. _grid_size = 1.0;
  725. _rotation_snap = 15.0;
  726. _show_grid = true;
  727. _snap_to_grid = false;
  728. _debug_render_world = false;
  729. _debug_physics_world = false;
  730. _tool_type = ToolType.MOVE;
  731. _tool_type_prev = _tool_type;
  732. _snap_mode = SnapMode.RELATIVE;
  733. _reference_system = ReferenceSystem.LOCAL;
  734. // Project state
  735. _placeable_type = "";
  736. _placeable_name = "";
  737. _project_store = new ProjectStore(_project);
  738. // Register component types.
  739. Unit.register_component_type(OBJECT_TYPE_TRANSFORM, "");
  740. Unit.register_component_type(OBJECT_TYPE_LIGHT, OBJECT_TYPE_TRANSFORM);
  741. Unit.register_component_type(OBJECT_TYPE_CAMERA, OBJECT_TYPE_TRANSFORM);
  742. Unit.register_component_type(OBJECT_TYPE_MESH_RENDERER, OBJECT_TYPE_TRANSFORM);
  743. Unit.register_component_type(OBJECT_TYPE_SPRITE_RENDERER, OBJECT_TYPE_TRANSFORM);
  744. Unit.register_component_type(OBJECT_TYPE_COLLIDER, OBJECT_TYPE_TRANSFORM);
  745. Unit.register_component_type(OBJECT_TYPE_ACTOR, OBJECT_TYPE_TRANSFORM);
  746. Unit.register_component_type(OBJECT_TYPE_SCRIPT, "");
  747. Unit.register_component_type(OBJECT_TYPE_ANIMATION_STATE_MACHINE, "");
  748. // Widgets
  749. _combo = new Gtk.ComboBoxText();
  750. _combo.append("editor", "Editor");
  751. _combo.append("game", "Game");
  752. _combo.set_active_id("editor");
  753. _console_view = new ConsoleView(_project, _combo, _preferences_dialog);
  754. _thumbnail_cache = new ThumbnailCache(_project, _thumbnail, (uint)_preferences_dialog._thumbnail_cache_max_size.value * 1024 * 1024);
  755. _project_browser = new ProjectBrowser(_project_store, _thumbnail_cache);
  756. _level_treeview = new LevelTreeView(_database, _level);
  757. _level_layers_treeview = new LevelLayersTreeView(_database, _level);
  758. _properties_view = new PropertiesView(_database, _project_store);
  759. _level.selection_changed.connect(_properties_view.on_selection_changed);
  760. _project_stack = new Gtk.Stack();
  761. _project_stack.add(_project_browser);
  762. _project_stack_compiling_data_label = compiling_data_label();
  763. _project_stack.add(_project_stack_compiling_data_label);
  764. _project_stack_connecting_to_data_compiler_label = connecting_to_data_compiler_label();
  765. _project_stack.add(_project_stack_connecting_to_data_compiler_label);
  766. _project_stack_compiler_crashed_label = compiler_crashed_label();
  767. _project_stack.add(_project_stack_compiler_crashed_label);
  768. _project_stack_compiler_failed_compilation_label = compiler_failed_compilation_label();
  769. _project_stack.add(_project_stack_compiler_failed_compilation_label);
  770. _project_stack_stopping_backend_label = stopping_backend_label();
  771. _project_stack.add(_project_stack_stopping_backend_label);
  772. _editor_stack = new Gtk.Stack();
  773. _editor_stack_compiling_data_label = compiling_data_label();
  774. _editor_stack.add(_editor_stack_compiling_data_label);
  775. _editor_stack_connecting_to_data_compiler_label = connecting_to_data_compiler_label();
  776. _editor_stack.add(_editor_stack_connecting_to_data_compiler_label);
  777. _editor_stack_compiler_crashed_label = compiler_crashed_label();
  778. _editor_stack.add(_editor_stack_compiler_crashed_label);
  779. _editor_stack_compiler_failed_compilation_label = compiler_failed_compilation_label();
  780. _editor_stack.add(_editor_stack_compiler_failed_compilation_label);
  781. _editor_stack_disconnected_label = new Gtk.Label("Disconnected.");
  782. _editor_stack.add(_editor_stack_disconnected_label);
  783. _editor_stack_oops_label = new Gtk.Label(null);
  784. _editor_stack_oops_label.track_visited_links = false;
  785. _editor_stack_oops_label.set_markup("Something went wrong.\rTry to <a href=\"restart\">restart this view</a>.");
  786. _editor_stack_oops_label.activate_link.connect(() => {
  787. activate_action("restart-editor-view", null);
  788. return true;
  789. });
  790. _editor_stack.add(_editor_stack_oops_label);
  791. _editor_stack_stopping_backend_label = stopping_backend_label();
  792. _editor_stack.add(_editor_stack_stopping_backend_label);
  793. _resource_preview_stack = new Gtk.Stack();
  794. _resource_preview_no_preview_label = new Gtk.Label("No Preview");
  795. _resource_preview_no_preview_label.set_size_request(300, 300);
  796. _resource_preview_stack.add(_resource_preview_no_preview_label);
  797. _resource_preview_disconnected_label = new Gtk.Label("Disconnected");
  798. _resource_preview_stack.add(_resource_preview_disconnected_label);
  799. _resource_preview_oops_label = new Gtk.Label(null);
  800. _resource_preview_oops_label.track_visited_links = false;
  801. _resource_preview_oops_label.set_markup("Something went wrong.\rTry to <a href=\"restart\">restart this view</a>.");
  802. _resource_preview_oops_label.activate_link.connect(() => {
  803. restart_resource_preview.begin((obj, res) => {
  804. restart_resource_preview.end(res);
  805. });
  806. return true;
  807. });
  808. _resource_preview_stack.add(_resource_preview_oops_label);
  809. _inspector_stack = new Gtk.Stack();
  810. _inspector_stack_compiling_data_label = compiling_data_label();
  811. _inspector_stack.add(_inspector_stack_compiling_data_label);
  812. _inspector_stack_connecting_to_data_compiler_label = connecting_to_data_compiler_label();
  813. _inspector_stack.add(_inspector_stack_connecting_to_data_compiler_label);
  814. _inspector_stack_compiler_crashed_label = compiler_crashed_label();
  815. _inspector_stack.add(_inspector_stack_compiler_crashed_label);
  816. _inspector_stack_compiler_failed_compilation_label = compiler_failed_compilation_label();
  817. _inspector_stack.add(_inspector_stack_compiler_failed_compilation_label);
  818. _inspector_stack_stopping_backend_label = stopping_backend_label();
  819. _inspector_stack.add(_inspector_stack_stopping_backend_label);
  820. Gtk.Builder builder = new Gtk.Builder.from_resource("/org/crownengine/Crown/ui/toolbar.ui");
  821. _toolbar = builder.get_object("toolbar") as Gtk.Toolbar;
  822. _toolbar_run = builder.get_object("run") as Gtk.ToolButton;
  823. _editor_view_overlay = new Gtk.Overlay();
  824. _editor_view_overlay.add_overlay(_toolbar);
  825. _resource_popover = new Gtk.Popover(_toolbar);
  826. _resource_popover.key_press_event.connect((ev) => {
  827. if (ev.keyval == Gdk.Key.Escape) {
  828. // Do not transition-animate (i.e. call hide() instead of popdown()).
  829. _resource_popover.hide();
  830. return Gdk.EVENT_STOP;
  831. }
  832. return Gdk.EVENT_PROPAGATE;
  833. });
  834. _resource_popover.button_press_event.connect((ev) => {
  835. // Do not transition-animate (i.e. call hide() instead of popdown()).
  836. // See: https://gitlab.gnome.org/GNOME/gtk/-/blob/3.22.30/gtk/gtkpopover.c
  837. Gtk.Widget child = _resource_popover.get_child();
  838. Gtk.Widget event_widget = Gtk.get_event_widget(ev);
  839. if (child != null && ev.window == event_widget.get_window()) {
  840. Gtk.Allocation child_alloc;
  841. child.get_allocation(out child_alloc);
  842. if ((int)ev.x < child_alloc.x
  843. || (int)ev.x > child_alloc.x + child_alloc.width
  844. || (int)ev.y < child_alloc.y
  845. || (int)ev.y > child_alloc.y + child_alloc.height
  846. ) {
  847. _resource_popover.hide();
  848. }
  849. } else if (!event_widget.is_ancestor(_resource_popover)) {
  850. _resource_popover.hide();
  851. }
  852. return Gdk.EVENT_PROPAGATE;
  853. });
  854. _resource_popover.events |= Gdk.EventMask.STRUCTURE_MASK; // unmap_event
  855. _resource_popover.unmap_event.connect(() => {
  856. // Redraw the editor view when the popover is not on-screen anymore.
  857. device_frame_delayed(16, _editor);
  858. return Gdk.EVENT_PROPAGATE;
  859. });
  860. _resource_popover.delete_event.connect(_resource_popover.hide_on_delete);
  861. _resource_popover.modal = true;
  862. _resource_chooser = new ResourceChooser(_project, _project_store, _resource_preview_stack, _resource_preview);
  863. _resource_chooser.resource_selected.connect(on_resource_browser_resource_selected);
  864. _resource_chooser.destroy.connect(() => {
  865. stop_resource_preview.begin((obj, res) => {
  866. stop_resource_preview.end(res);
  867. });
  868. });
  869. _resource_popover.add(_resource_chooser);
  870. _level_tree_view_notebook = new Notebook();
  871. _level_tree_view_notebook.show_border = false;
  872. _level_tree_view_notebook.append_page(_level_treeview, new Gtk.Image.from_icon_name("level-tree", IconSize.SMALL_TOOLBAR));
  873. _level_tree_view_notebook.append_page(_level_layers_treeview, new Gtk.Image.from_icon_name("level-layers", IconSize.SMALL_TOOLBAR));
  874. _console_notebook = new Notebook();
  875. _console_notebook.show_border = false;
  876. _console_notebook.append_page(_console_view, new Gtk.Label.with_mnemonic("Console"));
  877. _project_notebook = new Notebook();
  878. _project_notebook.show_border = false;
  879. _project_notebook.append_page(_project_stack, new Gtk.Label.with_mnemonic("Project"));
  880. _inspector_notebook = new Notebook();
  881. _inspector_notebook.show_border = false;
  882. _inspector_notebook.append_page(_properties_view, new Gtk.Label.with_mnemonic("Properties"));
  883. _editor_pane = new Gtk.Paned(Gtk.Orientation.HORIZONTAL);
  884. _editor_pane.pack1(_project_notebook, false, false);
  885. _editor_pane.pack2(_editor_stack, true, false);
  886. _content_pane = new Gtk.Paned(Gtk.Orientation.VERTICAL);
  887. _content_pane.pack1(_editor_pane, true, false);
  888. _content_pane.pack2(_console_notebook, false, false);
  889. _inspector_pane = new Gtk.Paned(Gtk.Orientation.VERTICAL);
  890. _inspector_pane.pack1(_level_tree_view_notebook, true, false);
  891. _inspector_pane.pack2(_inspector_notebook, false, false);
  892. _inspector_stack.add(_inspector_pane);
  893. _main_pane = new Gtk.Paned(Gtk.Orientation.HORIZONTAL);
  894. _main_pane.pack1(_content_pane, true, false);
  895. _main_pane.pack2(_inspector_stack, false, false);
  896. _statusbar = new Statusbar();
  897. _main_vbox = new Gtk.Box(Gtk.Orientation.VERTICAL, 0);
  898. _main_vbox.pack_start(_main_pane, true, true, 0);
  899. _main_vbox.pack_start(_statusbar, false, false, 0);
  900. _main_vbox.set_visible(true);
  901. _file_filter = new Gtk.FileFilter();
  902. _file_filter.set_filter_name("Level (*.level)");
  903. _file_filter.add_pattern("*.level");
  904. _user = new User();
  905. _panel_new_project = new PanelNewProject(_user, _project);
  906. _panel_new_project.fill_templates_list(_templates_dir.get_path());
  907. _panel_welcome = new PanelWelcome();
  908. _panel_projects_list = new PanelProjectsList(_user);
  909. _panel_welcome.pack_start(_panel_projects_list);
  910. _panel_welcome.set_visible(true); // To make Gtk.Stack work...
  911. _main_stack = new Gtk.Stack();
  912. _main_stack.add_named(_panel_welcome, "panel_welcome");
  913. _main_stack.add_named(_panel_new_project, "panel_new_project");
  914. _main_stack.add_named(_main_vbox, "main_vbox");
  915. // Delete expired logs
  916. if (_preferences_dialog._log_delete_after_days.value != 0) {
  917. try {
  918. FileEnumerator enumerator = _logs_dir.enumerate_children("standard::*"
  919. , FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  920. );
  921. GLib.FileInfo info = null;
  922. while ((info = enumerator.next_file()) != null) {
  923. if (info.get_file_type() != GLib.FileType.REGULAR)
  924. continue; // Skip anything but regular files
  925. // Parse DateTime from log filename
  926. int year = 1970;
  927. int month = 1;
  928. int day = 1;
  929. if (info.get_name().scanf("%d-%d-%d.log", &year, &month, &day) != 3)
  930. continue; // Skip malformed filenames
  931. GLib.DateTime time_log = new GLib.DateTime.local(year, month, day, 0, 0, 0.0);
  932. if (time_log == null)
  933. continue; // Skip invalid dates
  934. GLib.DateTime time_now = new GLib.DateTime.now_local();
  935. if (time_now.difference(time_log) <= GLib.TimeSpan.DAY*_preferences_dialog._log_delete_after_days.value)
  936. continue; // Skip if date is within range
  937. // Delete
  938. GLib.File log_file = _logs_dir.resolve_relative_path(info.get_name());
  939. log_file.delete();
  940. }
  941. } catch (GLib.Error e) {
  942. loge(e.message);
  943. }
  944. }
  945. _user.load(_user_file.get_path());
  946. _console_view._entry_history.load(_console_history_file.get_path());
  947. if (_source_dir == null) {
  948. show_panel("panel_welcome");
  949. } else {
  950. show_panel("main_vbox");
  951. restart_backend.begin(_source_dir, _level_resource);
  952. }
  953. }
  954. protected override void activate()
  955. {
  956. if (this.active_window == null) {
  957. LevelEditorWindow win = new LevelEditorWindow(this);
  958. if (_window_state.has_key("level_editor_window"))
  959. win.decode((Hashtable)_window_state["level_editor_window"]);
  960. win.add(_main_stack);
  961. try {
  962. win.icon = IconTheme.get_default().load_icon(CROWN_EDITOR_ICON_NAME, 256, 0);
  963. } catch (Error e) {
  964. loge(e.message);
  965. }
  966. }
  967. this.active_window.show_all();
  968. }
  969. protected override bool local_command_line(ref unowned string[] args, out int exit_status)
  970. {
  971. if (args.length > 1) {
  972. if (!GLib.FileUtils.test(args[1], FileTest.EXISTS) || !GLib.FileUtils.test(args[1], FileTest.IS_DIR)) {
  973. loge("Source directory does not exist or it is not a directory");
  974. exit_status = 1;
  975. return true;
  976. }
  977. _source_dir = args[1];
  978. }
  979. if (args.length > 2) {
  980. // Validation is done below after the Project object instantiation
  981. _level_resource = args[2];
  982. }
  983. exit_status = 0;
  984. return false;
  985. }
  986. protected override int command_line(ApplicationCommandLine command_line)
  987. {
  988. this.activate();
  989. return 0;
  990. }
  991. public RuntimeInstance? current_selected_runtime()
  992. {
  993. if (_combo.get_active_id() == "editor")
  994. return _editor;
  995. else if (_combo.get_active_id() == "game")
  996. return _game;
  997. else
  998. return null;
  999. }
  1000. private void on_resource_browser_resource_selected(string type, string name)
  1001. {
  1002. activate_action("set-placeable", new GLib.Variant.tuple({ type, name }));
  1003. }
  1004. private void on_runtime_connected(RuntimeInstance ri, string address, int port)
  1005. {
  1006. logi("Connected to %s@%s:%d".printf(ri._name, address, port));
  1007. }
  1008. private void on_runtime_disconnected(RuntimeInstance ri)
  1009. {
  1010. logi("Disconnected from %s".printf(ri._name));
  1011. }
  1012. private void on_runtime_disconnected_unexpected(RuntimeInstance ri)
  1013. {
  1014. logw("Disconnected from %s unexpectedly".printf(ri._name));
  1015. }
  1016. private async void on_data_compiler_disconnected_unexpected(RuntimeInstance ri)
  1017. {
  1018. on_runtime_disconnected_unexpected(ri);
  1019. yield stop_heads();
  1020. // Reset the callback
  1021. _data_compiler.compile_finished(false, 0);
  1022. _project_stack.set_visible_child(_project_stack_compiler_crashed_label);
  1023. _editor_stack.set_visible_child(_editor_stack_compiler_crashed_label);
  1024. _inspector_stack.set_visible_child(_inspector_stack_compiler_crashed_label);
  1025. }
  1026. private void on_editor_connected(RuntimeInstance ri, string address, int port)
  1027. {
  1028. on_runtime_connected(ri, address, port);
  1029. // Update editor view with current editor state.
  1030. _level.send_level();
  1031. send_state();
  1032. _preferences_dialog.apply();
  1033. _editor.send(DeviceApi.frame());
  1034. }
  1035. private void on_editor_disconnected_unexpected(RuntimeInstance ri)
  1036. {
  1037. on_runtime_disconnected_unexpected(ri);
  1038. _editor_stack.set_visible_child(_editor_stack_oops_label);
  1039. }
  1040. private void on_resource_preview_disconnected_unexpected(RuntimeInstance ri)
  1041. {
  1042. on_runtime_disconnected_unexpected(ri);
  1043. _resource_preview_stack.set_visible_child(_resource_preview_oops_label);
  1044. }
  1045. private void on_game_connected(RuntimeInstance ri, string address, int port)
  1046. {
  1047. on_runtime_connected(ri, address, port);
  1048. _combo.set_active_id("game");
  1049. }
  1050. private void on_game_disconnected(RuntimeInstance ri)
  1051. {
  1052. on_runtime_disconnected(ri);
  1053. _combo.set_active_id("editor");
  1054. _toolbar_run.icon_name = "game-run";
  1055. }
  1056. private void on_message_received(RuntimeInstance ri, ConsoleClient client, uint8[] json)
  1057. {
  1058. try {
  1059. Hashtable msg = JSON.decode(json) as Hashtable;
  1060. handle_message(ri, client, (string)msg["type"], msg);
  1061. } catch (JsonSyntaxError e) {
  1062. loge(e.message);
  1063. }
  1064. }
  1065. private void handle_message(RuntimeInstance ri, ConsoleClient client, string msg_type, Hashtable msg)
  1066. {
  1067. if (msg_type == "message") {
  1068. string system = ri._name + ": " + (string)msg["system"];
  1069. log(system, (string)msg["severity"], (string)msg["message"]);
  1070. } else if (msg_type == "add_file") {
  1071. string path = (string)msg["path"];
  1072. uint64 size = uint64.parse((string)msg["size"]);
  1073. uint64 mtime = uint64.parse((string)msg["mtime"]);
  1074. _project.add_file(path, size, mtime);
  1075. } else if (msg_type == "remove_file") {
  1076. string path = (string)msg["path"];
  1077. _project.remove_file(path);
  1078. } else if (msg_type == "add_tree") {
  1079. string path = (string)msg["path"];
  1080. _project.add_tree(path);
  1081. } else if (msg_type == "remove_tree") {
  1082. string path = (string)msg["path"];
  1083. _project.remove_tree(path);
  1084. } else if (msg_type == "change_file") {
  1085. string path = (string)msg["path"];
  1086. uint64 size = uint64.parse((string)msg["size"]);
  1087. uint64 mtime = uint64.parse((string)msg["mtime"]);
  1088. _project.change_file(path, size, mtime);
  1089. } else if (msg_type == "compile") {
  1090. // Guid id = Guid.parse((string)msg["id"]);
  1091. if (msg.has_key("start")) {
  1092. // FIXME
  1093. } else if (msg.has_key("success")) {
  1094. _data_compiler.compile_finished((bool)msg["success"], (uint)(double)msg["revision"]);
  1095. refresh_all_clients.begin((obj, res) => {
  1096. refresh_all_clients.end(res);
  1097. _project.data_compiled();
  1098. _project_browser.queue_draw();
  1099. });
  1100. }
  1101. } else if (msg_type == "refresh") {
  1102. ri.refresh_finished((bool)msg["success"]);
  1103. } else if (msg_type == "refresh_list") {
  1104. _data_compiler.refresh_list_finished((ArrayList<Value?>)msg["list"]);
  1105. } else if (msg_type == "unit_spawned") {
  1106. Guid id = Guid.parse((string)msg["id"]);
  1107. string name = (string)msg["name"];
  1108. ArrayList<Value?> pos = (ArrayList<Value?>)msg["position"];
  1109. ArrayList<Value?> rot = (ArrayList<Value?>)msg["rotation"];
  1110. ArrayList<Value?> scl = (ArrayList<Value?>)msg["scale"];
  1111. _level.on_unit_spawned(id
  1112. , name
  1113. , Vector3.from_array(pos)
  1114. , Quaternion.from_array(rot)
  1115. , Vector3.from_array(scl)
  1116. );
  1117. _database.add_restore_point((int)ActionType.SPAWN_UNIT, new Guid?[] { id }, ActionTypeFlags.FROM_SERVER);
  1118. } else if (msg_type == "sound_spawned") {
  1119. Guid id = Guid.parse((string)msg["id"]);
  1120. string name = (string)msg["name"];
  1121. ArrayList<Value?> pos = (ArrayList<Value?>)msg["position"];
  1122. ArrayList<Value?> rot = (ArrayList<Value?>)msg["rotation"];
  1123. ArrayList<Value?> scl = (ArrayList<Value?>)msg["scale"];
  1124. double range = (double)msg["range"];
  1125. double volume = (double)msg["volume"];
  1126. bool loop = (bool)msg["loop"];
  1127. _level.on_sound_spawned(id
  1128. , name
  1129. , Vector3.from_array(pos)
  1130. , Quaternion.from_array(rot)
  1131. , Vector3.from_array(scl)
  1132. , range
  1133. , volume
  1134. , loop
  1135. );
  1136. _database.add_restore_point((int)ActionType.SPAWN_SOUND, new Guid?[] { id }, ActionTypeFlags.FROM_SERVER);
  1137. } else if (msg_type == "move_objects") {
  1138. Hashtable ids = (Hashtable)msg["ids"];
  1139. Hashtable new_positions = (Hashtable)msg["new_positions"];
  1140. Hashtable new_rotations = (Hashtable)msg["new_rotations"];
  1141. Hashtable new_scales = (Hashtable)msg["new_scales"];
  1142. ArrayList<string> keys = new ArrayList<string>.wrap(ids.keys.to_array());
  1143. keys.sort(Gee.Functions.get_compare_func_for(typeof(string)));
  1144. Guid?[] n_ids = new Guid?[keys.size];
  1145. Vector3[] n_positions = new Vector3[keys.size];
  1146. Quaternion[] n_rotations = new Quaternion[keys.size];
  1147. Vector3[] n_scales = new Vector3[keys.size];
  1148. for (int i = 0; i < keys.size; ++i) {
  1149. string k = keys[i];
  1150. n_ids[i] = Guid.parse((string)ids[k]);
  1151. n_positions[i] = Vector3.from_array((ArrayList<Value?>)(new_positions[k]));
  1152. n_rotations[i] = Quaternion.from_array((ArrayList<Value?>)new_rotations[k]);
  1153. n_scales[i] = Vector3.from_array((ArrayList<Value?>)new_scales[k]);
  1154. }
  1155. _level.on_move_objects(n_ids, n_positions, n_rotations, n_scales);
  1156. _database.add_restore_point((int)ActionType.MOVE_OBJECTS, n_ids, ActionTypeFlags.FROM_SERVER);
  1157. } else if (msg_type == "selection") {
  1158. Hashtable objects = (Hashtable)msg["objects"];
  1159. ArrayList<string> keys = new ArrayList<string>.wrap(objects.keys.to_array());
  1160. keys.sort(Gee.Functions.get_compare_func_for(typeof(string)));
  1161. Guid[] ids = new Guid[keys.size];
  1162. for (int i = 0; i < keys.size; ++i) {
  1163. string k = keys[i];
  1164. ids[i] = Guid.parse((string)objects[k]);
  1165. }
  1166. _level.on_selection(ids);
  1167. } else if (msg_type == "camera") {
  1168. _level.on_camera(msg);
  1169. } else if (msg_type == "error") {
  1170. loge((string)msg["message"]);
  1171. } else if (msg_type == "thumbnail") {
  1172. string resource_type = (string)msg["resource_type"];
  1173. string resource_name = (string)msg["resource_name"];
  1174. string path = (string)msg["path"];
  1175. _thumbnail_cache.thumbnail_ready(resource_type, resource_name, path);
  1176. } else {
  1177. loge("Unknown message type: " + msg_type);
  1178. }
  1179. }
  1180. private void append_editor_state(StringBuilder sb)
  1181. {
  1182. // This state is common to any project.
  1183. sb.append(LevelEditorApi.set_grid_size(_grid_size));
  1184. sb.append(LevelEditorApi.set_rotation_snap(_rotation_snap));
  1185. sb.append(LevelEditorApi.enable_show_grid(_show_grid));
  1186. sb.append(LevelEditorApi.enable_snap_to_grid(_snap_to_grid));
  1187. sb.append(LevelEditorApi.enable_debug_render_world(_debug_render_world));
  1188. sb.append(LevelEditorApi.enable_debug_physics_world(_debug_physics_world));
  1189. sb.append(LevelEditorApi.set_tool_type(_tool_type));
  1190. sb.append(LevelEditorApi.set_snap_mode(_snap_mode));
  1191. sb.append(LevelEditorApi.set_reference_system(_reference_system));
  1192. }
  1193. private void append_project_state(StringBuilder sb)
  1194. {
  1195. // This state is not guaranteed to be applicable to any project.
  1196. if (_placeable_type != "")
  1197. sb.append(LevelEditorApi.set_placeable(_placeable_type, _placeable_name));
  1198. }
  1199. private void send_state()
  1200. {
  1201. StringBuilder sb = new StringBuilder();
  1202. append_editor_state(sb);
  1203. append_project_state(sb);
  1204. _editor.send_script(sb.str);
  1205. }
  1206. private void on_objects_created(Guid?[] object_ids)
  1207. {
  1208. StringBuilder sb = new StringBuilder();
  1209. _level.generate_spawn_objects(sb, object_ids);
  1210. _editor.send_script(sb.str);
  1211. _editor.send(DeviceApi.frame());
  1212. _level.selection_changed(_level._selection);
  1213. }
  1214. private void on_objects_destroyed(Guid?[] object_ids)
  1215. {
  1216. StringBuilder sb = new StringBuilder();
  1217. _level.generate_destroy_objects(sb, object_ids);
  1218. _editor.send_script(sb.str);
  1219. _editor.send(DeviceApi.frame());
  1220. _level.selection_changed(_level._selection);
  1221. }
  1222. private void on_objects_changed(Guid?[] object_ids)
  1223. {
  1224. StringBuilder sb = new StringBuilder();
  1225. _level.generate_change_objects(sb, object_ids);
  1226. _editor.send_script(sb.str);
  1227. _editor.send(DeviceApi.frame());
  1228. }
  1229. private void on_restore_point_added(int id, Guid?[] data, uint32 flags)
  1230. {
  1231. switch (id) {
  1232. case ActionType.SPAWN_UNIT:
  1233. case ActionType.SPAWN_SOUND:
  1234. case ActionType.DUPLICATE_OBJECTS:
  1235. case ActionType.UNIT_ADD_COMPONENT:
  1236. if ((flags & ActionTypeFlags.FROM_SERVER) == 0)
  1237. on_objects_created(data);
  1238. break;
  1239. case ActionType.DESTROY_OBJECTS:
  1240. case ActionType.UNIT_REMOVE_COMPONENT:
  1241. if ((flags & ActionTypeFlags.FROM_SERVER) == 0)
  1242. on_objects_destroyed(data);
  1243. break;
  1244. case ActionType.MOVE_OBJECTS:
  1245. case ActionType.SET_TRANSFORM:
  1246. case ActionType.SET_LIGHT:
  1247. case ActionType.SET_MESH:
  1248. case ActionType.SET_SPRITE:
  1249. case ActionType.SET_CAMERA:
  1250. case ActionType.SET_COLLIDER:
  1251. case ActionType.SET_ACTOR:
  1252. case ActionType.SET_SCRIPT:
  1253. case ActionType.SET_ANIMATION_STATE_MACHINE:
  1254. case ActionType.SET_SOUND:
  1255. if ((flags & ActionTypeFlags.FROM_SERVER) == 0)
  1256. on_objects_changed(data);
  1257. break;
  1258. case ActionType.OBJECT_SET_EDITOR_NAME:
  1259. on_objects_changed(data);
  1260. _level.object_editor_name_changed(data[0], _level.object_editor_name(data[0]));
  1261. break;
  1262. default:
  1263. logw("Unknown action type %d".printf(id));
  1264. break;
  1265. }
  1266. _properties_view.show_or_hide_properties();
  1267. }
  1268. private void on_undo_redo(bool undo, uint32 id, Guid?[] data)
  1269. {
  1270. switch (id) {
  1271. case ActionType.SPAWN_UNIT:
  1272. case ActionType.SPAWN_SOUND:
  1273. case ActionType.DUPLICATE_OBJECTS:
  1274. case ActionType.UNIT_ADD_COMPONENT:
  1275. if (undo)
  1276. on_objects_destroyed(data);
  1277. else
  1278. on_objects_created(data);
  1279. break;
  1280. case ActionType.DESTROY_OBJECTS:
  1281. case ActionType.UNIT_REMOVE_COMPONENT:
  1282. if (undo)
  1283. on_objects_created(data);
  1284. else
  1285. on_objects_destroyed(data);
  1286. break;
  1287. case ActionType.MOVE_OBJECTS:
  1288. case ActionType.SET_TRANSFORM:
  1289. case ActionType.SET_LIGHT:
  1290. case ActionType.SET_MESH:
  1291. case ActionType.SET_SPRITE:
  1292. case ActionType.SET_CAMERA:
  1293. case ActionType.SET_COLLIDER:
  1294. case ActionType.SET_ACTOR:
  1295. case ActionType.SET_SCRIPT:
  1296. case ActionType.SET_ANIMATION_STATE_MACHINE:
  1297. case ActionType.SET_SOUND:
  1298. on_objects_changed(data);
  1299. break;
  1300. case ActionType.OBJECT_SET_EDITOR_NAME:
  1301. on_objects_changed(data);
  1302. _level.object_editor_name_changed(data[0], _level.object_editor_name(data[0]));
  1303. break;
  1304. default:
  1305. logw("Unknown action type %u".printf(id));
  1306. break;
  1307. }
  1308. _properties_view.show_or_hide_properties();
  1309. }
  1310. private bool on_button_press(Gdk.EventButton ev)
  1311. {
  1312. return Gdk.EVENT_STOP;
  1313. }
  1314. private bool on_button_release(Gdk.EventButton ev)
  1315. {
  1316. return Gdk.EVENT_STOP;
  1317. }
  1318. Gtk.Label compiling_data_label()
  1319. {
  1320. return new Gtk.Label("Compiling resources, please wait...");
  1321. }
  1322. Gtk.Label connecting_to_data_compiler_label()
  1323. {
  1324. return new Gtk.Label("Connecting to Data Compiler...");
  1325. }
  1326. Gtk.Label compiler_crashed_label()
  1327. {
  1328. Gtk.Label label = new Gtk.Label(null);
  1329. label.track_visited_links = false;
  1330. label.set_markup("Data Compiler disconnected.\rTry to <a href=\"restart\">restart the compiler</a> to continue.");
  1331. label.activate_link.connect(() => {
  1332. restart_backend.begin(_project.source_dir(), _level._name != null ? _level._name : "");
  1333. return true;
  1334. });
  1335. return label;
  1336. }
  1337. Gtk.Label compiler_failed_compilation_label()
  1338. {
  1339. Gtk.Label label = new Gtk.Label(null);
  1340. label.track_visited_links = false;
  1341. label.set_markup("Data compilation failed.\rFix errors and <a href=\"restart\">restart the compiler</a> to continue.");
  1342. label.activate_link.connect(() => {
  1343. restart_backend.begin(_project.source_dir(), _level._name != null ? _level._name : "");
  1344. return true;
  1345. });
  1346. return label;
  1347. }
  1348. Gtk.Label stopping_backend_label()
  1349. {
  1350. return new Gtk.Label("Stopping Backend...");
  1351. }
  1352. public async void restart_backend(string source_dir, string level_name)
  1353. {
  1354. string sd = source_dir.dup();
  1355. string ln = level_name.dup();
  1356. yield stop_backend();
  1357. // Reset project state.
  1358. _placeable_type = "unit";
  1359. _placeable_name = "core/units/primitives/cube";
  1360. // Load project and level if any.
  1361. logi("Loading project: `%s`...".printf(sd));
  1362. _project.load(sd);
  1363. // Spawn the data compiler.
  1364. string args[] =
  1365. {
  1366. ENGINE_EXE,
  1367. "--source-dir",
  1368. _project.source_dir(),
  1369. "--data-dir",
  1370. _project.data_dir(),
  1371. "--map-source-dir",
  1372. "core",
  1373. _project.toolchain_dir(),
  1374. "--server",
  1375. "--wait-console"
  1376. };
  1377. try {
  1378. _compiler._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1379. } catch (Error e) {
  1380. loge(e.message);
  1381. }
  1382. _project_stack.set_visible_child(_project_stack_connecting_to_data_compiler_label);
  1383. _editor_stack.set_visible_child(_editor_stack_connecting_to_data_compiler_label);
  1384. _inspector_stack.set_visible_child(_inspector_stack_connecting_to_data_compiler_label);
  1385. int tries = yield _compiler.connect_async(DATA_COMPILER_ADDRESS
  1386. , DATA_COMPILER_TCP_PORT
  1387. , DATA_COMPILER_CONNECTION_TRIES
  1388. , DATA_COMPILER_CONNECTION_INTERVAL
  1389. );
  1390. if (tries == DATA_COMPILER_CONNECTION_TRIES) {
  1391. loge("Cannot connect to data_compiler");
  1392. return;
  1393. }
  1394. _project_stack.set_visible_child(_project_stack_compiling_data_label);
  1395. _editor_stack.set_visible_child(_editor_stack_compiling_data_label);
  1396. _inspector_stack.set_visible_child(_inspector_stack_compiling_data_label);
  1397. // Compile data.
  1398. bool success = yield _data_compiler.compile(_project.data_dir(), _project.platform());
  1399. if (!success) {
  1400. _project_stack.set_visible_child(_project_stack_compiler_failed_compilation_label);
  1401. _editor_stack.set_visible_child(_editor_stack_compiler_failed_compilation_label);
  1402. _inspector_stack.set_visible_child(_inspector_stack_compiler_failed_compilation_label);
  1403. return;
  1404. }
  1405. // If successful, start the level editor.
  1406. load_level(ln);
  1407. yield restart_editor();
  1408. _project_stack.set_visible_child(_project_browser);
  1409. _inspector_stack.set_visible_child(_inspector_pane);
  1410. _project_browser.select_project_root();
  1411. return;
  1412. }
  1413. public async void stop_heads()
  1414. {
  1415. yield stop_game();
  1416. yield stop_editor();
  1417. }
  1418. public async void stop_backend()
  1419. {
  1420. _project_stack.set_visible_child(_project_stack_stopping_backend_label);
  1421. _editor_stack.set_visible_child(_editor_stack_stopping_backend_label);
  1422. _inspector_stack.set_visible_child(_inspector_stack_stopping_backend_label);
  1423. yield stop_heads();
  1424. yield stop_data_compiler();
  1425. _level.reset();
  1426. _project.reset();
  1427. this.active_window.title = CROWN_EDITOR_MAIN_WINDOW_TITLE;
  1428. }
  1429. private async void stop_data_compiler()
  1430. {
  1431. yield _compiler.stop();
  1432. }
  1433. private async void start_editor(uint window_xid, int width, int height)
  1434. {
  1435. if (window_xid == 0)
  1436. return;
  1437. // Spawn the level editor.
  1438. string args[] =
  1439. {
  1440. ENGINE_EXE,
  1441. "--data-dir",
  1442. _project.data_dir(),
  1443. "--boot-dir",
  1444. LEVEL_EDITOR_BOOT_DIR,
  1445. "--parent-window",
  1446. window_xid.to_string(),
  1447. "--wait-console",
  1448. "--pumped",
  1449. "--window-rect", "0", "0", width.to_string(), height.to_string()
  1450. };
  1451. try {
  1452. _editor._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1453. _editor._revision = _data_compiler._revision;
  1454. } catch (Error e) {
  1455. loge(e.message);
  1456. }
  1457. // Try to connect to the level editor.
  1458. int tries = yield _editor.connect_async(EDITOR_ADDRESS
  1459. , EDITOR_TCP_PORT
  1460. , EDITOR_CONNECTION_TRIES
  1461. , EDITOR_CONNECTION_INTERVAL
  1462. );
  1463. if (tries == EDITOR_CONNECTION_TRIES) {
  1464. loge("Cannot connect to level_editor");
  1465. return;
  1466. }
  1467. }
  1468. private async void start_resource_preview(uint window_xid, int width, int height)
  1469. {
  1470. if (window_xid == 0)
  1471. return;
  1472. // Spawn unit_preview.
  1473. string args[] =
  1474. {
  1475. ENGINE_EXE,
  1476. "--data-dir",
  1477. _project.data_dir(),
  1478. "--boot-dir",
  1479. UNIT_PREVIEW_BOOT_DIR,
  1480. "--parent-window",
  1481. window_xid.to_string(),
  1482. "--console-port",
  1483. UNIT_PREVIEW_TCP_PORT.to_string(),
  1484. "--wait-console",
  1485. "--pumped",
  1486. "--window-rect", "0", "0", width.to_string(), height.to_string()
  1487. };
  1488. try {
  1489. _resource_preview._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1490. _resource_preview._revision = _data_compiler._revision;
  1491. } catch (Error e) {
  1492. loge(e.message);
  1493. }
  1494. // Try to connect to unit_preview.
  1495. int tries = yield _resource_preview.connect_async(UNIT_PREVIEW_ADDRESS
  1496. , UNIT_PREVIEW_TCP_PORT
  1497. , EDITOR_CONNECTION_TRIES
  1498. , EDITOR_CONNECTION_INTERVAL
  1499. );
  1500. if (tries == EDITOR_CONNECTION_TRIES) {
  1501. loge("Cannot connect to unit_preview.");
  1502. return;
  1503. }
  1504. // FIXME: This should be done in ResourceChooser.
  1505. _resource_chooser._tree_view.set_cursor(new Gtk.TreePath.first(), null, false);
  1506. }
  1507. private async void stop_editor()
  1508. {
  1509. yield stop_thumbnail();
  1510. yield stop_resource_preview();
  1511. yield _editor.stop();
  1512. _editor_stack.set_visible_child(_editor_stack_disconnected_label);
  1513. }
  1514. public async void stop_resource_preview()
  1515. {
  1516. yield _resource_preview.stop();
  1517. _resource_preview_stack.set_visible_child(_resource_preview_disconnected_label);
  1518. }
  1519. private async void restart_editor()
  1520. {
  1521. yield stop_editor();
  1522. if (_editor_view != null) {
  1523. _editor_view_overlay.remove(_editor_view);
  1524. _editor_stack.remove(_editor_view_overlay);
  1525. _editor_view = null;
  1526. }
  1527. _editor_view = new EditorView(_editor);
  1528. _editor_view.native_window_ready.connect(on_editor_view_realized);
  1529. _editor_view.button_press_event.connect(on_button_press);
  1530. _editor_view.button_release_event.connect(on_button_release);
  1531. _editor_view_overlay.add(_editor_view);
  1532. _editor_view_overlay.show_all();
  1533. _editor_stack.add(_editor_view_overlay);
  1534. _editor_stack.set_visible_child(_editor_view_overlay);
  1535. yield restart_resource_preview();
  1536. yield start_thumbnail();
  1537. }
  1538. private async void restart_resource_preview()
  1539. {
  1540. yield stop_resource_preview();
  1541. if (_resource_preview_view != null) {
  1542. _resource_preview_stack.remove(_resource_preview_view);
  1543. _resource_preview_view = null;
  1544. }
  1545. _resource_preview_view = new EditorView(_resource_preview, false);
  1546. _resource_preview_view.set_size_request(300, 300);
  1547. _resource_preview_view.native_window_ready.connect(on_resource_preview_view_realized);
  1548. _resource_preview_view.show_all();
  1549. _resource_preview_stack.add(_resource_preview_view);
  1550. _resource_preview_stack.set_visible_child(_resource_preview_view);
  1551. }
  1552. private int dump_test_level()
  1553. {
  1554. try {
  1555. // Save temporary package to reference test level.
  1556. ArrayList<Value?> level = new ArrayList<Value?>();
  1557. level.add("_level_editor_test");
  1558. Hashtable package = new Hashtable();
  1559. package["level"] = level;
  1560. SJSON.save(package, _project._level_editor_test_package.get_path());
  1561. } catch (JsonWriteError e) {
  1562. return -1;
  1563. }
  1564. // Save test level to file.
  1565. return _database.dump(_project._level_editor_test_level.get_path(), _level._id);
  1566. }
  1567. private async void start_game(StartGame sg)
  1568. {
  1569. if (sg == StartGame.TEST && dump_test_level() != 0)
  1570. return;
  1571. bool success = yield _data_compiler.compile(_project.data_dir(), _project.platform());
  1572. _project.delete_garbage();
  1573. if (!success) {
  1574. _toolbar_run.icon_name = "game-run";
  1575. return;
  1576. }
  1577. // Spawn the game.
  1578. string args[] =
  1579. {
  1580. ENGINE_EXE,
  1581. "--data-dir",
  1582. _project.data_dir(),
  1583. "--console-port",
  1584. GAME_TCP_PORT.to_string(),
  1585. "--wait-console",
  1586. "--lua-string",
  1587. sg == StartGame.TEST ? "TEST=true" : ""
  1588. };
  1589. try {
  1590. _game._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1591. _game._revision = _data_compiler._revision;
  1592. } catch (Error e) {
  1593. loge(e.message);
  1594. }
  1595. // Try to connect to the game.
  1596. int tries = yield _game.connect_async(GAME_ADDRESS
  1597. , GAME_TCP_PORT
  1598. , GAME_CONNECTION_TRIES
  1599. , GAME_CONNECTION_INTERVAL
  1600. );
  1601. if (tries == GAME_CONNECTION_TRIES) {
  1602. loge("Cannot connect to game");
  1603. return;
  1604. }
  1605. }
  1606. private async void start_thumbnail()
  1607. {
  1608. string args[] =
  1609. {
  1610. ENGINE_EXE,
  1611. "--data-dir",
  1612. _project.data_dir(),
  1613. "--boot-dir",
  1614. THUMBNAIL_BOOT_DIR,
  1615. "--console-port",
  1616. THUMBNAIL_TCP_PORT.to_string(),
  1617. "--wait-console",
  1618. "--pumped",
  1619. "--hidden"
  1620. };
  1621. try {
  1622. _thumbnail._process_id = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1623. _thumbnail._revision = _data_compiler._revision;
  1624. } catch (Error e) {
  1625. loge(e.message);
  1626. }
  1627. // Try to connect to the game.
  1628. int tries = yield _thumbnail.connect_async(THUMBNAIL_ADDRESS
  1629. , THUMBNAIL_TCP_PORT
  1630. , THUMBNAIL_CONNECTION_TRIES
  1631. , THUMBNAIL_CONNECTION_INTERVAL
  1632. );
  1633. if (tries == THUMBNAIL_CONNECTION_TRIES) {
  1634. loge("Cannot connect to thumbnail");
  1635. return;
  1636. }
  1637. }
  1638. private async void stop_game()
  1639. {
  1640. yield _game.stop();
  1641. }
  1642. private async void stop_thumbnail()
  1643. {
  1644. yield _thumbnail.stop();
  1645. }
  1646. private async void on_editor_view_realized(uint window_id, int width, int height)
  1647. {
  1648. start_editor.begin(window_id, width, height);
  1649. }
  1650. private async void on_resource_preview_view_realized(uint window_id, int width, int height)
  1651. {
  1652. start_resource_preview.begin(window_id, width, height);
  1653. }
  1654. private void on_tool(GLib.SimpleAction action, GLib.Variant? param)
  1655. {
  1656. ToolType type = (ToolType)param.get_int32();
  1657. if (type == ToolType.PLACE) {
  1658. // Store previous tool for it to be restored later.
  1659. if (_tool_type != ToolType.PLACE)
  1660. _tool_type_prev = _tool_type;
  1661. }
  1662. _tool_type = type;
  1663. _editor_view.grab_focus();
  1664. send_state();
  1665. _editor.send(DeviceApi.frame());
  1666. action.set_state(param);
  1667. }
  1668. private void on_cancel_place(GLib.SimpleAction action, GLib.Variant? param)
  1669. {
  1670. if (_tool_type != ToolType.PLACE)
  1671. return;
  1672. activate_action("tool", new GLib.Variant.int32(_tool_type_prev));
  1673. }
  1674. private void on_snap(GLib.SimpleAction action, GLib.Variant? param)
  1675. {
  1676. _snap_mode = (SnapMode)param.get_int32();
  1677. send_state();
  1678. _editor.send(DeviceApi.frame());
  1679. action.set_state(param);
  1680. }
  1681. private void on_reference_system(GLib.SimpleAction action, GLib.Variant? param)
  1682. {
  1683. _reference_system = (ReferenceSystem)param.get_int32();
  1684. send_state();
  1685. _editor.send(DeviceApi.frame());
  1686. action.set_state(param);
  1687. }
  1688. private void on_grid_size(GLib.SimpleAction action, GLib.Variant? param)
  1689. {
  1690. int32 new_size = param.get_int32();
  1691. if (new_size != 0) {
  1692. _grid_size = (double)new_size / 10.0;
  1693. send_state();
  1694. _editor.send(DeviceApi.frame());
  1695. action.set_state(param);
  1696. return;
  1697. }
  1698. // Custom grid size.
  1699. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Grid size"
  1700. , this.active_window
  1701. , DialogFlags.MODAL
  1702. , "Cancel"
  1703. , ResponseType.CANCEL
  1704. , "Ok"
  1705. , ResponseType.OK
  1706. , null
  1707. );
  1708. EntryDouble sb = new EntryDouble(_grid_size, 0.1, 1000);
  1709. sb.activate.connect(() => { dg.response(ResponseType.OK); });
  1710. dg.get_content_area().add(sb);
  1711. dg.skip_taskbar_hint = true;
  1712. dg.show_all();
  1713. if (dg.run() == ResponseType.OK) {
  1714. _grid_size = sb.value;
  1715. send_state();
  1716. _editor.send(DeviceApi.frame());
  1717. action.set_state(param);
  1718. }
  1719. dg.destroy();
  1720. }
  1721. private void new_level()
  1722. {
  1723. _level.load_from_path(LEVEL_EMPTY);
  1724. _level.send_level();
  1725. _editor.send(DeviceApi.frame());
  1726. }
  1727. private void update_active_window_title()
  1728. {
  1729. string title = "";
  1730. if (_level._name != null) {
  1731. if (_database.changed())
  1732. title += " • ";
  1733. title += (_level._name == LEVEL_EMPTY) ? "untitled" : _level._name;
  1734. title += " - ";
  1735. }
  1736. title += CROWN_EDITOR_MAIN_WINDOW_TITLE;
  1737. if (this.active_window.title != title)
  1738. this.active_window.title = title;
  1739. }
  1740. private void load_level(string name)
  1741. {
  1742. if (name == _level._name)
  1743. return;
  1744. string resource_name = name != "" ? name : LEVEL_EMPTY;
  1745. if (_level.load_from_path(resource_name) != 0) {
  1746. loge("Unable to load level %s".printf(resource_name));
  1747. return;
  1748. }
  1749. if (_editor.is_connected()) {
  1750. _level.send_level();
  1751. send_state();
  1752. _editor.send(DeviceApi.frame());
  1753. }
  1754. update_active_window_title();
  1755. }
  1756. private bool save_as(string? filename)
  1757. {
  1758. string path = filename;
  1759. if (path == null) {
  1760. Gtk.FileChooserDialog fcd = new Gtk.FileChooserDialog("Save As..."
  1761. , this.active_window
  1762. , FileChooserAction.SAVE
  1763. , "Cancel"
  1764. , ResponseType.CANCEL
  1765. , "Save"
  1766. , ResponseType.ACCEPT
  1767. );
  1768. fcd.add_filter(_file_filter);
  1769. fcd.set_current_folder(_project.source_dir());
  1770. int rt = ResponseType.CANCEL;
  1771. do {
  1772. // Select the file
  1773. rt = fcd.run();
  1774. if (rt != ResponseType.ACCEPT) {
  1775. fcd.destroy();
  1776. return false;
  1777. }
  1778. path = fcd.get_filename();
  1779. // Append file extension
  1780. if (!path.has_suffix(".level"))
  1781. path += ".level";
  1782. // Check if the file is within the source directory
  1783. if (!_project.path_is_within_source_dir(path)) {
  1784. Gtk.MessageDialog md = new Gtk.MessageDialog(fcd
  1785. , DialogFlags.MODAL
  1786. , MessageType.WARNING
  1787. , Gtk.ButtonsType.OK
  1788. , "The file must be within the source directory."
  1789. );
  1790. md.set_default_response(ResponseType.OK);
  1791. md.run();
  1792. md.destroy();
  1793. fcd.set_current_folder(_project.source_dir());
  1794. continue;
  1795. }
  1796. // Check if the file already exists
  1797. rt = ResponseType.YES;
  1798. if (GLib.FileUtils.test(path, FileTest.EXISTS)) {
  1799. Gtk.MessageDialog md = new Gtk.MessageDialog(fcd
  1800. , DialogFlags.MODAL
  1801. , MessageType.QUESTION
  1802. , Gtk.ButtonsType.NONE
  1803. , "A file named `%s` already exists.\nOverwrite?".printf(GLib.Path.get_basename(path))
  1804. );
  1805. Gtk.Widget btn;
  1806. md.add_button("_No", ResponseType.NO);
  1807. btn = md.add_button("_Yes", ResponseType.YES);
  1808. btn.get_style_context().add_class(Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION);
  1809. md.set_default_response(ResponseType.NO);
  1810. rt = md.run();
  1811. md.destroy();
  1812. }
  1813. } while (rt != ResponseType.YES);
  1814. fcd.destroy();
  1815. }
  1816. // Save level
  1817. string resource_filename = _project.resource_filename(path);
  1818. string resource_path = ResourceId.normalize(resource_filename);
  1819. string resource_name = ResourceId.name(resource_path);
  1820. _level.save(resource_name);
  1821. _statusbar.set_temporary_message("Saved %s".printf(_level._path));
  1822. update_active_window_title();
  1823. return true;
  1824. }
  1825. private bool save()
  1826. {
  1827. return save_as(_level._path);
  1828. }
  1829. private bool save_timeout()
  1830. {
  1831. if (_level._path != null)
  1832. save();
  1833. return GLib.Source.CONTINUE;
  1834. }
  1835. private Hashtable encode()
  1836. {
  1837. Hashtable json_obj = new Hashtable();
  1838. json_obj["level_editor_window"] = ((LevelEditorWindow)this.active_window).encode();
  1839. return json_obj;
  1840. }
  1841. protected override void shutdown()
  1842. {
  1843. // Disable auto-save.
  1844. if (_save_timer_id > 0)
  1845. GLib.Source.remove(_save_timer_id);
  1846. // Save editor settings.
  1847. _user.save(_user_file.get_path());
  1848. _preferences_dialog.encode(_settings);
  1849. try {
  1850. SJSON.save(_settings, _settings_file.get_path());
  1851. } catch (JsonWriteError e) {
  1852. loge(e.message);
  1853. }
  1854. try {
  1855. SJSON.save(encode(), _window_state_file.get_path());
  1856. } catch (JsonWriteError e) {
  1857. loge(e.message);
  1858. }
  1859. _console_view._entry_history.save(_console_history_file.get_path());
  1860. // Destroy widgets.
  1861. if (_resource_chooser != null)
  1862. _resource_chooser.destroy();
  1863. if (_preferences_dialog != null)
  1864. _preferences_dialog.destroy();
  1865. base.shutdown();
  1866. }
  1867. // Returns true if the level has been saved or the user decided it
  1868. // should be discarded.
  1869. public bool should_quit()
  1870. {
  1871. int rt = ResponseType.YES;
  1872. if (_database.changed())
  1873. rt = run_level_changed_dialog(this.active_window);
  1874. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO)
  1875. return true;
  1876. return false;
  1877. }
  1878. private void on_new_level(GLib.SimpleAction action, GLib.Variant? param)
  1879. {
  1880. int rt = ResponseType.YES;
  1881. if (_database.changed())
  1882. rt = run_level_changed_dialog(this.active_window);
  1883. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1884. new_level();
  1885. send_state();
  1886. _editor.send(DeviceApi.frame());
  1887. }
  1888. }
  1889. private void on_open_level_from_menubar(GLib.SimpleAction action, GLib.Variant? param)
  1890. {
  1891. string path = "";
  1892. Gtk.FileChooserDialog fcd = new Gtk.FileChooserDialog("Open Level..."
  1893. , this.active_window
  1894. , FileChooserAction.OPEN
  1895. , "Cancel"
  1896. , ResponseType.CANCEL
  1897. , "Open"
  1898. , ResponseType.ACCEPT
  1899. );
  1900. fcd.add_filter(_file_filter);
  1901. fcd.set_current_folder(_project.source_dir());
  1902. int err = 1;
  1903. int rt = ResponseType.CANCEL;
  1904. do {
  1905. // Select the file
  1906. rt = fcd.run();
  1907. if (rt != ResponseType.ACCEPT) {
  1908. fcd.destroy();
  1909. return;
  1910. }
  1911. path = fcd.get_filename();
  1912. err = 0;
  1913. // Append file extension
  1914. if (!path.has_suffix(".level"))
  1915. path += ".level";
  1916. if (!_project.path_is_within_source_dir(path)) {
  1917. Gtk.MessageDialog md = new Gtk.MessageDialog(fcd
  1918. , DialogFlags.MODAL
  1919. , MessageType.WARNING
  1920. , Gtk.ButtonsType.OK
  1921. , "The file must be within the source directory."
  1922. );
  1923. md.set_default_response(ResponseType.OK);
  1924. md.run();
  1925. md.destroy();
  1926. fcd.set_current_folder(_project.source_dir());
  1927. err = 1;
  1928. continue;
  1929. }
  1930. } while (err != 0);
  1931. fcd.destroy();
  1932. assert(path != "");
  1933. // Load level
  1934. string resource_filename = _project.resource_filename(path);
  1935. string resource_path = ResourceId.normalize(resource_filename);
  1936. string resource_name = ResourceId.name(resource_path);
  1937. load_level(resource_name);
  1938. }
  1939. private void on_open_level(GLib.SimpleAction action, GLib.Variant? param)
  1940. {
  1941. int rt = ResponseType.YES;
  1942. string level_name = param.get_string();
  1943. if (level_name != "" && level_name == _level._name)
  1944. return;
  1945. if (_database.changed())
  1946. rt = run_level_changed_dialog(this.active_window);
  1947. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1948. if (level_name != "")
  1949. load_level(level_name);
  1950. else // Action invoked from menubar File > Open Level...
  1951. on_open_level_from_menubar(action, param);
  1952. }
  1953. }
  1954. private void on_open_project(GLib.SimpleAction action, GLib.Variant? param)
  1955. {
  1956. int rt = ResponseType.YES;
  1957. if (_database.changed())
  1958. rt = run_level_changed_dialog(this.active_window);
  1959. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1960. string source_dir;
  1961. source_dir = param.get_string();
  1962. if (source_dir == "") {
  1963. // Project opened from menubar.
  1964. rt = run_open_project_dialog(out source_dir, this.active_window);
  1965. if (rt != ResponseType.ACCEPT)
  1966. return;
  1967. }
  1968. if (_project.source_dir() == source_dir)
  1969. return;
  1970. // Naively check whether the selected folder contains a Crown project.
  1971. if (!GLib.File.new_for_path(GLib.Path.build_filename(source_dir, "boot.config")).query_exists()
  1972. || !GLib.File.new_for_path(GLib.Path.build_filename(source_dir, "global.physics_config")).query_exists()
  1973. ) {
  1974. Gtk.MessageDialog md = new Gtk.MessageDialog(this.active_window
  1975. , Gtk.DialogFlags.MODAL
  1976. , Gtk.MessageType.INFO
  1977. , Gtk.ButtonsType.OK
  1978. , "The selected folder does not appear to be a valid Crown project."
  1979. );
  1980. md.set_default_response(ResponseType.OK);
  1981. md.run();
  1982. md.destroy();
  1983. return;
  1984. }
  1985. this.show_panel("main_vbox", Gtk.StackTransitionType.NONE);
  1986. _user.add_or_touch_recent_project(source_dir, source_dir);
  1987. _console_view.reset();
  1988. restart_backend.begin(source_dir, LEVEL_NONE, (obj, res) => {
  1989. restart_backend.end(res);
  1990. });
  1991. }
  1992. }
  1993. private void on_new_project(GLib.SimpleAction action, GLib.Variant? param)
  1994. {
  1995. int rt = ResponseType.YES;
  1996. if (_database.changed())
  1997. rt = run_level_changed_dialog(this.active_window);
  1998. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1999. stop_backend.begin((obj, res) => {
  2000. stop_backend.end(res);
  2001. show_panel("panel_new_project");
  2002. });
  2003. }
  2004. }
  2005. private void on_add_project(GLib.SimpleAction action, GLib.Variant? param)
  2006. {
  2007. string source_dir;
  2008. int rt = run_open_project_dialog(out source_dir, this.active_window);
  2009. if (rt != ResponseType.ACCEPT)
  2010. return;
  2011. _user.add_or_touch_recent_project(source_dir, source_dir);
  2012. }
  2013. private void on_save(GLib.SimpleAction action, GLib.Variant? param)
  2014. {
  2015. save();
  2016. }
  2017. private void on_save_as(GLib.SimpleAction action, GLib.Variant? param)
  2018. {
  2019. save_as(null);
  2020. }
  2021. private void on_import_result(ImportResult result)
  2022. {
  2023. if (result == ImportResult.ERROR) {
  2024. loge("Failed to import resource(s)");
  2025. return;
  2026. } else if (result == ImportResult.SUCCESS) {
  2027. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  2028. _data_compiler.compile.end(res);
  2029. });
  2030. }
  2031. // FIXME: hack to force PropertiesView to update.
  2032. _level.selection_changed(_level._selection);
  2033. }
  2034. private void on_import(GLib.SimpleAction action, GLib.Variant? param)
  2035. {
  2036. string? destination_dir = param == null ? null : param.get_string();
  2037. ImportResult ec = _project.import(destination_dir
  2038. , on_import_result
  2039. , _project_store
  2040. , this.active_window
  2041. );
  2042. if (ec != ImportResult.CALLBACK)
  2043. on_import_result(ec);
  2044. }
  2045. private void on_preferences(GLib.SimpleAction action, GLib.Variant? param)
  2046. {
  2047. _preferences_dialog.set_transient_for(this.active_window);
  2048. _preferences_dialog.set_position(Gtk.WindowPosition.CENTER_ON_PARENT);
  2049. _preferences_dialog.show_all();
  2050. _preferences_dialog.present();
  2051. }
  2052. private void on_deploy(GLib.SimpleAction action, GLib.Variant? param)
  2053. {
  2054. if (_deploy_dialog == null) {
  2055. _deploy_dialog = new DeployDialog(_project, _editor);
  2056. _deploy_dialog.set_transient_for(this.active_window);
  2057. _deploy_dialog.set_position(Gtk.WindowPosition.CENTER_ON_PARENT);
  2058. _deploy_dialog.delete_event.connect(_deploy_dialog.hide_on_delete);
  2059. }
  2060. _deploy_dialog.show_all();
  2061. _deploy_dialog.present();
  2062. }
  2063. private void on_texture_settings(GLib.SimpleAction action, GLib.Variant? param)
  2064. {
  2065. string texture_name = param.get_string();
  2066. if (_texture_settings_dialog == null) {
  2067. _texture_settings_dialog = new TextureSettingsDialog(_project, _project_store, _database);
  2068. _texture_settings_dialog.set_transient_for(this.active_window);
  2069. _texture_settings_dialog.set_position(Gtk.WindowPosition.CENTER_ON_PARENT);
  2070. _texture_settings_dialog.delete_event.connect(_texture_settings_dialog.hide_on_delete);
  2071. _texture_settings_dialog.texture_saved.connect(() => {
  2072. _data_compiler.compile.begin(_project.data_dir(), _project.platform());
  2073. });
  2074. }
  2075. _texture_settings_dialog.set_texture(texture_name);
  2076. _texture_settings_dialog.show_all();
  2077. _texture_settings_dialog.present();
  2078. }
  2079. private int run_level_changed_dialog(Gtk.Window? parent)
  2080. {
  2081. Gtk.MessageDialog md = new Gtk.MessageDialog(parent
  2082. , Gtk.DialogFlags.MODAL
  2083. , Gtk.MessageType.WARNING
  2084. , Gtk.ButtonsType.NONE
  2085. , "Save changes to Level before closing?"
  2086. );
  2087. Gtk.Widget btn;
  2088. btn = md.add_button("Close _without Saving", ResponseType.NO);
  2089. btn.get_style_context().add_class(Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION);
  2090. md.add_button("_Cancel", ResponseType.CANCEL);
  2091. md.add_button("_Save", ResponseType.YES);
  2092. md.set_default_response(ResponseType.YES);
  2093. int rt = md.run();
  2094. md.destroy();
  2095. return rt;
  2096. }
  2097. public int run_open_project_dialog(out string source_dir, Gtk.Window? parent)
  2098. {
  2099. Gtk.FileChooserDialog fcd = new Gtk.FileChooserDialog("Open Project..."
  2100. , parent
  2101. , FileChooserAction.SELECT_FOLDER
  2102. , "Cancel"
  2103. , ResponseType.CANCEL
  2104. , "Open"
  2105. , ResponseType.ACCEPT
  2106. );
  2107. int rt = fcd.run();
  2108. source_dir = fcd.get_filename();
  2109. fcd.destroy();
  2110. return rt;
  2111. }
  2112. private void on_close_project(GLib.SimpleAction action, GLib.Variant? param)
  2113. {
  2114. int rt = ResponseType.YES;
  2115. if (_database.changed())
  2116. rt = run_level_changed_dialog(this.active_window);
  2117. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  2118. stop_backend.begin((obj, res) => {
  2119. stop_backend.end(res);
  2120. show_panel("panel_welcome");
  2121. });
  2122. }
  2123. }
  2124. public void stop_backend_and_quit()
  2125. {
  2126. stop_backend.begin((obj, res) => {
  2127. stop_backend.end(res);
  2128. this.quit();
  2129. });
  2130. }
  2131. private void on_quit(GLib.SimpleAction action, GLib.Variant? param)
  2132. {
  2133. if (should_quit())
  2134. stop_backend_and_quit();
  2135. }
  2136. public static bool is_image_file(string path)
  2137. {
  2138. return path.has_suffix(".png")
  2139. || path.has_suffix(".tga")
  2140. ;
  2141. }
  2142. private void on_open_resource(GLib.SimpleAction action, GLib.Variant? param)
  2143. {
  2144. if (param == null)
  2145. return;
  2146. string resource_path = param.get_string();
  2147. string? resource_type = ResourceId.type(resource_path);
  2148. string? resource_name = ResourceId.name(resource_path);
  2149. if (resource_type == null || resource_name == null)
  2150. return;
  2151. if (resource_type == "level") {
  2152. activate_action("open-level", resource_name);
  2153. return;
  2154. } else if (resource_type == "texture") {
  2155. activate_action("texture-settings", resource_name);
  2156. return;
  2157. }
  2158. GLib.AppInfo? app = null;
  2159. if (resource_type == "lua") {
  2160. app = _preferences_dialog._lua_external_tool_button.get_app_info();
  2161. } else if (is_image_file(resource_path)) {
  2162. app = _preferences_dialog._image_external_tool_button.get_app_info();
  2163. }
  2164. try {
  2165. GLib.File file = GLib.File.new_for_path(_project.absolute_path(resource_path));
  2166. if (app == null)
  2167. app = file.query_default_handler();
  2168. GLib.List<GLib.File> files = new GLib.List<GLib.File>();
  2169. files.append(file);
  2170. app.launch(files, null);
  2171. } catch (Error e) {
  2172. loge(e.message);
  2173. }
  2174. }
  2175. private void copy_string(string str)
  2176. {
  2177. var clip = Gtk.Clipboard.get_default(Gdk.Display.get_default());
  2178. clip.set_text(str, str.length);
  2179. #if !CROWN_PLATFORM_WINDOWS
  2180. clip.store();
  2181. #endif
  2182. }
  2183. private void on_copy_path(GLib.SimpleAction action, GLib.Variant? param)
  2184. {
  2185. string path = param.get_string();
  2186. copy_string(_project.absolute_path(path));
  2187. }
  2188. private void on_copy_name(GLib.SimpleAction action, GLib.Variant? param)
  2189. {
  2190. copy_string(param.get_string());
  2191. }
  2192. private void on_show_grid(GLib.SimpleAction action, GLib.Variant? param)
  2193. {
  2194. _show_grid = !action.get_state().get_boolean();
  2195. send_state();
  2196. _editor.send(DeviceApi.frame());
  2197. action.set_state(new GLib.Variant.boolean(_show_grid));
  2198. }
  2199. private void on_rotation_snap_size(GLib.SimpleAction action, GLib.Variant? param)
  2200. {
  2201. int32 new_size = param.get_int32();
  2202. if (new_size != 0) {
  2203. _rotation_snap = (double)new_size;
  2204. send_state();
  2205. _editor.send(DeviceApi.frame());
  2206. action.set_state(param);
  2207. return;
  2208. }
  2209. // Custom rotation size.
  2210. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Rotation snap"
  2211. , this.active_window
  2212. , DialogFlags.MODAL
  2213. , "Cancel"
  2214. , ResponseType.CANCEL
  2215. , "Ok"
  2216. , ResponseType.OK
  2217. , null
  2218. );
  2219. EntryDouble sb = new EntryDouble(_rotation_snap, 1.0, 180.0);
  2220. sb.activate.connect(() => { dg.response(ResponseType.OK); });
  2221. dg.get_content_area().add(sb);
  2222. dg.skip_taskbar_hint = true;
  2223. dg.show_all();
  2224. if (dg.run() == ResponseType.OK) {
  2225. _rotation_snap = sb.value;
  2226. send_state();
  2227. _editor.send(DeviceApi.frame());
  2228. action.set_state(param);
  2229. }
  2230. dg.destroy();
  2231. }
  2232. private void on_spawn_primitive(GLib.SimpleAction action, GLib.Variant? param)
  2233. {
  2234. GLib.Variant[] paramz;
  2235. if (action.name == "primitive-cube")
  2236. paramz = { "unit", "core/units/primitives/cube" };
  2237. else if (action.name == "primitive-sphere")
  2238. paramz = { "unit", "core/units/primitives/sphere" };
  2239. else if (action.name == "primitive-cone")
  2240. paramz = { "unit", "core/units/primitives/cone" };
  2241. else if (action.name == "primitive-cylinder")
  2242. paramz = { "unit", "core/units/primitives/cylinder" };
  2243. else if (action.name == "primitive-plane")
  2244. paramz = { "unit", "core/units/primitives/plane" };
  2245. else if (action.name == "camera")
  2246. paramz = { "unit", "core/units/camera" };
  2247. else if (action.name == "light")
  2248. paramz = { "unit", "core/units/light" };
  2249. else if (action.name == "sound-source")
  2250. paramz = { "sound", "" };
  2251. else
  2252. paramz = { "unit", "core/units/primitives/cube" };
  2253. activate_action("set-placeable", new GLib.Variant.tuple(paramz));
  2254. }
  2255. private void on_spawn_unit(GLib.SimpleAction action, GLib.Variant? param)
  2256. {
  2257. _level.spawn_empty_unit();
  2258. _editor.send(DeviceApi.frame());
  2259. }
  2260. private void on_camera_view(GLib.SimpleAction action, GLib.Variant? param)
  2261. {
  2262. _level._camera_view_type = (CameraViewType)param.get_int32();
  2263. _editor.send_script(LevelEditorApi.set_camera_view_type(_level._camera_view_type));
  2264. _editor.send(DeviceApi.frame());
  2265. action.set_state(param);
  2266. }
  2267. private void on_camera_frame_selected(GLib.SimpleAction action, GLib.Variant? param)
  2268. {
  2269. Guid?[] selected_objects = _level._selection.to_array();
  2270. _editor.send_script(LevelEditorApi.frame_objects(selected_objects));
  2271. _editor.send(DeviceApi.frame());
  2272. }
  2273. private void on_camera_frame_all(GLib.SimpleAction action, GLib.Variant? param)
  2274. {
  2275. Gee.ArrayList<Guid?> all_objects = new Gee.ArrayList<Guid?>();
  2276. _level.objects(ref all_objects);
  2277. _editor.send_script(LevelEditorApi.frame_objects(all_objects.to_array()));
  2278. _editor.send(DeviceApi.frame());
  2279. }
  2280. private void on_resource_chooser(GLib.SimpleAction action, GLib.Variant? param)
  2281. {
  2282. _resource_popover.show_all();
  2283. }
  2284. private void on_project_browser(GLib.SimpleAction action, GLib.Variant? param)
  2285. {
  2286. if (_project_notebook.is_visible()) {
  2287. _project_notebook.hide();
  2288. } else {
  2289. _project_notebook.show_all();
  2290. }
  2291. }
  2292. private void on_console(GLib.SimpleAction action, GLib.Variant? param)
  2293. {
  2294. if (_console_notebook.is_visible()) {
  2295. if (_console_view._entry.has_focus)
  2296. _console_notebook.hide();
  2297. else
  2298. _console_view._entry.grab_focus_without_selecting();
  2299. } else {
  2300. _console_notebook.show_all();
  2301. _console_view._entry.grab_focus_without_selecting();
  2302. }
  2303. }
  2304. private void on_statusbar(GLib.SimpleAction action, GLib.Variant? param)
  2305. {
  2306. if (_statusbar.is_visible()) {
  2307. _statusbar.hide();
  2308. } else {
  2309. _statusbar.show_all();
  2310. }
  2311. }
  2312. private void on_inspector(GLib.SimpleAction action, GLib.Variant? param)
  2313. {
  2314. if (_inspector_stack.is_visible()) {
  2315. _inspector_stack.hide();
  2316. } else {
  2317. _inspector_stack.show_all();
  2318. }
  2319. }
  2320. private void on_restart_editor_view(GLib.SimpleAction action, GLib.Variant? param)
  2321. {
  2322. restart_editor.begin((obj, res) => {
  2323. restart_editor.end(res);
  2324. });
  2325. }
  2326. private void on_build_data(GLib.SimpleAction action, GLib.Variant? param)
  2327. {
  2328. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  2329. _data_compiler.compile.end(res);
  2330. });
  2331. }
  2332. private void on_refresh_lua(GLib.SimpleAction action, GLib.Variant? param)
  2333. {
  2334. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  2335. if (_data_compiler.compile.end(res)) {
  2336. refresh_all_clients.begin();
  2337. }
  2338. });
  2339. }
  2340. private async bool refresh_all_clients()
  2341. {
  2342. RuntimeInstance[] runtimes = new RuntimeInstance[] { _editor, _resource_preview, _game, _thumbnail };
  2343. bool success = true;
  2344. foreach (var ri in runtimes)
  2345. if (!yield ri.refresh(_data_compiler))
  2346. success = false;
  2347. return success;
  2348. }
  2349. private void on_snap_to_grid(GLib.SimpleAction action, GLib.Variant? param)
  2350. {
  2351. _snap_to_grid = !action.get_state().get_boolean();
  2352. send_state();
  2353. _editor.send(DeviceApi.frame());
  2354. action.set_state(new GLib.Variant.boolean(_snap_to_grid));
  2355. }
  2356. private void on_debug_render_world(GLib.SimpleAction action, GLib.Variant? param)
  2357. {
  2358. _debug_render_world = !action.get_state().get_boolean();
  2359. send_state();
  2360. _editor.send(DeviceApi.frame());
  2361. action.set_state(new GLib.Variant.boolean(_debug_render_world));
  2362. }
  2363. private void on_debug_physics_world(GLib.SimpleAction action, GLib.Variant? param)
  2364. {
  2365. _debug_physics_world = !action.get_state().get_boolean();
  2366. send_state();
  2367. _editor.send(DeviceApi.frame());
  2368. action.set_state(new GLib.Variant.boolean(_debug_physics_world));
  2369. }
  2370. private void on_run_game(GLib.SimpleAction action, GLib.Variant? param)
  2371. {
  2372. // Trigger a 'focus_out_event' on the currently focused
  2373. // widget within the active_window, if any. This will
  2374. // force 'focus' to commit its pending changes to the
  2375. // database so we do not miss any modifications before
  2376. // launching the game.
  2377. Gtk.Widget? focus = this.active_window.get_focus();
  2378. _editor_view.grab_focus();
  2379. if (focus != null)
  2380. focus.grab_focus();
  2381. string icon_name_displayed = _toolbar_run.icon_name;
  2382. stop_game.begin((obj, res) => {
  2383. stop_game.end(res);
  2384. if (icon_name_displayed == "game-run") {
  2385. // Always change icon state regardless of failures
  2386. _toolbar_run.icon_name = "game-stop";
  2387. start_game.begin(action.name == "test-level" ? StartGame.TEST : StartGame.NORMAL);
  2388. }
  2389. });
  2390. }
  2391. private void on_undo(GLib.SimpleAction action, GLib.Variant? param)
  2392. {
  2393. int id = _database.undo();
  2394. if (id != -1) {
  2395. _statusbar.set_temporary_message("Undo: " + ActionNames[id]);
  2396. update_active_window_title();
  2397. }
  2398. }
  2399. private void on_redo(GLib.SimpleAction action, GLib.Variant? param)
  2400. {
  2401. int id = _database.redo();
  2402. if (id != -1) {
  2403. _statusbar.set_temporary_message("Redo: " + ActionNames[id]);
  2404. update_active_window_title();
  2405. }
  2406. }
  2407. private void on_duplicate(GLib.SimpleAction action, GLib.Variant? param)
  2408. {
  2409. _level.duplicate_selected_objects();
  2410. _editor.send(DeviceApi.frame());
  2411. }
  2412. private void on_delete(GLib.SimpleAction action, GLib.Variant? param)
  2413. {
  2414. _level.destroy_selected_objects();
  2415. _editor.send(DeviceApi.frame());
  2416. }
  2417. private void on_manual(GLib.SimpleAction action, GLib.Variant? param)
  2418. {
  2419. try {
  2420. AppInfo.launch_default_for_uri(CROWN_LATEST_DOCS_URL, null);
  2421. } catch (Error e) {
  2422. loge(e.message);
  2423. }
  2424. }
  2425. private void on_report_issue(GLib.SimpleAction action, GLib.Variant? param)
  2426. {
  2427. try {
  2428. AppInfo.launch_default_for_uri("https://github.com/crownengine/crown/issues", null);
  2429. } catch (Error e) {
  2430. loge(e.message);
  2431. }
  2432. }
  2433. private void on_browse_logs(GLib.SimpleAction action, GLib.Variant? param)
  2434. {
  2435. open_directory(_logs_dir.get_path());
  2436. }
  2437. private void on_changelog(GLib.SimpleAction action, GLib.Variant? param)
  2438. {
  2439. try {
  2440. AppInfo.launch_default_for_uri(CROWN_LATEST_CHANGELOG_URL, null);
  2441. } catch (Error e) {
  2442. loge(e.message);
  2443. }
  2444. }
  2445. private void on_donate(GLib.SimpleAction action, GLib.Variant? param)
  2446. {
  2447. try {
  2448. AppInfo.launch_default_for_uri(CROWN_FUND_URL, null);
  2449. } catch (Error e) {
  2450. loge(e.message);
  2451. }
  2452. }
  2453. private void on_about(GLib.SimpleAction action, GLib.Variant? param)
  2454. {
  2455. Gtk.AboutDialog dlg = new Gtk.AboutDialog();
  2456. dlg.set_destroy_with_parent(true);
  2457. dlg.set_transient_for(this.active_window);
  2458. dlg.set_modal(true);
  2459. dlg.set_logo_icon_name(CROWN_EDITOR_ICON_NAME);
  2460. dlg.program_name = CROWN_EDITOR_NAME;
  2461. dlg.version = CROWN_VERSION;
  2462. dlg.website = CROWN_WWW_URL;
  2463. dlg.copyright = "Copyright (c) 2012-2025 Daniele Bartolini et al.";
  2464. dlg.license_type = GPL_3_0;
  2465. dlg.authors =
  2466. {
  2467. "Daniele Bartolini",
  2468. "Simone Boscaratto",
  2469. "Michele Rossi",
  2470. "Raphael de Vasconcelos Nascimento"
  2471. };
  2472. dlg.artists =
  2473. {
  2474. "Michela Iacchelli - Pepper logo",
  2475. "Giulia Gazzoli - Crown logo"
  2476. };
  2477. dlg.run();
  2478. dlg.destroy();
  2479. }
  2480. private void on_delete_file(GLib.SimpleAction action, GLib.Variant? param)
  2481. {
  2482. if (param == null)
  2483. return;
  2484. string resource_path = param.get_string();
  2485. string? resource_type = ResourceId.type(resource_path);
  2486. string? resource_name = ResourceId.name(resource_path);
  2487. bool do_delete = true;
  2488. if (resource_type != null && resource_name != null) {
  2489. if (resource_name == _level._name) {
  2490. int rt = ResponseType.YES;
  2491. if (_database.changed())
  2492. rt = run_level_changed_dialog(this.active_window);
  2493. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  2494. new_level();
  2495. send_state();
  2496. _editor.send(DeviceApi.frame());
  2497. } else {
  2498. do_delete = false;
  2499. }
  2500. }
  2501. }
  2502. if (do_delete) {
  2503. string path = _project.absolute_path(resource_path);
  2504. try {
  2505. GLib.File.new_for_path(path).delete();
  2506. } catch (Error e) {
  2507. loge(e.message);
  2508. }
  2509. }
  2510. }
  2511. private void on_delete_directory(GLib.SimpleAction action, GLib.Variant? param)
  2512. {
  2513. string dir_name = param.get_string();
  2514. var path = _project.absolute_path(dir_name);
  2515. try {
  2516. _project.delete_tree(GLib.File.new_for_path(path));
  2517. } catch (Error e) {
  2518. loge(e.message);
  2519. }
  2520. }
  2521. private void on_create_directory(GLib.SimpleAction action, GLib.Variant? param)
  2522. {
  2523. string parent_dir_name = (string)param.get_child_value(0);
  2524. string dir_name = (string)param.get_child_value(1);
  2525. var path = _project.absolute_path(GLib.Path.build_filename(parent_dir_name, dir_name));
  2526. try {
  2527. GLib.File.new_for_path(path).make_directory();
  2528. } catch (Error e) {
  2529. loge(e.message);
  2530. }
  2531. }
  2532. private void on_create_script(GLib.SimpleAction action, GLib.Variant? param)
  2533. {
  2534. string dir_name = (string)param.get_child_value(0);
  2535. string script_name = (string)param.get_child_value(1);
  2536. bool empty = (bool)param.get_child_value(2);
  2537. int ec = _project.create_script(dir_name, script_name, empty);
  2538. if (ec < 0) {
  2539. loge("Failed to create script %s".printf(script_name));
  2540. return;
  2541. }
  2542. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  2543. _data_compiler.compile.end(res);
  2544. });
  2545. }
  2546. private void on_create_unit(GLib.SimpleAction action, GLib.Variant? param)
  2547. {
  2548. string dir_name = (string)param.get_child_value(0);
  2549. string unit_name = (string)param.get_child_value(1);
  2550. int ec = _project.create_unit(dir_name, unit_name);
  2551. if (ec < 0) {
  2552. loge("Failed to create unit %s".printf(unit_name));
  2553. return;
  2554. }
  2555. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  2556. _data_compiler.compile.end(res);
  2557. });
  2558. }
  2559. private void on_open_containing(GLib.SimpleAction action, GLib.Variant? param)
  2560. {
  2561. string path = param.get_string();
  2562. GLib.File abs_path = GLib.File.new_for_path(_project.absolute_path(path));
  2563. GLib.File? abs_parent = abs_path.get_parent();
  2564. string abs_parent_path = abs_parent != null
  2565. ? abs_parent.get_path()
  2566. : abs_path.get_path()
  2567. ;
  2568. open_directory(abs_parent_path);
  2569. }
  2570. public void delete_tree(GLib.File file) throws Error
  2571. {
  2572. GLib.FileEnumerator fe = file.enumerate_children("standard::*"
  2573. , GLib.FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  2574. );
  2575. GLib.FileInfo info = null;
  2576. while ((info = fe.next_file()) != null) {
  2577. GLib.File subfile = file.resolve_relative_path(info.get_name());
  2578. if (info.get_file_type() == GLib.FileType.DIRECTORY)
  2579. delete_tree(subfile);
  2580. else
  2581. subfile.delete();
  2582. }
  2583. file.delete();
  2584. }
  2585. private int deploy_create_package_folder(out string config_path, out string package_path, string output_path, string app_identifier, TargetPlatform platform, TargetArch arch, TargetConfig config)
  2586. {
  2587. string platform_name[] =
  2588. {
  2589. "android", // TargetArch.ANDROID
  2590. "html5", // TargetArch.HTML5
  2591. "linux", // TargetArch.LINUX
  2592. "windows" // TargetArch.WINDOWS
  2593. };
  2594. string arch_name[] =
  2595. {
  2596. "x86", // TargetArch.X86
  2597. "x64", // TargetArch.X64
  2598. "arm", // TargetArch.ARM
  2599. "arm64", // TargetArch.ARM64
  2600. "wasm" // TargetArch.WASM
  2601. };
  2602. string config_name[] =
  2603. {
  2604. "release", // TargetConfig.RELEASE
  2605. "development" // TargetConfig.DEVELOPMENT
  2606. };
  2607. string platform_path = Path.build_path(Path.DIR_SEPARATOR_S, output_path, platform_name[platform], arch_name[arch]);
  2608. config_path = Path.build_path(Path.DIR_SEPARATOR_S, platform_path, config_name[config]);
  2609. package_path = Path.build_path(Path.DIR_SEPARATOR_S, config_path, app_identifier);
  2610. try {
  2611. int rt = ResponseType.CANCEL;
  2612. if (GLib.File.new_for_path(package_path).query_exists()) {
  2613. Gtk.MessageDialog md = new Gtk.MessageDialog(_deploy_dialog
  2614. , DialogFlags.MODAL
  2615. , MessageType.QUESTION
  2616. , Gtk.ButtonsType.NONE
  2617. , "A file named `%s` already exists.\nOverwrite?".printf(package_path)
  2618. );
  2619. Gtk.Widget btn;
  2620. md.add_button("_No", ResponseType.NO);
  2621. btn = md.add_button("_Yes", ResponseType.YES);
  2622. btn.get_style_context().add_class(Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION);
  2623. md.set_default_response(ResponseType.NO);
  2624. rt = md.run();
  2625. md.destroy();
  2626. if (rt == ResponseType.YES)
  2627. delete_tree(GLib.File.new_for_path(package_path));
  2628. else
  2629. return -1;
  2630. }
  2631. GLib.File.new_for_path(package_path).make_directory_with_parents();
  2632. } catch (Error e) {
  2633. loge(e.message);
  2634. return -1;
  2635. }
  2636. return 0;
  2637. }
  2638. private void on_create_package_android(GLib.SimpleAction action, GLib.Variant? param)
  2639. {
  2640. string config_name[] =
  2641. {
  2642. "release",
  2643. "development"
  2644. };
  2645. var output_path = (string)param.get_child_value(0);
  2646. var config = (int)param.get_child_value(1);
  2647. var app_title = (string)param.get_child_value(2);
  2648. var app_identifier = (string)param.get_child_value(3);
  2649. var app_version_code = (int)param.get_child_value(4);
  2650. var app_version_name = (string)param.get_child_value(5);
  2651. var keystore_path = (string)param.get_child_value(6);
  2652. var keystore_pass = (string)param.get_child_value(7);
  2653. var key_alias = (string)param.get_child_value(8);
  2654. var key_pass = (string)param.get_child_value(9);
  2655. var arch = (int)param.get_child_value(10);
  2656. var apk_name = app_identifier + "-" + app_version_name;
  2657. var activity_name = "MainActivity";
  2658. string? android_sdk_path = GLib.Environment.get_variable("ANDROID_SDK_PATH");
  2659. if (android_sdk_path == null) {
  2660. loge("Please set a valid ANDROID_SDK_PATH environment variable.");
  2661. return;
  2662. }
  2663. string? android_ndk_root_path = GLib.Environment.get_variable("ANDROID_NDK_ROOT");
  2664. if (android_ndk_root_path == null) {
  2665. loge("Please set a valid ANDROID_NDK_ROOT environment variable.");
  2666. return;
  2667. }
  2668. string config_path;
  2669. string package_path;
  2670. int err = deploy_create_package_folder(out config_path
  2671. , out package_path
  2672. , output_path
  2673. , apk_name
  2674. , TargetPlatform.ANDROID
  2675. , arch
  2676. , (TargetConfig)config
  2677. );
  2678. if (err != 0)
  2679. return;
  2680. logi("Creating Android package (%s)...".printf(arch == TargetArch.ARM ? "ARMv7-A" : "ARMv8-A"));
  2681. // Architecture-agnostic paths.
  2682. var manifests_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "manifests");
  2683. var java_sources_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "java");
  2684. var app_sources_path = Path.build_path(Path.DIR_SEPARATOR_S, java_sources_path, app_identifier.replace(".", "/"));
  2685. var assets_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "assets");
  2686. var res_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "res");
  2687. var bin_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "bin");
  2688. var obj_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "obj");
  2689. var res_layout_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "layout");
  2690. var res_values_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "values");
  2691. var res_drawable_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "drawable");
  2692. var manifest_xml_path = Path.build_path(Path.DIR_SEPARATOR_S, manifests_path, "AndroidManifest.xml");
  2693. var strings_xml_path = Path.build_path(Path.DIR_SEPARATOR_S, res_path, "values", "strings.xml");
  2694. var activity_java_path = Path.build_path(Path.DIR_SEPARATOR_S, app_sources_path, "%s.java".printf(activity_name));
  2695. var android_jar_path = Path.build_path(Path.DIR_SEPARATOR_S, android_sdk_path, "platforms", "android-24", "android.jar");
  2696. var libcrown_src_name = "libcrown-" + config_name[config] + ".so";
  2697. var libcpp_name = "libc++_shared.so";
  2698. var signed_apk = Path.build_path(Path.DIR_SEPARATOR_S, bin_path, apk_name + ".signed.apk");
  2699. var unaligned_apk = Path.build_path(Path.DIR_SEPARATOR_S, bin_path, apk_name + ".unaligned.apk");
  2700. var final_apk = Path.build_path(Path.DIR_SEPARATOR_S, config_path, apk_name + ".apk");
  2701. var classes_dex_path = Path.build_path(Path.DIR_SEPARATOR_S, bin_path, "classes.dex");
  2702. // Architecture-specific paths.
  2703. string dc_platform = null;
  2704. string bin_folder = null;
  2705. string apk_arch = null;
  2706. if (arch == TargetArch.ARM) {
  2707. dc_platform = "android";
  2708. bin_folder = "android-arm";
  2709. apk_arch = "armeabi-v7a";
  2710. } else if (arch == TargetArch.ARM64) {
  2711. dc_platform = "android-arm64";
  2712. bin_folder = "android-arm64";
  2713. apk_arch = "arm64-v8a";
  2714. } else {
  2715. loge("Invalid architecture");
  2716. return;
  2717. }
  2718. var libcrown_src_path = Path.build_path(Path.DIR_SEPARATOR_S, "..", "..", bin_folder, "bin", libcrown_src_name);
  2719. var libcpp_src_path = Path.build_path(Path.DIR_SEPARATOR_S, android_ndk_root_path, "sources", "cxx-stl", "llvm-libc++", "libs", apk_arch, libcpp_name);
  2720. var lib_path_relative = Path.build_path(Path.DIR_SEPARATOR_S, "lib", apk_arch);
  2721. var lib_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, lib_path_relative);
  2722. var libcrown_path_relative = Path.build_path(Path.DIR_SEPARATOR_S, lib_path_relative, "libcrown.so");
  2723. var libcpp_path_relative = Path.build_path(Path.DIR_SEPARATOR_S, lib_path_relative, libcpp_name);
  2724. var libcrown_dst_path = Path.build_path(Path.DIR_SEPARATOR_S, lib_path, "libcrown.so");
  2725. var libcpp_dst_path = Path.build_path(Path.DIR_SEPARATOR_S, lib_path, "libc++_shared.so");
  2726. // Create Android project skeleton.
  2727. try {
  2728. GLib.File.new_for_path(manifests_path).make_directory();
  2729. GLib.File.new_for_path(app_sources_path).make_directory_with_parents();
  2730. GLib.File.new_for_path(lib_path).make_directory_with_parents();
  2731. GLib.File.new_for_path(assets_path).make_directory();
  2732. GLib.File.new_for_path(bin_path).make_directory();
  2733. GLib.File.new_for_path(obj_path).make_directory();
  2734. GLib.File.new_for_path(res_layout_path).make_directory_with_parents();
  2735. GLib.File.new_for_path(res_values_path).make_directory();
  2736. GLib.File.new_for_path(res_drawable_path).make_directory();
  2737. } catch (Error e) {
  2738. loge(e.message);
  2739. }
  2740. // Compile game data.
  2741. try {
  2742. GLib.File.new_for_path(libcrown_src_path).copy(GLib.File.new_for_path(libcrown_dst_path), GLib.FileCopyFlags.NONE);
  2743. GLib.File.new_for_path(libcpp_src_path).copy(GLib.File.new_for_path(libcpp_dst_path), GLib.FileCopyFlags.NONE);
  2744. string[] args;
  2745. string tmp_data_dir = GLib.DirUtils.make_tmp("XXXXXX");
  2746. // Populate Android assets folder with data.
  2747. args = new string[]
  2748. {
  2749. ENGINE_EXE,
  2750. "--source-dir",
  2751. _project.source_dir(),
  2752. "--map-source-dir",
  2753. "core",
  2754. _project.toolchain_dir(),
  2755. "--data-dir",
  2756. tmp_data_dir,
  2757. "--bundle-dir",
  2758. assets_path,
  2759. "--compile",
  2760. "--bundle",
  2761. "--platform",
  2762. dc_platform
  2763. };
  2764. uint32 pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  2765. int exit_status = _subprocess_launcher.wait(pid);
  2766. delete_tree(GLib.File.new_for_path(tmp_data_dir));
  2767. if (exit_status != 0) {
  2768. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  2769. return;
  2770. }
  2771. } catch (Error e) {
  2772. loge(e.message);
  2773. return;
  2774. }
  2775. // Create Android manifest.
  2776. string android_manifest = "";
  2777. android_manifest += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
  2778. android_manifest += "\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"";
  2779. android_manifest += "\n package=\"%s\"".printf(app_identifier);
  2780. android_manifest += "\n android:versionCode=\"%u\"".printf(app_version_code);
  2781. android_manifest += "\n android:versionName=\"%s\">".printf(app_version_name);
  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 private 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 private 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. "javac",
  2903. "-verbose",
  2904. "-source",
  2905. "1.7",
  2906. "-target",
  2907. "1.7",
  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. "dx",
  2952. "--dex",
  2953. "--output",
  2954. classes_dex_path,
  2955. obj_path
  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. "aapt",
  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. "aapt",
  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. "aapt",
  3002. "add",
  3003. unaligned_apk,
  3004. libcrown_path_relative,
  3005. libcpp_path_relative
  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. "jarsigner",
  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. "zipalign",
  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(package_path));
  3053. return 0;
  3054. });
  3055. }
  3056. private void on_create_package_html5(GLib.SimpleAction action, GLib.Variant? param)
  3057. {
  3058. string config_name[] =
  3059. {
  3060. "release",
  3061. "development"
  3062. };
  3063. var output_path = (string)param.get_child_value(0);
  3064. var config = (int)param.get_child_value(1);
  3065. var app_title = (string)param.get_child_value(2);
  3066. var exe_name = app_title.replace(" ", "_").down();
  3067. string config_path;
  3068. string package_path;
  3069. int err = deploy_create_package_folder(out config_path
  3070. , out package_path
  3071. , output_path
  3072. , exe_name
  3073. , TargetPlatform.HTML5
  3074. , TargetArch.WASM
  3075. , (TargetConfig)config
  3076. );
  3077. if (err != 0)
  3078. return;
  3079. logi("Creating HTML5 package...");
  3080. // Create data bundle.
  3081. try {
  3082. string[] args;
  3083. string tmp_data_dir = GLib.DirUtils.make_tmp("XXXXXX");
  3084. string tmp_bundle_dir = GLib.DirUtils.make_tmp("XXXXXX");
  3085. args = new string[]
  3086. {
  3087. ENGINE_EXE,
  3088. "--source-dir",
  3089. _project.source_dir(),
  3090. "--map-source-dir",
  3091. "core",
  3092. _project.toolchain_dir(),
  3093. "--data-dir",
  3094. tmp_data_dir,
  3095. "--bundle-dir",
  3096. tmp_bundle_dir,
  3097. "--compile",
  3098. "--bundle",
  3099. "--platform",
  3100. "html5"
  3101. };
  3102. var pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3103. var exit_status = _subprocess_launcher.wait(pid);
  3104. delete_tree(GLib.File.new_for_path(tmp_data_dir));
  3105. if (exit_status != 0) {
  3106. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  3107. return;
  3108. }
  3109. // Copy runtime executables to package folder.
  3110. var runtime_name_src = "crown-%s".printf(config_name[config]);
  3111. var runtime_path_src = Path.build_path(Path.DIR_SEPARATOR_S, "..", "..", "wasm", "bin", runtime_name_src);
  3112. var runtime_name_dst = Path.build_filename(package_path, runtime_name_src);
  3113. var src = File.new_for_path(runtime_path_src + ".js");
  3114. var dst = File.new_for_path(runtime_name_dst + ".js");
  3115. src.copy(dst, FileCopyFlags.OVERWRITE);
  3116. src = File.new_for_path(runtime_path_src + ".worker.js");
  3117. dst = File.new_for_path(runtime_name_dst + ".worker.js");
  3118. src.copy(dst, FileCopyFlags.OVERWRITE);
  3119. src = File.new_for_path(runtime_path_src + ".wasm");
  3120. dst = File.new_for_path(runtime_name_dst + ".wasm");
  3121. src.copy(dst, FileCopyFlags.OVERWRITE);
  3122. // Package bundle data with emscripten's file_packager.
  3123. args = new string[]
  3124. {
  3125. "file_packager",
  3126. Path.build_path(Path.DIR_SEPARATOR_S, package_path, "data.bin"),
  3127. "--preload",
  3128. "./data",
  3129. "--js-output=" + Path.build_path(Path.DIR_SEPARATOR_S, package_path, "data.js")
  3130. };
  3131. pid = _subprocess_launcher.spawnv_async(subprocess_flags(), args, tmp_bundle_dir);
  3132. exit_status = _subprocess_launcher.wait(pid);
  3133. delete_tree(GLib.File.new_for_path(tmp_bundle_dir));
  3134. if (exit_status != 0) {
  3135. loge("Failed to package data.js. exit_status %d".printf(exit_status));
  3136. return;
  3137. }
  3138. // Generate index.html.
  3139. var index_html_path = Path.build_path(Path.DIR_SEPARATOR_S, package_path, "index.html");
  3140. string index_html = "";
  3141. index_html += "\n<!doctype html>";
  3142. index_html += "\n<html lang=\"en-us\">";
  3143. index_html += "\n<head>";
  3144. index_html += "\n<meta charset=\"utf-8\">";
  3145. index_html += "\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
  3146. index_html += "\n<style>";
  3147. index_html += "\n body {";
  3148. index_html += "\n margin: 0px;";
  3149. index_html += "\n background-color: black;";
  3150. index_html += "\n }";
  3151. index_html += "\n .app {";
  3152. index_html += "\n display: block;";
  3153. index_html += "\n border: 0px;";
  3154. index_html += "\n margin: 0px;";
  3155. index_html += "\n position: absolute;";
  3156. index_html += "\n top: 0;";
  3157. index_html += "\n left: 0;";
  3158. index_html += "\n width: 100%;";
  3159. index_html += "\n height: 100%;";
  3160. index_html += "\n background-color: black;";
  3161. index_html += "\n }";
  3162. index_html += "\n</style>";
  3163. index_html += "\n</head>";
  3164. index_html += "\n<body>";
  3165. index_html += "\n<canvas class=\"app\" id=\"canvas\" oncontextmenu=\"event.preventDefault()\" tabindex=-1></canvas>";
  3166. index_html += "\n<script type='text/javascript'>";
  3167. index_html += "\n var Module = {";
  3168. index_html += "\n preRun: [],";
  3169. index_html += "\n postRun: [],";
  3170. index_html += "\n canvas: (() => {";
  3171. index_html += "\n var canvas = document.getElementById('canvas');";
  3172. index_html += "\n canvas.addEventListener(\"webglcontextlost\", (e) => {";
  3173. index_html += "\n alert('WebGL context lost. You will need to reload the page.');";
  3174. index_html += "\n e.preventDefault();";
  3175. index_html += "\n }, false);";
  3176. index_html += "\n return canvas;";
  3177. index_html += "\n })(),";
  3178. index_html += "\n setStatus: (text) => { },";
  3179. index_html += "\n monitorRunDependencies: (left) => { }";
  3180. index_html += "\n };";
  3181. index_html += "\n window.onerror = (event) => {";
  3182. index_html += "\n console.error('onerror: ' + event.message);";
  3183. index_html += "\n };";
  3184. index_html += "\n</script>";
  3185. index_html += "\n<script async type=\"text/javascript\" src=\"data.js\"></script>";
  3186. index_html += "\n<script async type=\"text/javascript\" src=\"%s.js\"></script>".printf(runtime_name_src);
  3187. index_html += "\n</body>";
  3188. index_html += "\n</html>";
  3189. index_html += "\n";
  3190. GLib.FileStream? fs = FileStream.open(index_html_path, "w");
  3191. if (fs == null) {
  3192. loge("Failed to open '%s'".printf(index_html_path));
  3193. return;
  3194. }
  3195. fs.write(index_html.data);
  3196. } catch (Error e) {
  3197. loge(e.message);
  3198. loge("Failed to deploy '%s'".printf(app_title));
  3199. return;
  3200. }
  3201. logi("Done: #FILE(%s)".printf(package_path));
  3202. }
  3203. private void on_create_package_linux(GLib.SimpleAction action, GLib.Variant? param)
  3204. {
  3205. string config_name[] =
  3206. {
  3207. "release",
  3208. "development"
  3209. };
  3210. var output_path = (string)param.get_child_value(0);
  3211. var config = (int)param.get_child_value(1);
  3212. var app_title = (string)param.get_child_value(2);
  3213. var exe_name = app_title.replace(" ", "_").down();
  3214. string config_path;
  3215. string package_path;
  3216. int err = deploy_create_package_folder(out config_path
  3217. , out package_path
  3218. , output_path
  3219. , exe_name
  3220. , TargetPlatform.LINUX
  3221. , TargetArch.X64
  3222. , (TargetConfig)config
  3223. );
  3224. if (err != 0)
  3225. return;
  3226. logi("Creating Linux package...");
  3227. // Create data bundle.
  3228. try {
  3229. string tmp_data_dir = GLib.DirUtils.make_tmp("XXXXXX");
  3230. string args[] =
  3231. {
  3232. ENGINE_EXE,
  3233. "--source-dir",
  3234. _project.source_dir(),
  3235. "--map-source-dir",
  3236. "core",
  3237. _project.toolchain_dir(),
  3238. "--data-dir",
  3239. tmp_data_dir,
  3240. "--bundle-dir",
  3241. package_path,
  3242. "--compile",
  3243. "--bundle",
  3244. "--platform",
  3245. "linux"
  3246. };
  3247. uint32 compiler = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3248. int exit_status = _subprocess_launcher.wait(compiler);
  3249. delete_tree(GLib.File.new_for_path(tmp_data_dir));
  3250. if (exit_status != 0) {
  3251. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  3252. return;
  3253. }
  3254. GLib.File engine_exe_src = File.new_for_path(EXE_PREFIX + "crown-%s".printf(config_name[config]) + EXE_SUFFIX);
  3255. GLib.File engine_exe_dst = File.new_for_path(Path.build_filename(package_path, exe_name + EXE_SUFFIX));
  3256. engine_exe_src.copy(engine_exe_dst, FileCopyFlags.OVERWRITE);
  3257. } catch (Error e) {
  3258. loge(e.message);
  3259. loge("Failed to deploy '%s'".printf(app_title));
  3260. return;
  3261. }
  3262. logi("Done: #FILE(%s)".printf(package_path));
  3263. }
  3264. private void on_create_package_windows(GLib.SimpleAction action, GLib.Variant? param)
  3265. {
  3266. string config_name[] =
  3267. {
  3268. "release",
  3269. "development"
  3270. };
  3271. var output_path = (string)param.get_child_value(0);
  3272. var config = (int)param.get_child_value(1);
  3273. var app_title = (string)param.get_child_value(2);
  3274. var exe_name = app_title.replace(" ", "_").down();
  3275. string config_path;
  3276. string package_path;
  3277. int err = deploy_create_package_folder(out config_path
  3278. , out package_path
  3279. , output_path
  3280. , exe_name
  3281. , TargetPlatform.WINDOWS
  3282. , TargetArch.X64
  3283. , (TargetConfig)config
  3284. );
  3285. if (err != 0)
  3286. return;
  3287. logi("Creating Windows package");
  3288. // Create data bundle.
  3289. try {
  3290. string tmp_data_dir = GLib.DirUtils.make_tmp("XXXXXX");
  3291. string args[] =
  3292. {
  3293. ENGINE_EXE,
  3294. "--source-dir",
  3295. _project.source_dir(),
  3296. "--map-source-dir",
  3297. "core",
  3298. _project.toolchain_dir(),
  3299. "--data-dir",
  3300. tmp_data_dir,
  3301. "--bundle-dir",
  3302. package_path,
  3303. "--compile",
  3304. "--bundle",
  3305. "--platform",
  3306. "windows"
  3307. };
  3308. uint32 compiler = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  3309. int exit_status = _subprocess_launcher.wait(compiler);
  3310. delete_tree(GLib.File.new_for_path(tmp_data_dir));
  3311. if (exit_status != 0) {
  3312. loge("Failed to compile data. exit_status = %d".printf(exit_status));
  3313. return;
  3314. }
  3315. GLib.File engine_exe_src = File.new_for_path(EXE_PREFIX + "crown-%s".printf(config_name[config]) + EXE_SUFFIX);
  3316. GLib.File engine_exe_dst = File.new_for_path(Path.build_filename(package_path, exe_name + EXE_SUFFIX));
  3317. engine_exe_src.copy(engine_exe_dst, FileCopyFlags.OVERWRITE);
  3318. string openal_name = "openal-release.dll";
  3319. GLib.File openal_dll_src = File.new_for_path(openal_name);
  3320. GLib.File openal_dll_dst = File.new_for_path(Path.build_filename(package_path, openal_name));
  3321. openal_dll_src.copy(openal_dll_dst, FileCopyFlags.OVERWRITE);
  3322. string lua_name = "lua51.dll";
  3323. GLib.File lua_dll_src = File.new_for_path(lua_name);
  3324. GLib.File lua_dll_dst = File.new_for_path(Path.build_filename(package_path, lua_name));
  3325. lua_dll_src.copy(lua_dll_dst, FileCopyFlags.OVERWRITE);
  3326. } catch (Error e) {
  3327. loge("%s".printf(e.message));
  3328. loge("Failed to deploy '%s'".printf(app_title));
  3329. return;
  3330. }
  3331. logi("Done: #FILE(%s)".printf(package_path));
  3332. }
  3333. private void on_unit_add_component(GLib.SimpleAction action, GLib.Variant? param)
  3334. {
  3335. if (param == null)
  3336. return;
  3337. string component_type = param.get_string();
  3338. Guid unit_id = _level._selection.last();
  3339. Unit unit = Unit(_database, unit_id);
  3340. ArrayList<Guid?> components_added = new ArrayList<Guid?>();
  3341. components_added.add(unit_id);
  3342. unit.add_component_type_dependencies(ref components_added, component_type);
  3343. _database.add_restore_point((int)ActionType.UNIT_ADD_COMPONENT, components_added.to_array());
  3344. }
  3345. private void on_unit_remove_component(GLib.SimpleAction action, GLib.Variant? param)
  3346. {
  3347. if (param == null)
  3348. return;
  3349. string component_type = param.get_string();
  3350. Guid unit_id = _level._selection.last();
  3351. Unit unit = Unit(_database, unit_id);
  3352. Guid component_id;
  3353. if (!unit.has_component(out component_id, component_type))
  3354. return;
  3355. Gee.ArrayList<unowned string> dependents = new Gee.ArrayList<unowned string>();
  3356. // Do not remove if any other component needs us.
  3357. foreach (var entry in Unit._component_registry.entries) {
  3358. Guid dummy;
  3359. if (!unit.has_component(out dummy, entry.key))
  3360. continue;
  3361. string[] component_type_dependencies = ((string)entry.value).split(", ");
  3362. if (component_type in component_type_dependencies)
  3363. dependents.add(entry.key);
  3364. }
  3365. if (dependents.size > 0) {
  3366. StringBuilder sb = new StringBuilder();
  3367. sb.append("Cannot remove %s due to the following dependencies:\n\n".printf(component_type));
  3368. foreach (var item in dependents)
  3369. sb.append("• %s\n".printf(item));
  3370. Gtk.MessageDialog md = new Gtk.MessageDialog(this.active_window
  3371. , DialogFlags.MODAL
  3372. , MessageType.WARNING
  3373. , Gtk.ButtonsType.OK
  3374. , sb.str
  3375. );
  3376. md.set_default_response(ResponseType.OK);
  3377. md.run();
  3378. md.destroy();
  3379. return;
  3380. } else {
  3381. unit.remove_component_type(component_type);
  3382. }
  3383. }
  3384. public void set_autosave_timer(uint minutes)
  3385. {
  3386. if (_save_timer_id > 0)
  3387. GLib.Source.remove(_save_timer_id);
  3388. _save_timer_id = GLib.Timeout.add_seconds(minutes*60, save_timeout);
  3389. }
  3390. public void menu_set_enabled(bool enabled, GLib.ActionEntry[] entries, string[]? whitelist = null)
  3391. {
  3392. for (int ii = 0; ii < entries.length; ++ii) {
  3393. string action_name = entries[ii].name;
  3394. int jj = 0;
  3395. if (whitelist != null) {
  3396. for (; jj < whitelist.length; ++jj) {
  3397. if (action_name == whitelist[jj])
  3398. break;
  3399. }
  3400. }
  3401. if (whitelist == null || whitelist != null && jj == whitelist.length) {
  3402. GLib.SimpleAction sa = this.lookup_action(action_name) as GLib.SimpleAction;
  3403. if (sa != null)
  3404. sa.set_enabled(enabled);
  3405. }
  3406. }
  3407. }
  3408. private void set_conflicting_accels(bool on)
  3409. {
  3410. if (on) {
  3411. this.set_accels_for_action("app.tool(0)", _tool_place_accels);
  3412. this.set_accels_for_action("app.tool(1)", _tool_move_accels);
  3413. this.set_accels_for_action("app.tool(2)", _tool_rotate_accels);
  3414. this.set_accels_for_action("app.tool(3)", _tool_scale_accels);
  3415. this.set_accels_for_action("app.delete", _delete_accels);
  3416. this.set_accels_for_action("app.camera-view(0)", _camera_view_perspective_accels);
  3417. this.set_accels_for_action("app.camera-view(1)", _camera_view_front_accels);
  3418. this.set_accels_for_action("app.camera-view(2)", _camera_view_back_accels);
  3419. this.set_accels_for_action("app.camera-view(3)", _camera_view_right_accels);
  3420. this.set_accels_for_action("app.camera-view(4)", _camera_view_left_accels);
  3421. this.set_accels_for_action("app.camera-view(5)", _camera_view_top_accels);
  3422. this.set_accels_for_action("app.camera-view(6)", _camera_view_bottom_accels);
  3423. this.set_accels_for_action("app.camera-frame-selected", _camera_frame_selected_accels);
  3424. this.set_accels_for_action("app.camera-frame-all", _camera_frame_all_accels);
  3425. } else {
  3426. this.set_accels_for_action("app.tool(0)", {});
  3427. this.set_accels_for_action("app.tool(1)", {});
  3428. this.set_accels_for_action("app.tool(2)", {});
  3429. this.set_accels_for_action("app.tool(3)", {});
  3430. this.set_accels_for_action("app.delete", {});
  3431. this.set_accels_for_action("app.camera-view(0)", {});
  3432. this.set_accels_for_action("app.camera-view(1)", {});
  3433. this.set_accels_for_action("app.camera-view(2)", {});
  3434. this.set_accels_for_action("app.camera-view(3)", {});
  3435. this.set_accels_for_action("app.camera-view(4)", {});
  3436. this.set_accels_for_action("app.camera-view(5)", {});
  3437. this.set_accels_for_action("app.camera-view(6)", {});
  3438. this.set_accels_for_action("app.camera-frame-selected", {});
  3439. this.set_accels_for_action("app.camera-frame-all", {});
  3440. }
  3441. }
  3442. public void entry_any_focus_in(Gtk.Widget widget)
  3443. {
  3444. set_conflicting_accels(false);
  3445. }
  3446. public void entry_any_focus_out(Gtk.Widget widget)
  3447. {
  3448. set_conflicting_accels(true);
  3449. }
  3450. public void show_panel(string name, Gtk.StackTransitionType stt = Gtk.StackTransitionType.NONE)
  3451. {
  3452. _main_stack.set_visible_child_full(name, stt);
  3453. if (name == "main_vbox") {
  3454. // FIXME: save/restore last known window state
  3455. int win_w;
  3456. int win_h;
  3457. this.active_window.get_size(out win_w, out win_h);
  3458. _editor_pane.set_position(320);
  3459. _content_pane.set_position(win_h - 250);
  3460. _inspector_pane.set_position(win_h - 600);
  3461. _main_pane.set_position(win_w - 375);
  3462. menu_set_enabled(true, action_entries_file);
  3463. menu_set_enabled(true, action_entries_edit);
  3464. menu_set_enabled(true, action_entries_create);
  3465. menu_set_enabled(true, action_entries_camera);
  3466. menu_set_enabled(true, action_entries_view);
  3467. menu_set_enabled(true, action_entries_debug);
  3468. menu_set_enabled(true, action_entries_help);
  3469. } else if (name == "panel_welcome"
  3470. || name == "panel_new_project"
  3471. || name == "panel_projects_list"
  3472. ) {
  3473. menu_set_enabled(false, action_entries_file, {"new-project", "add-project", "open-project", "quit"});
  3474. menu_set_enabled(false, action_entries_edit);
  3475. menu_set_enabled(false, action_entries_create);
  3476. menu_set_enabled(false, action_entries_camera);
  3477. menu_set_enabled(false, action_entries_view);
  3478. menu_set_enabled(false, action_entries_debug);
  3479. menu_set_enabled(true, action_entries_help);
  3480. }
  3481. }
  3482. private void on_set_placeable(GLib.SimpleAction action, GLib.Variant? param)
  3483. {
  3484. _placeable_type = (string)param.get_child_value(0);
  3485. _placeable_name = (string)param.get_child_value(1);
  3486. _editor.send_script(LevelEditorApi.set_placeable(_placeable_type, _placeable_name));
  3487. activate_action("tool", new GLib.Variant.int32(ToolType.PLACE));
  3488. }
  3489. private void on_project_reset()
  3490. {
  3491. if (!_project.is_loaded())
  3492. return;
  3493. // Save per-project data.
  3494. try {
  3495. string path = GLib.Path.build_filename(_project.user_dir(), "project_store.sjson");
  3496. SJSON.save(_project_store.encode(), path);
  3497. } catch (JsonWriteError e) {
  3498. loge(e.message);
  3499. }
  3500. // Destroy dialogs.
  3501. _texture_settings_dialog = null;
  3502. _deploy_dialog = null;
  3503. }
  3504. private void on_project_loaded()
  3505. {
  3506. // Load per-project data.
  3507. try {
  3508. string path = GLib.Path.build_filename(_project.user_dir(), "project_store.sjson");
  3509. _project_store.decode(SJSON.load_from_path(path));
  3510. }
  3511. catch (JsonSyntaxError e) {
  3512. // No-op.
  3513. }
  3514. }
  3515. }
  3516. // Global paths
  3517. public static GLib.File _toolchain_dir;
  3518. public static GLib.File _templates_dir;
  3519. public static GLib.File _data_dir;
  3520. public static GLib.File _config_dir;
  3521. public static GLib.File _cache_dir;
  3522. public static GLib.File _logs_dir;
  3523. public static GLib.File _thumbnails_dir;
  3524. public static GLib.File _thumbnails_normal_dir;
  3525. public static GLib.File _documents_dir;
  3526. public static GLib.File _log_file;
  3527. public static GLib.File _settings_file;
  3528. public static GLib.File _user_file;
  3529. public static GLib.File _console_history_file;
  3530. public static GLib.File _window_state_file;
  3531. public static GLib.FileStream _log_stream;
  3532. public static ConsoleView _console_view;
  3533. public static bool _console_view_valid = false;
  3534. public static string _log_prefix;
  3535. public static void log(string system, string severity, string message)
  3536. {
  3537. GLib.DateTime now = new GLib.DateTime.now_local();
  3538. int now_us = now.get_microsecond();
  3539. string now_str = now.format("%H:%M:%S");
  3540. string plain_text_line = "%s.%06d %.4s %s: %s\n".printf(now_str
  3541. , now_us
  3542. , severity.ascii_up()
  3543. , system
  3544. , message
  3545. );
  3546. if (_log_stream != null) {
  3547. _log_stream.puts(plain_text_line);
  3548. _log_stream.flush();
  3549. }
  3550. if (_console_view_valid) {
  3551. string line = "%s: %s\n".printf(system, message);
  3552. string time = "%s.%06d ".printf(now_str, now_us);
  3553. _console_view.log(time, severity, line);
  3554. }
  3555. }
  3556. public static void logi(string message)
  3557. {
  3558. log(_log_prefix, "info", message);
  3559. }
  3560. public static void logw(string message)
  3561. {
  3562. log(_log_prefix, "warning", message);
  3563. }
  3564. public static void loge(string message)
  3565. {
  3566. log(_log_prefix, "error", message);
  3567. }
  3568. public void open_directory(string directory)
  3569. {
  3570. #if CROWN_PLATFORM_LINUX
  3571. try {
  3572. GLib.AppInfo.launch_default_for_uri("file://" + directory, null);
  3573. } catch (Error e) {
  3574. loge(e.message);
  3575. }
  3576. #else
  3577. GLib.SubprocessLauncher sl = new GLib.SubprocessLauncher(subprocess_flags());
  3578. try {
  3579. sl.spawnv({ "explorer.exe", directory, null });
  3580. } catch (Error e) {
  3581. loge(e.message);
  3582. }
  3583. #endif
  3584. }
  3585. public static GLib.SubprocessFlags subprocess_flags()
  3586. {
  3587. GLib.SubprocessFlags flags = SubprocessFlags.NONE;
  3588. #if !CROWN_DEBUG
  3589. flags |= SubprocessFlags.STDOUT_SILENCE | SubprocessFlags.STDERR_SILENCE;
  3590. #endif
  3591. return flags;
  3592. }
  3593. public static bool is_directory_empty(string path)
  3594. {
  3595. GLib.File file = GLib.File.new_for_path(path);
  3596. try {
  3597. FileEnumerator enumerator = file.enumerate_children("standard::*"
  3598. , FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  3599. );
  3600. return enumerator.next_file() == null;
  3601. } catch (GLib.Error e) {
  3602. loge(e.message);
  3603. }
  3604. return false;
  3605. }
  3606. private void device_frame_delayed(uint delay_ms, RuntimeInstance runtime)
  3607. {
  3608. // FIXME: find a way to time exactly when it is effective to queue a redraw.
  3609. // See: https://blogs.gnome.org/jnelson/2010/10/13/those-realize-map-widget-signals/
  3610. GLib.Timeout.add_full(GLib.Priority.DEFAULT, delay_ms, () => {
  3611. runtime.send(DeviceApi.frame());
  3612. return GLib.Source.REMOVE;
  3613. });
  3614. }
  3615. public static int main(string[] args)
  3616. {
  3617. // If args does not contain --child, spawn the launcher.
  3618. int ii;
  3619. for (ii = 0; ii < args.length; ++ii) {
  3620. if (args[ii] == "--child") {
  3621. break;
  3622. }
  3623. }
  3624. if (ii == args.length) {
  3625. _log_prefix = "launcher";
  3626. } else {
  3627. _log_prefix = "editor";
  3628. // Remove --child from args for backward compatibility.
  3629. if (args.length > 1)
  3630. args = args[0 : args.length - 1];
  3631. }
  3632. // Redirect GLib logs to internal log*().
  3633. GLib.set_print_handler((msg) => { logi(msg); });
  3634. GLib.set_printerr_handler((msg) => { loge(msg); });
  3635. GLib.Log.set_writer_func((log_level, fields) => {
  3636. foreach (var field in fields) {
  3637. if (field.key == "MESSAGE") {
  3638. switch (log_level) {
  3639. case LEVEL_DEBUG:
  3640. #if CROWN_DEBUG
  3641. logi((string)field.value);
  3642. #endif
  3643. break;
  3644. case LEVEL_INFO:
  3645. case LEVEL_MESSAGE:
  3646. logi((string)field.value);
  3647. break;
  3648. case LEVEL_CRITICAL:
  3649. case LEVEL_WARNING:
  3650. logw((string)field.value);
  3651. break;
  3652. case LEVEL_ERROR:
  3653. loge((string)field.value);
  3654. break;
  3655. default:
  3656. logw((string)field.value);
  3657. break;
  3658. }
  3659. return GLib.LogWriterOutput.HANDLED;
  3660. }
  3661. }
  3662. return GLib.LogWriterOutput.UNHANDLED;
  3663. });
  3664. // Global paths
  3665. _data_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_data_dir(), "crown"));
  3666. try {
  3667. _data_dir.make_directory();
  3668. } catch (Error e) {
  3669. /* Nobody cares */
  3670. }
  3671. _config_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_config_dir(), "crown"));
  3672. try {
  3673. _config_dir.make_directory();
  3674. } catch (Error e) {
  3675. /* Nobody cares */
  3676. }
  3677. _cache_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_cache_dir(), "crown"));
  3678. try {
  3679. _cache_dir.make_directory();
  3680. } catch (Error e) {
  3681. /* Nobody cares */
  3682. }
  3683. _logs_dir = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "logs"));
  3684. try {
  3685. _logs_dir.make_directory();
  3686. } catch (Error e) {
  3687. /* Nobody cares */
  3688. }
  3689. _documents_dir = GLib.File.new_for_path(GLib.Environment.get_user_special_dir(GLib.UserDirectory.DOCUMENTS));
  3690. _thumbnails_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_cache_dir(), "thumbnails"));
  3691. try {
  3692. _thumbnails_dir.make_directory();
  3693. } catch (Error e) {
  3694. /* Nobody cares */
  3695. }
  3696. _thumbnails_normal_dir = GLib.File.new_for_path(GLib.Path.build_filename(_thumbnails_dir.get_path(), "normal"));
  3697. try {
  3698. _thumbnails_normal_dir.make_directory();
  3699. } catch (Error e) {
  3700. /* Nobody cares */
  3701. }
  3702. _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"));
  3703. _log_stream = GLib.FileStream.open(_log_file.get_path(), "a");
  3704. if (_log_prefix == "launcher")
  3705. return launcher_main(args);
  3706. _settings_file = GLib.File.new_for_path(GLib.Path.build_filename(_config_dir.get_path(), "settings.sjson"));
  3707. _window_state_file = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "window.sjson"));
  3708. _user_file = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "user.sjson"));
  3709. _console_history_file = GLib.File.new_for_path(GLib.Path.build_filename(_data_dir.get_path(), "console_history.txt"));
  3710. // Connect to SubprocessLauncher service.
  3711. SubprocessLauncher subprocess_launcher;
  3712. try {
  3713. subprocess_launcher = GLib.Bus.get_proxy_sync(GLib.BusType.SESSION
  3714. , "org.crownengine.SubprocessLauncher"
  3715. , "/org/crownengine/subprocess_launcher"
  3716. );
  3717. } catch (IOError e) {
  3718. loge(e.message);
  3719. return 1;
  3720. }
  3721. // Find toolchain path, more desirable paths come first.
  3722. ii = 0;
  3723. string toolchain_paths[] =
  3724. {
  3725. "../../..", // Relative path in release package.
  3726. "../../../samples", // Relative path in git worktree.
  3727. ".",
  3728. };
  3729. for (ii = 0; ii < toolchain_paths.length; ++ii) {
  3730. string path = Path.build_filename(toolchain_paths[ii], "core");
  3731. if (GLib.FileUtils.test(path, FileTest.EXISTS) && GLib.FileUtils.test(path, FileTest.IS_DIR)) {
  3732. _toolchain_dir = File.new_for_path(path).get_parent();
  3733. break;
  3734. }
  3735. }
  3736. if (ii == toolchain_paths.length) {
  3737. loge("Unable to find the toolchain directory");
  3738. return 1;
  3739. }
  3740. // Find templates path, more desirable paths come first.
  3741. string templates_path[] =
  3742. {
  3743. "../../..", // Relative path in release package or git worktree.
  3744. ".",
  3745. };
  3746. for (ii = 0; ii < templates_path.length; ++ii) {
  3747. string path = Path.build_filename(templates_path[ii], "samples");
  3748. if (GLib.FileUtils.test(path, FileTest.EXISTS) && GLib.FileUtils.test(path, FileTest.IS_DIR)) {
  3749. _templates_dir = File.new_for_path(path);
  3750. break;
  3751. }
  3752. }
  3753. if (ii == templates_path.length) {
  3754. loge("Unable to find the templates directory");
  3755. return 1;
  3756. }
  3757. #if CROWN_PLATFORM_LINUX
  3758. Gdk.set_allowed_backends("x11");
  3759. #endif
  3760. LevelEditorApplication app = new LevelEditorApplication(subprocess_launcher);
  3761. return app.run(args);
  3762. }
  3763. } /* namespace Crown */