level_editor.vala 144 KB

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