level_editor.vala 144 KB

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