level_editor.vala 135 KB

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